diff --git a/docs/GENERATORS.md b/docs/GENERATORS.md new file mode 100644 index 00000000..e08da343 --- /dev/null +++ b/docs/GENERATORS.md @@ -0,0 +1,117 @@ +# Test generators + +Test generators allow tracks to generate tests automatically without having to write them ourselves. Each test generator reads from the exercise's `canonical data`, which defines the name of the test, its inputs, and outputs. You can read more about exercism's approach to test suites [here](https://github.com/exercism/problem-specifications#test-data-canonical-datajson). + +Generating tests automatically removes any sort of user error when creating tests. Furthermore, we want the tests to be accurate with respect to its canonical data. Test generation also makes it much easier to keep tests up to date. As the canonical data changes, the tests will be automatically updated when the generator for that test is run. + +An example of a canonical data file can be found [here](https://github.com/exercism/problem-specifications/blob/master/exercises/bob/canonical-data.json) + +## Deploying the generator + +### Creating a project + +1. Open IntelliJ Idea. +2. Click on "New Project". +3. Set name: "TestGeneratorTool". +4. Set desired test generator location +5. Set build system: "Gradle". +6. Set latest JDK and Groovy SDK. +7. Set Gradle DSL: "Groovy". +8. Click "Create". +9. Copy *TestGeneratorTool/src* folder to the project. +10. Copy *TestGeneratorTool/templates* folder to the project. +11. Copy *TestGeneratorTool/build.gradle* file to the project. + +### Adding necessary dependencies + +All necessary dependencies are already added to *TestGeneratorTool/build.gradle* + +Should you run into any problems, search for installation instructions of Spock testing framework on their [official site][spock-framework-official]. + +Search for installation instructions of Picocli framework [here][picocli]. + +### The structure of project + +- TestGeneratorTool/src - source files of test generator +- TestGeneratorTool/templates - templates used to render test class and test methods +- TestGeneratorTool/build.gradle - dependencies of project + +## Usage of test generator + +1. Open project in IntelliJ Idea. +2. Move to *TestGeneratorTool/src/main/groovy/Main.groovy* +3. Create a new run configuration by clicking on green arrow to the left of `static void main`. +4. Edit the configuration: + 1. Find the "Main" confugration on top panel, to the left of green arrow and green bug. + 2. Click on configuration and choose "Edit configurations..." + 3. In the "Program arguments" text box, set location of repository directory and the location on canonical-data.json to parse. + + Here is the example, please edit it to match your actual file system: + + ``` + --repository-directory=C:\Users\Aksima\Exercism\building-exercism\groovy --canonical-data=C:\Users\Aksima\Exercism\building-exercism\canonical-data\groovy\largest-series-product\canonical-data.json + ``` + 4. In the "Working directory" set the path to the project you created for test generator tool. For example, if you created project in + + ``` + C:\Users\Aksima\Exercism\building-exercism\tooling\groovy\generators\TestGeneratorTool + ``` + + ...then you must set the same text in the "Working directory" textbox. + + 5. Click "OK" +5. Everything should be set now! You can generate tests by simply clicking the green arrow on top menu. +6. Do not forget to change *--canonical-data* command line option when you need to generate tests from another *canonical-data.json* file. + +## Contibuting to test generator tool + +These resources may be useful for you if you plan to contibute to test generator tool: + +1. The [documentation][problem-specifications-readme] for problem specifiations. +2. The [schema][canonical-data-definition] for canonical data. +3. Groovy language [official documentation][groovy-docs]. +4. [Parsing and producing JSON][groovy-parsing-json] topic in Groovy language official documentation. +5. [Template engines][groovy-templating] in Groovy +6. An article on [command line builder][command-line-builder] at groovy-lang.org. +7. [Instructions][command-line-parser-annotations] on building command-line parsers using annotations and an interface. +8. [Official page][spock-framework-official] for Spock test framework. +9. [Examples][spock-test-primer] of test cases built on top of Spock framework. +10. [Picocli][picocli] official documentation. + +### Investigating canonical-data.json file structure + +The formal definition of canonical-data.json file can be found [here][canonical-data-definition]. According to that definition, the canonical-data.json file consists of following parts: + +- **exercise** - exercise's slug (kebab-case) - required. +- **comments** - optional. +- **cases** - an array of labeled test items - required. + - **labeledTestItem** - either **labeledTest** or group of description and **cases** defined above. + - **labeledTest** - a single test with following properties: + - **uuid** - a version 4 UUID - required. + - **reimplements** - optional. + - **description** - a short, clear, one-line description - required. + - **comments** - optional. + - **scenarios** - scenarios to include/exclude test cases - optional. + - **property** - letters-only, lowerCamelCase property name - required. + - **input** - the inputs to a test case - required. + - **expected** - the expected return value of a test case - required. + +[problem-specifications-readme]: "The documentation for problem specifiations" + +[canonical-data-definition]: "Formal definition of canonical data (schema)" + +[groovy-docs]: "Groovy language official documentation" + +[groovy-parsing-json]: "Parsing and producing JSON in Groovy" + +[groovy-templating]: "Template engines in Groovy" + +[command-line-builder]: "Builder for command-line interface" + +[command-line-parser-annotations]: "Describe command-line parsers using annotations and an interface" + +[spock-framework-official]: "Official page for Spock test framework" + +[spock-test-primer]: "Examples of test cases built on top of Spock framework" + +[picocli]: "Picocli framework official page" \ No newline at end of file diff --git a/generators/TestGeneratorTool/.gitignore b/generators/TestGeneratorTool/.gitignore new file mode 100644 index 00000000..b63da455 --- /dev/null +++ b/generators/TestGeneratorTool/.gitignore @@ -0,0 +1,42 @@ +.gradle +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ + +### IntelliJ IDEA ### +.idea/modules.xml +.idea/jarRepositories.xml +.idea/compiler.xml +.idea/libraries/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ + +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ + +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ + +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store \ No newline at end of file diff --git a/generators/TestGeneratorTool/build.gradle b/generators/TestGeneratorTool/build.gradle new file mode 100644 index 00000000..afaecb39 --- /dev/null +++ b/generators/TestGeneratorTool/build.gradle @@ -0,0 +1,20 @@ +plugins { + id 'groovy' +} + +group = 'org.example' +version = '1.0-SNAPSHOT' + +repositories { + mavenCentral() +} + +dependencies { + implementation "org.codehaus.groovy:groovy-all:3.0.22" + implementation 'info.picocli:picocli:4.7.6' + testImplementation "org.spockframework:spock-core:2.1-groovy-3.0" +} + +test { + useJUnitPlatform() +} \ No newline at end of file diff --git a/generators/TestGeneratorTool/gradle/wrapper/gradle-wrapper.jar b/generators/TestGeneratorTool/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000..249e5832 Binary files /dev/null and b/generators/TestGeneratorTool/gradle/wrapper/gradle-wrapper.jar differ diff --git a/generators/TestGeneratorTool/gradle/wrapper/gradle-wrapper.properties b/generators/TestGeneratorTool/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000..68630082 --- /dev/null +++ b/generators/TestGeneratorTool/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sat Jul 06 10:42:27 MSK 2024 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.5-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/generators/TestGeneratorTool/gradlew b/generators/TestGeneratorTool/gradlew new file mode 100644 index 00000000..1b6c7873 --- /dev/null +++ b/generators/TestGeneratorTool/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/generators/TestGeneratorTool/gradlew.bat b/generators/TestGeneratorTool/gradlew.bat new file mode 100644 index 00000000..107acd32 --- /dev/null +++ b/generators/TestGeneratorTool/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/generators/TestGeneratorTool/settings.gradle b/generators/TestGeneratorTool/settings.gradle new file mode 100644 index 00000000..b5fcf3b1 --- /dev/null +++ b/generators/TestGeneratorTool/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'TestGeneratorTool' + diff --git a/generators/TestGeneratorTool/src/main/groovy/CanonicalDataParser.groovy b/generators/TestGeneratorTool/src/main/groovy/CanonicalDataParser.groovy new file mode 100644 index 00000000..0e1701ad --- /dev/null +++ b/generators/TestGeneratorTool/src/main/groovy/CanonicalDataParser.groovy @@ -0,0 +1,60 @@ +import groovy.json.JsonSlurper + +/** + * Canonical data parser. + */ +class CanonicalDataParser { + LinkedHashMap specification + + /** + * Parse canonical-data.json. + * @param source The text content of canonical-data.json file. + */ + CanonicalDataParser(String source) { + specification = new JsonSlurper().parseText(source) as LinkedHashMap + } + + /** + * Get exercise slug from parsed data. + * @return Exercise slug. + */ + String getExerciseSlug() { + specification["exercise"] + } + + /** + * Helper function to flatten the nested structure of test cases. + * @param testItems A collection of test cases and test groups. + * @return A collection of test cases as LabeledTestCase objects (test groups are flattened). + */ + ArrayList getTestCasesHelper(ArrayList testItems) { + ArrayList collectedItems = [] + + for (LinkedHashMap labeledTestItem in testItems) { + + // Only test groups contain the 'cases' property. + if (labeledTestItem.containsKey 'cases') { + + // Test groups are handled by recursive call. + collectedItems.addAll(getTestCasesHelper(labeledTestItem['cases'] as ArrayList)) + } else { + + // Standard test case (not a test group). + collectedItems.add(new LabeledTestCase(UUID.fromString(labeledTestItem['uuid'] as String), + labeledTestItem['description'] as String, + labeledTestItem['property'] as String, + labeledTestItem['input'], + labeledTestItem['expected'])) + } + } + collectedItems + } + + /** + * Get collection of test cases as LabeledTestCase objects. + * @return A collection of test cases as LabeledTestCase objects. + */ + ArrayList getLabeledTestCases() { + getTestCasesHelper(specification['cases'] as ArrayList) + } +} diff --git a/generators/TestGeneratorTool/src/main/groovy/Casing.groovy b/generators/TestGeneratorTool/src/main/groovy/Casing.groovy new file mode 100644 index 00000000..b1eccbb7 --- /dev/null +++ b/generators/TestGeneratorTool/src/main/groovy/Casing.groovy @@ -0,0 +1,17 @@ +/** + * Variants of identifier casing. + */ +enum Casing { + + UnknownCase, + + /** + * Each word start with capital letter and continue with lowercase letters. + */ + PascalCase, + + /** + * Each word is delimited by dash (-). + */ + KebabCase +} \ No newline at end of file diff --git a/generators/TestGeneratorTool/src/main/groovy/CommandLineInterface.groovy b/generators/TestGeneratorTool/src/main/groovy/CommandLineInterface.groovy new file mode 100644 index 00000000..6aa57a06 --- /dev/null +++ b/generators/TestGeneratorTool/src/main/groovy/CommandLineInterface.groovy @@ -0,0 +1,31 @@ +import groovy.cli.picocli.CliBuilder + +/** + * Command-line arguments parser. + */ +class CommandLineInterface { + CliBuilder builder + + /** + * Initialize command-line arguments parser. + */ + CommandLineInterface() { + builder = new CliBuilder() + } + + /** + * Parse command-line arguments. + * @param args An array of command-line arguments to parse. + * @return Parsed arguments. + */ + ICommandLineInterface parse(String[] args) { + builder.parseFromSpec ICommandLineInterface, args + } + + /** + * Show program usage. + */ + void showUsage() { + builder.usage() + } +} \ No newline at end of file diff --git a/generators/TestGeneratorTool/src/main/groovy/ICommandLineInterface.groovy b/generators/TestGeneratorTool/src/main/groovy/ICommandLineInterface.groovy new file mode 100644 index 00000000..9ebe88db --- /dev/null +++ b/generators/TestGeneratorTool/src/main/groovy/ICommandLineInterface.groovy @@ -0,0 +1,15 @@ +import groovy.cli.Option + +/** + * Command-line interface. + */ +interface ICommandLineInterface { + @Option(shortName = 'h', description = 'Display usage.') + Boolean help() + + @Option(shortName = 'i', longName = 'canonical-data', description = 'Set path to canonical-data.json file.') + String canonical_data() + + @Option(shortName = 'd', longName = 'repository-directory', description = 'Set path to repository directory.') + String repository_directory() +} \ No newline at end of file diff --git a/generators/TestGeneratorTool/src/main/groovy/Identifier.groovy b/generators/TestGeneratorTool/src/main/groovy/Identifier.groovy new file mode 100644 index 00000000..f8fd94b4 --- /dev/null +++ b/generators/TestGeneratorTool/src/main/groovy/Identifier.groovy @@ -0,0 +1,67 @@ +/** + * An identifier. + */ +class Identifier { + String[] words + + /** + * Store identifier as array of each word in identifier. + * @param words The words which make up an identifier. + */ + private Identifier(String[] words) { + this.words = words + } + + /** + * Create identifier from its string representation, taking into account its casing. + * @param identifier Identifier as string. + * @param casing The casing of identifier. + * @return Parsed identifier. + */ + static Identifier of(String identifier, Casing casing) { + String[] tokens + + switch (casing) { + case Casing.PascalCase: + tokens = (~/[A-Z][a-z]*/) + .matcher(identifier).results() + .map({ it.group() }) + .toArray(String[]::new) + break + + case Casing.KebabCase: + tokens = identifier.split("-") + break + + default: + throw new IllegalArgumentException("Suggested casing not implemented.") + } + + new Identifier(tokens) + } + + /** + * Convert identifier to the specified casing. + * @param casing Desired casing of identifier. + * @return Identifier in the specified casing. + */ + String toCase(Casing casing) { + String result + + switch (casing) { + + case Casing.PascalCase: + result = words.collect({ it[0..<1].toUpperCase() + it[1..-1].toLowerCase() }).join('') + break + + case Casing.KebabCase: + result = words.collect({ it.toLowerCase() }).join('-') + break + + default: + throw new IllegalArgumentException("Suggested casing not implemented.") + } + + result + } +} diff --git a/generators/TestGeneratorTool/src/main/groovy/LabeledTestCase.groovy b/generators/TestGeneratorTool/src/main/groovy/LabeledTestCase.groovy new file mode 100644 index 00000000..88fd3490 --- /dev/null +++ b/generators/TestGeneratorTool/src/main/groovy/LabeledTestCase.groovy @@ -0,0 +1,37 @@ +/** + * A single test with a description. + */ +class LabeledTestCase { + /** + * A version 4 UUID (compliant with RFC 4122) in the canonical textual representation. + */ + UUID identifier + + /** + * Description of test case. + */ + String description + + /** + * Property to test. + */ + String property + + /** + * Suggested inputs. + */ + Object input + + /** + * Expected answer. + */ + Object expected + + LabeledTestCase(UUID identifier, String description, String property, Object input, Object expected) { + this.identifier = identifier + this.description = description + this.property = property + this.input = input + this.expected = expected + } +} diff --git a/generators/TestGeneratorTool/src/main/groovy/Main.groovy b/generators/TestGeneratorTool/src/main/groovy/Main.groovy new file mode 100644 index 00000000..35b064a9 --- /dev/null +++ b/generators/TestGeneratorTool/src/main/groovy/Main.groovy @@ -0,0 +1,42 @@ +import java.nio.file.Files +import java.nio.file.Path + +static void main(String[] args) { + CommandLineInterface commandLineInterface = new CommandLineInterface() + ICommandLineInterface options = commandLineInterface.parse args + + // User requested usage summary. + if (options.help()) { + commandLineInterface.showUsage() + return + } + + // Getting path to canonical data and repository directory. + String canonical_data = options.canonical_data() + if (canonical_data == null) { + println 'Path to canonical-data.json not set.' + return + } + String repository_directory = options.repository_directory() + if (repository_directory == null) { + println 'Path to repository directory not set.' + return + } + + // Parsing canonical data. + CanonicalDataParser specification = new CanonicalDataParser(Files.readString(Path.of(canonical_data))) + String exerciseSlug = specification.exerciseSlug + String exerciseName = Identifier.of(exerciseSlug, Casing.KebabCase).toCase(Casing.PascalCase) + + // Checking tests.toml for excluded tests. + Path testConfigurationPath = Path.of(repository_directory, 'exercises', 'practice', exerciseSlug, '.meta', 'tests.toml') + Set excludedTests = TestConfigurationParser.findExcludedTests(Files.readString(testConfigurationPath)) + + // Rendering tests. + String renderedTests = TestCasesRenderer.render(specification, excludedTests) + + // Writing rendered tests to file. + Path testFilePath = Path.of(repository_directory, 'exercises', 'practice', exerciseSlug, 'src', 'test', 'groovy', exerciseName + 'Spec.groovy') + Files.writeString(testFilePath, renderedTests) + println "Tests are written to " + testFilePath.toString() +} diff --git a/generators/TestGeneratorTool/src/main/groovy/TestCasesRenderer.groovy b/generators/TestGeneratorTool/src/main/groovy/TestCasesRenderer.groovy new file mode 100644 index 00000000..598e884d --- /dev/null +++ b/generators/TestGeneratorTool/src/main/groovy/TestCasesRenderer.groovy @@ -0,0 +1,156 @@ +import groovy.json.JsonOutput +import groovy.text.SimpleTemplateEngine +import groovy.text.Template + +import java.nio.file.Files +import java.nio.file.Path + +/** + * Renderer of test cases. + */ +class TestCasesRenderer { + + /** + * Render all test cases inside a test class. + * @param specification A parsed specification of tests (from canonical-data.json). + * @param excludedTests A set of tests excluded in tests.toml file. + * @return Rendered test cases. + */ + static String render(CanonicalDataParser specification, Set excludedTests) { + String exerciseName = Identifier.of(specification.exerciseSlug, Casing.KebabCase).toCase(Casing.PascalCase) + + Template testClassTemplate, testMethodTemplate, testErrorTemplate + (testClassTemplate, testMethodTemplate, testErrorTemplate) = loadTemplates() + + // Do not add @Ignore attribute to the first test. + boolean ignore = false + + ArrayList testMethods = [] + for (labeledTestCase in specification.labeledTestCases) { + + // Prepare the rendering of method. + String preparedMethod = renderMethod( + exerciseName, + labeledTestCase, + testMethodTemplate, + testErrorTemplate, + ignore) + + // Comment out the rendered method if it + // should not be included according to tests.toml file. + // + // As per https://github.com/exercism/problem-specifications/blob/main/README.md: + // Track generators should not automatically select the "latest" version + // of a test case by looking at the "reimplements" hierarchy. We recommend + // each track to make this a manual action, as the re-implemented test case + // might actually make less sense for a track. + // + // According to this, we cannot just delete the excluded exercise, + // all we can do is to comment it out, leaving the final decision + // to the exercise author and maintainers. + if (excludedTests.contains(labeledTestCase.identifier)) { + preparedMethod = commentOut(preparedMethod) + } + + // Add rendered method to the list of methods + // which will be rendered inside test class. + testMethods.add(preparedMethod) + + // Use @Ignore attribute for all tests after the first one. + ignore = true + } + + // Render the test class. + testClassTemplate.make([ + exerciseName: exerciseName, + testMethods : testMethods + ]).toString() + } + + /** + * Render a single test method. + * @param exerciseName The name of exercise for which test method is rendered. + * @param labeledTestCase Test case to be rendered. + * @param testMethodTemplate Regular test method template. + * @param testErrorTemplate Template for checking the existence and contents of error. + * @param ignore Should the rendered method have the @Ignore attribute? + * @return Rendered test method. + */ + static String renderMethod( + String exerciseName, + LabeledTestCase labeledTestCase, + Template testMethodTemplate, + Template testErrorTemplate, + boolean ignore + ) { + // Convert the names of arguments and their values to string representation. + LinkedHashMap arguments = labeledTestCase.input as LinkedHashMap + ArrayList argumentNames = new ArrayList<>(arguments.keySet()) + ArrayList argumentValues = arguments.values().collect({ JsonOutput.toJson(it) }) + + // Prepare the list of argument names used in property call. + String commaSeparatedArgumentNames = argumentNames.join(', ') + + // Calculate column widths for data tables. + ArrayList columnWidths = [] + for (i in 0.. name.padRight(columnWidths[index]) }) + .join(' | ') + + // Pad values to column widths and join them using pipe. + String pipeSeparatedArgumentValues = + argumentValues + .withIndex() + .collect({ String value, Integer index -> value.padRight(columnWidths[index]) }) + .join(' | ') + + // Check what template we should use: a regular test method template, + // or a template to test property call which should throw an error. + boolean useErrorCheckTemplate = + labeledTestCase.expected instanceof Map + && (labeledTestCase.expected as LinkedHashMap).containsKey('error') + + // Render the corresponding template. + Object expected = useErrorCheckTemplate ? labeledTestCase.expected['error'] : labeledTestCase.expected + (useErrorCheckTemplate ? testErrorTemplate : testMethodTemplate).make([ + ignore : ignore, + description : labeledTestCase.description, + exerciseName : exerciseName, + property : labeledTestCase.property, + commaSeparatedArgumentNames: commaSeparatedArgumentNames, + pipeSeparatedArgumentNames : pipeSeparatedArgumentNames, + pipeSeparatedArgumentValues: pipeSeparatedArgumentValues, + expected : JsonOutput.toJson(expected) + ]).toString() + } + + /** + * Load templates from filesystem. + * @return Retrieved templates. + */ + static ArrayList