diff --git a/README.md b/README.md index 34cfaffe3..ff60e3760 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Next to the exercises, the Java track also consists of the following tooling: - [exercism/java-test-runner] - The Exercism [test runner][docs-test-runners] for the Java track that automatically verifies if a submitted solution passes all of the exercise's tests. - [exercism/java-representer] - The Exercism [representer][docs-representers] for the Java track that creates normalized representations of submitted solutions. - [exercism/java-analyzer] - The Exercism [analyzer][docs-analyzers] for the Java track that automatically provides comments on submitted solutions. +- [test-generator](test-generator) - Tool to generate JUnit 5 practice exercise test suites from canonical data. ## Contributing Guide diff --git a/bin/generate-tests b/bin/generate-tests new file mode 100644 index 000000000..4414334ec --- /dev/null +++ b/bin/generate-tests @@ -0,0 +1,22 @@ +#!/usr/bin/env bash +set -eo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)" + +# Default to --help if no arguments provided +if [ $# -eq 0 ]; then + ARGS="--help" +else + ARGS="$*" +fi + +INSTALLED_APP="$REPO_ROOT/test-generator/build/install/test-generator/bin/test-generator" + +# If not installed yet, build the distribution once +if [ ! -f "$INSTALLED_APP" ]; then + "$REPO_ROOT/test-generator/gradlew" -p "$REPO_ROOT/test-generator" installDist --quiet +fi + +# Run pre-compiled binary directly (instant startup, zero Gradle daemon overhead!) +"$INSTALLED_APP" $ARGS diff --git a/exercises/practice/acronym/.meta/template.hbs b/exercises/practice/acronym/.meta/template.hbs new file mode 100644 index 000000000..71aa6ea37 --- /dev/null +++ b/exercises/practice/acronym/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + @DisplayName("{{{description}}}") + public void {{methodName}}() { + assertThat(new Acronym({{{formattedInputs.phrase}}}).get()) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/affine-cipher/.meta/template.hbs b/exercises/practice/affine-cipher/.meta/template.hbs new file mode 100644 index 000000000..3ceb2e961 --- /dev/null +++ b/exercises/practice/affine-cipher/.meta/template.hbs @@ -0,0 +1,31 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class AffineCipherTest { + + private AffineCipher affineCipher = new AffineCipher(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> affineCipher.{{rawCase.property}}( + "{{{escapeJava rawCase.input.phrase}}}", {{rawCase.input.key.a}}, {{rawCase.input.key.b}})) + .withMessage("Error: keyA and alphabet size must be coprime."); + {{else}} + assertThat(affineCipher.{{rawCase.property}}( + "{{{escapeJava rawCase.input.phrase}}}", {{rawCase.input.key.a}}, {{rawCase.input.key.b}})) + .isEqualTo({{{expectedValue}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/all-your-base/.meta/template.hbs b/exercises/practice/all-your-base/.meta/template.hbs new file mode 100644 index 000000000..739b39ded --- /dev/null +++ b/exercises/practice/all-your-base/.meta/template.hbs @@ -0,0 +1,29 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class BaseConverterTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new BaseConverter({{{formattedInputs.inputBase}}}, {{{asIntArray rawCase.input.digits}}}) + .convertToBase({{{formattedInputs.outputBase}}})) + .withMessage("{{{allYourBaseErrorMessage this}}}"); + {{else}} + assertThat(new BaseConverter({{{formattedInputs.inputBase}}}, {{{asIntArray rawCase.input.digits}}}) + .convertToBase({{{formattedInputs.outputBase}}})) + .containsExactly({{{formatElements rawCase.expected}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/allergies/.meta/template.hbs b/exercises/practice/allergies/.meta/template.hbs new file mode 100644 index 000000000..2e379f9b8 --- /dev/null +++ b/exercises/practice/allergies/.meta/template.hbs @@ -0,0 +1,30 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class AllergiesTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "allergicTo")~}} + assertThat(new Allergies({{{formattedInputs.score}}}).isAllergicTo({{toAllergen inputNodes.item}})) + .{{#if (eq expectedValue "true")}}isTrue(){{else}}isFalse(){{/if}}; + {{~else~}} + {{#if (eq rawCase.expected.size 0)~}} + assertThat(new Allergies({{{formattedInputs.score}}}).getList()) + .isEmpty(); + {{~else~}} + assertThat(new Allergies({{{formattedInputs.score}}}).getList()) + .containsExactly({{{asAllergens rawCase.expected}}}); + {{~/if}} + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/alphametics/.meta/template.hbs b/exercises/practice/alphametics/.meta/template.hbs new file mode 100644 index 000000000..038d37230 --- /dev/null +++ b/exercises/practice/alphametics/.meta/template.hbs @@ -0,0 +1,29 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static java.util.Map.entry; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class AlphameticsTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() throws UnsolvablePuzzleException { + {{#if isNullExpected}} + assertThatExceptionOfType(UnsolvablePuzzleException.class) + .isThrownBy(() -> new Alphametics({{{alphameticsPuzzle rawCase.input.puzzle}}}).solve()); + {{else}} + assertThat(new Alphametics({{{alphameticsPuzzle rawCase.input.puzzle}}}).solve()) + .isEqualTo({{{formatAlphameticsExpected rawCase.expected}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/anagram/.meta/template.hbs b/exercises/practice/anagram/.meta/template.hbs new file mode 100644 index 000000000..018e5538f --- /dev/null +++ b/exercises/practice/anagram/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class AnagramTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new Anagram({{{formattedInputs.subject}}}).match({{{formattedInputs.candidates}}})) + .containsExactlyInAnyOrderElementsOf({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/baffling-birthdays/.meta/template.hbs b/exercises/practice/baffling-birthdays/.meta/template.hbs new file mode 100644 index 000000000..e2f511b35 --- /dev/null +++ b/exercises/practice/baffling-birthdays/.meta/template.hbs @@ -0,0 +1,53 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; + +public class BafflingBirthdaysTest { + + private BafflingBirthdays birthdays = new BafflingBirthdays(); + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq rawCase.property "sharedBirthday")}} + List birthdates = {{{asLocalDateList rawCase.input.birthdates}}}; + {{#if (eq rawCase.expected true)}} + assertThat(birthdays.sharedBirthday(birthdates)).isTrue(); + {{else}} + assertThat(birthdays.sharedBirthday(birthdates)).isFalse(); + {{/if}} + {{else if (eq rawCase.property "randomBirthdates")}} + {{#if rawCase.expected.years}} + assertThat(birthdays.randomBirthdates(100)).noneMatch(LocalDate::isLeapYear); + {{else if rawCase.expected.months}} + assertThat(birthdays.randomBirthdates(500).stream().map(LocalDate::getMonth).distinct()) + .hasSizeGreaterThanOrEqualTo(7); + {{else if rawCase.expected.days}} + assertThat(birthdays.randomBirthdates(500).stream().map(LocalDate::getDayOfMonth).distinct()) + .hasSizeGreaterThanOrEqualTo(11); + {{else}} + int groupSize = 50; + assertThat(birthdays.randomBirthdates(groupSize).size()).isEqualTo(groupSize); + {{/if}} + {{else if (eq rawCase.property "estimatedProbabilityOfSharedBirthday")}} + {{#if (eq rawCase.expected 0.0)}} + assertThat(birthdays.estimatedProbabilityOfSharedBirthday({{rawCase.input.groupSize}})) + .isEqualTo(0.0); + {{else}} + assertThat(birthdays.estimatedProbabilityOfSharedBirthday({{rawCase.input.groupSize}})) + .isCloseTo({{rawCase.expected}}, offset(1.0)); + {{/if}} + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/bank-account/.meta/template.hbs b/exercises/practice/bank-account/.meta/template.hbs new file mode 100644 index 000000000..24b673cdb --- /dev/null +++ b/exercises/practice/bank-account/.meta/template.hbs @@ -0,0 +1,23 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Random; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.assertj.core.api.Assertions.fail; + +public class BankAccountTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() throws Exception { + {{{renderBankAccountCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/binary-search-tree/.meta/template.hbs b/exercises/practice/binary-search-tree/.meta/template.hbs new file mode 100644 index 000000000..ecadffabb --- /dev/null +++ b/exercises/practice/binary-search-tree/.meta/template.hbs @@ -0,0 +1,21 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BinarySearchTreeTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderBinarySearchTreeCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/binary-search/.meta/template.hbs b/exercises/practice/binary-search/.meta/template.hbs new file mode 100644 index 000000000..c50df867d --- /dev/null +++ b/exercises/practice/binary-search/.meta/template.hbs @@ -0,0 +1,31 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class BinarySearchTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() throws ValueNotFoundException { + {{#if expectedError}} + assertThatExceptionOfType(ValueNotFoundException.class) + .isThrownBy(() -> new BinarySearch({{{formattedInputs.array}}}) + .indexOf({{{formattedInputs.value}}})) + .withMessage("Value not in array"); + {{else}} + assertThat(new BinarySearch({{{formattedInputs.array}}}) + .indexOf({{{formattedInputs.value}}})) + .isEqualTo({{{expectedValue}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/bob/.meta/template.hbs b/exercises/practice/bob/.meta/template.hbs new file mode 100644 index 000000000..d313aa26c --- /dev/null +++ b/exercises/practice/bob/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BobTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new Bob().hey({{{formattedInputs.heyBob}}})) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/book-store/.meta/template.hbs b/exercises/practice/book-store/.meta/template.hbs new file mode 100644 index 000000000..6bc452e1a --- /dev/null +++ b/exercises/practice/book-store/.meta/template.hbs @@ -0,0 +1,33 @@ +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; + +public class {{testClassName}} { + + // A 0.01 tolerance covers minor rounding variations in floating point calculations + private static final double EQUALITY_TOLERANCE = 0.01; + + private BookStore bookStore; + + @BeforeEach + public void setUp() { + bookStore = new BookStore(); + } +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderBookStoreCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/bottle-song/.meta/template.hbs b/exercises/practice/bottle-song/.meta/template.hbs new file mode 100644 index 000000000..0ca63ef99 --- /dev/null +++ b/exercises/practice/bottle-song/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BottleSongTest { + + private BottleSong bottleSong = new BottleSong(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(bottleSong.recite({{{formattedInputs.startBottles}}}, {{{formattedInputs.takeDown}}})) + .isEqualTo({{{bottleSongExpected rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/bowling/.meta/template.hbs b/exercises/practice/bowling/.meta/template.hbs new file mode 100644 index 000000000..e3a6211ff --- /dev/null +++ b/exercises/practice/bowling/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class BowlingGameTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderBowlingCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/camicia/.meta/template.hbs b/exercises/practice/camicia/.meta/template.hbs new file mode 100644 index 000000000..607692cc7 --- /dev/null +++ b/exercises/practice/camicia/.meta/template.hbs @@ -0,0 +1,28 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CamiciaTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + List playerA = {{{asCamiciaCards rawCase.input.playerA}}}; + List playerB = {{{asCamiciaCards rawCase.input.playerB}}}; + + CamiciaResult result = Camicia.simulateGame(playerA, playerB); + + assertThat(result.status()).isEqualTo("{{{escapeJava rawCase.expected.status}}}"); + assertThat(result.cards()).isEqualTo({{{rawCase.expected.cards}}}); + assertThat(result.tricks()).isEqualTo({{{rawCase.expected.tricks}}}); + } +{{/each}} +} diff --git a/exercises/practice/change/.meta/template.hbs b/exercises/practice/change/.meta/template.hbs new file mode 100644 index 000000000..0a687bd54 --- /dev/null +++ b/exercises/practice/change/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + + +import static java.util.Arrays.asList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderChangeCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/circular-buffer/.meta/template.hbs b/exercises/practice/circular-buffer/.meta/template.hbs new file mode 100644 index 000000000..8066da47f --- /dev/null +++ b/exercises/practice/circular-buffer/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() throws BufferIOException { + {{{renderCircularBufferCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/clock/.meta/config.json b/exercises/practice/clock/.meta/config.json index 4f093f4b8..a24cedf7c 100644 --- a/exercises/practice/clock/.meta/config.json +++ b/exercises/practice/clock/.meta/config.json @@ -26,9 +26,7 @@ "src/main/java/Clock.java" ], "test": [ - "src/test/java/ClockAddTest.java", - "src/test/java/ClockCreationTest.java", - "src/test/java/ClockEqualTest.java" + "src/test/java/ClockTest.java" ], "example": [ ".meta/src/reference/java/Clock.java" diff --git a/exercises/practice/clock/.meta/template.hbs b/exercises/practice/clock/.meta/template.hbs new file mode 100644 index 000000000..99c74cc4d --- /dev/null +++ b/exercises/practice/clock/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ClockTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderClockCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/clock/src/test/java/ClockAddTest.java b/exercises/practice/clock/src/test/java/ClockAddTest.java deleted file mode 100644 index 1a82b687e..000000000 --- a/exercises/practice/clock/src/test/java/ClockAddTest.java +++ /dev/null @@ -1,168 +0,0 @@ -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ClockAddTest { - - @Disabled("Remove to run test") - @Test - @DisplayName("add minutes") - public void addMinutes() { - Clock clock = new Clock(10, 0); - clock.add(3); - - assertThat(clock.toString()).isEqualTo("10:03"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("add no minutes") - public void addNoMinutes() { - Clock clock = new Clock(6, 41); - clock.add(0); - - assertThat(clock.toString()).isEqualTo("06:41"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("add to next hour") - public void addToNextHour() { - Clock clock = new Clock(0, 45); - clock.add(40); - - assertThat(clock.toString()).isEqualTo("01:25"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("add more than one hour") - public void addMoreThanOneHour() { - Clock clock = new Clock(10, 0); - clock.add(61); - - assertThat(clock.toString()).isEqualTo("11:01"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("add more than two hours with carry") - public void addMoreThanTwoHoursWithCarry() { - Clock clock = new Clock(0, 45); - clock.add(160); - - assertThat(clock.toString()).isEqualTo("03:25"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("add across midnight") - public void addAcrossMidnight() { - Clock clock = new Clock(23, 59); - clock.add(2); - - assertThat(clock.toString()).isEqualTo("00:01"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("add more than one day (1500 min = 25 hrs)") - public void addMoreThanOneDay() { - Clock clock = new Clock(5, 32); - clock.add(1500); - - assertThat(clock.toString()).isEqualTo("06:32"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("add more than two days") - public void addMoreThanTwoDays() { - Clock clock = new Clock(1, 1); - clock.add(3500); - - assertThat(clock.toString()).isEqualTo("11:21"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("subtract minutes") - public void subtractMinutes() { - Clock clock = new Clock(10, 3); - clock.add(-3); - - assertThat(clock.toString()).isEqualTo("10:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("subtract to previous hour") - public void subtractToPreviousHour() { - Clock clock = new Clock(10, 3); - clock.add(-30); - - assertThat(clock.toString()).isEqualTo("09:33"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("subtract more than an hour") - public void subtractMoreThanAnHour() { - Clock clock = new Clock(10, 3); - clock.add(-70); - - assertThat(clock.toString()).isEqualTo("08:53"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("subtract across midnight") - public void subtractAcrossMidnight() { - Clock clock = new Clock(0, 3); - clock.add(-4); - - assertThat(clock.toString()).isEqualTo("23:59"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("subtract more than two hours") - public void subtractMoreThanTwoHours() { - Clock clock = new Clock(0, 0); - clock.add(-160); - - assertThat(clock.toString()).isEqualTo("21:20"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("subtract more than two hours with borrow") - public void subtractMoreThanTwoHoursWithBorrow() { - Clock clock = new Clock(6, 15); - clock.add(-160); - - assertThat(clock.toString()).isEqualTo("03:35"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("subtract more than one day (1500 min = 25 hrs)") - public void subtractMoreThanOneDay() { - Clock clock = new Clock(5, 32); - clock.add(-1500); - - assertThat(clock.toString()).isEqualTo("04:32"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("subtract more than two days") - public void subtractMoreThanTwoDays() { - Clock clock = new Clock(2, 20); - clock.add(-3000); - - assertThat(clock.toString()).isEqualTo("00:20"); - } -} diff --git a/exercises/practice/clock/src/test/java/ClockCreationTest.java b/exercises/practice/clock/src/test/java/ClockCreationTest.java deleted file mode 100644 index 674d1fee7..000000000 --- a/exercises/practice/clock/src/test/java/ClockCreationTest.java +++ /dev/null @@ -1,147 +0,0 @@ -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ClockCreationTest { - - @Test - @DisplayName("on the hour") - public void canPrintTimeOnTheHour() { - assertThat(new Clock(8, 0).toString()).isEqualTo("08:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("past the hour") - public void canPrintTimeWithMinutes() { - assertThat(new Clock(11, 9).toString()).isEqualTo("11:09"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("midnight is zero hours") - public void midnightPrintsAsZero() { - assertThat(new Clock(24, 0).toString()).isEqualTo("00:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("hour rolls over") - public void hourRollsOver() { - assertThat(new Clock(25, 0).toString()).isEqualTo("01:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("hour rolls over continuously") - public void hourRollsOverContinuously() { - assertThat(new Clock(100, 0).toString()).isEqualTo("04:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("sixty minutes is next hour") - public void sixtyMinutesIsNextHour() { - assertThat(new Clock(1, 60).toString()).isEqualTo("02:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("minutes roll over") - public void minutesRollOver() { - assertThat(new Clock(0, 160).toString()).isEqualTo("02:40"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("minutes roll over continuously") - public void minutesRollOverContinuously() { - assertThat(new Clock(0, 1723).toString()).isEqualTo("04:43"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("hour and minutes roll over") - public void hourAndMinutesRollOver() { - assertThat(new Clock(25, 160).toString()).isEqualTo("03:40"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("hour and minutes roll over continuously") - public void hourAndMinutesRollOverContinuously() { - assertThat(new Clock(201, 3001).toString()).isEqualTo("11:01"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("hour and minutes roll over to exactly midnight") - public void hourAndMinutesRollOverToExactlyMidnight() { - assertThat(new Clock(72, 8640).toString()).isEqualTo("00:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative hour") - public void negativeHour() { - assertThat(new Clock(-1, 15).toString()).isEqualTo("23:15"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative hour rolls over") - public void negativeHourRollsOver() { - assertThat(new Clock(-25, 0).toString()).isEqualTo("23:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative hour rolls over continuously") - public void negativeHourRollsOverContinuously() { - assertThat(new Clock(-91, 0).toString()).isEqualTo("05:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative minutes") - public void negativeMinutes() { - assertThat(new Clock(1, -40).toString()).isEqualTo("00:20"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative minutes roll over") - public void negativeMinutesRollOver() { - assertThat(new Clock(1, -160).toString()).isEqualTo("22:20"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative minutes roll over continuously") - public void negativeMinutesRollOverContinuously() { - assertThat(new Clock(1, -4820).toString()).isEqualTo("16:40"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative sixty minutes is previous hour") - public void negativeSixtyMinutesIsPreviousHour() { - assertThat(new Clock(2, -60).toString()).isEqualTo("01:00"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative hour and minutes both roll over") - public void negativeHourAndMinutesBothRollOver() { - assertThat(new Clock(-25, -160).toString()).isEqualTo("20:20"); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("negative hour and minutes both roll over continuously") - public void negativeHourAndMinutesBothRollOverContinuously() { - assertThat(new Clock(-121, -5810).toString()).isEqualTo("22:10"); - } -} diff --git a/exercises/practice/clock/src/test/java/ClockEqualTest.java b/exercises/practice/clock/src/test/java/ClockEqualTest.java deleted file mode 100644 index d73687773..000000000 --- a/exercises/practice/clock/src/test/java/ClockEqualTest.java +++ /dev/null @@ -1,137 +0,0 @@ -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class ClockEqualTest { - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with same time") - public void clocksWithSameTimeAreEqual() { - assertThat(new Clock(15, 37)) - .isEqualTo(new Clock(15, 37)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks a minute apart") - public void clocksAMinuteApartAreNotEqual() { - assertThat(new Clock(15, 36)) - .isNotEqualTo(new Clock(15, 37)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks an hour apart") - public void clocksAnHourApartAreNotEqual() { - assertThat(new Clock(14, 37)) - .isNotEqualTo(new Clock(15, 37)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with hour overflow") - public void clocksWithHourOverflow() { - assertThat(new Clock(34, 37)) - .isEqualTo(new Clock(10, 37)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with hour overflow by several days") - public void clocksWithHourOverflowBySeveralDays() { - assertThat(new Clock(99, 11)) - .isEqualTo(new Clock(3, 11)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with negative hour") - public void clocksWithNegateHour() { - assertThat(new Clock(-2, 40)) - .isEqualTo(new Clock(22, 40)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with negative hour that wraps") - public void clocksWithNegativeHourThatWraps() { - assertThat(new Clock(-31, 3)) - .isEqualTo(new Clock(17, 3)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with negative hour that wraps multiple times") - public void clocksWithNegativeHourThatWrapsMultipleTimes() { - assertThat(new Clock(-83, 49)) - .isEqualTo(new Clock(13, 49)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with minute overflow") - public void clocksWithMinuteOverflow() { - assertThat(new Clock(0, 1441)) - .isEqualTo(new Clock(0, 1)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with minute overflow by several days") - public void clocksWithMinuteOverflowBySeveralDays() { - assertThat(new Clock(2, 4322)) - .isEqualTo(new Clock(2, 2)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with negative minute") - public void clocksWithNegativeMinutes() { - assertThat(new Clock(3, -20)) - .isEqualTo(new Clock(2, 40)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with negative minute that wraps") - public void clocksWithNegativeMinutesThatWraps() { - assertThat(new Clock(5, -1490)) - .isEqualTo(new Clock(4, 10)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with negative minute that wraps multiple times") - public void clocksWithNegativeMinutesThatWrapsMultipleTimes() { - assertThat(new Clock(6, -4305)) - .isEqualTo(new Clock(6, 15)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with negative hours and minutes") - public void clocksWithNegativeHoursAndMinutes() { - assertThat(new Clock(-12, -268)) - .isEqualTo(new Clock(7, 32)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("clocks with negative hours and minutes that wrap") - public void clocksWithNegativeHoursAndMinutesThatWrap() { - assertThat(new Clock(-54, -11513)) - .isEqualTo(new Clock(18, 7)); - } - - @Disabled("Remove to run test") - @Test - @DisplayName("full clock and zeroed clock") - public void clocksWithFullClockAndZeroedClockAreEqual() { - assertThat(new Clock(24, 0)) - .isEqualTo(new Clock(0, 0)); - } - -} diff --git a/exercises/practice/clock/src/test/java/ClockTest.java b/exercises/practice/clock/src/test/java/ClockTest.java new file mode 100644 index 000000000..c78694e0c --- /dev/null +++ b/exercises/practice/clock/src/test/java/ClockTest.java @@ -0,0 +1,440 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ClockTest { + + @Test + @DisplayName("Create a new clock with an initial time -> on the hour") + public void createANewClockWithAnInitialTimeOnTheHour() { + assertThat(new Clock(8, 0).toString()).isEqualTo("08:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> past the hour") + public void createANewClockWithAnInitialTimePastTheHour() { + assertThat(new Clock(11, 9).toString()).isEqualTo("11:09"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> midnight is zero hours") + public void createANewClockWithAnInitialTimeMidnightIsZeroHours() { + assertThat(new Clock(24, 0).toString()).isEqualTo("00:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> hour rolls over") + public void createANewClockWithAnInitialTimeHourRollsOver() { + assertThat(new Clock(25, 0).toString()).isEqualTo("01:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> hour rolls over continuously") + public void createANewClockWithAnInitialTimeHourRollsOverContinuously() { + assertThat(new Clock(100, 0).toString()).isEqualTo("04:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> sixty minutes is next hour") + public void createANewClockWithAnInitialTimeSixtyMinutesIsNextHour() { + assertThat(new Clock(1, 60).toString()).isEqualTo("02:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> minutes roll over") + public void createANewClockWithAnInitialTimeMinutesRollOver() { + assertThat(new Clock(0, 160).toString()).isEqualTo("02:40"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> minutes roll over continuously") + public void createANewClockWithAnInitialTimeMinutesRollOverContinuously() { + assertThat(new Clock(0, 1723).toString()).isEqualTo("04:43"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> hour and minutes roll over") + public void createANewClockWithAnInitialTimeHourAndMinutesRollOver() { + assertThat(new Clock(25, 160).toString()).isEqualTo("03:40"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> hour and minutes roll over continuously") + public void createANewClockWithAnInitialTimeHourAndMinutesRollOverContinuousl() { + assertThat(new Clock(201, 3001).toString()).isEqualTo("11:01"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> hour and minutes roll over " + + "to exactly midnight") + public void createANewClockWithAnInitialTimeHourAndMinutesRollOverToExactlyMi() { + assertThat(new Clock(72, 8640).toString()).isEqualTo("00:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative hour") + public void createANewClockWithAnInitialTimeNegativeHour() { + assertThat(new Clock(-1, 15).toString()).isEqualTo("23:15"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative hour rolls over") + public void createANewClockWithAnInitialTimeNegativeHourRollsOver() { + assertThat(new Clock(-25, 0).toString()).isEqualTo("23:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative hour rolls over continuously") + public void createANewClockWithAnInitialTimeNegativeHourRollsOverContinuously() { + assertThat(new Clock(-91, 0).toString()).isEqualTo("05:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative minutes") + public void createANewClockWithAnInitialTimeNegativeMinutes() { + assertThat(new Clock(1, -40).toString()).isEqualTo("00:20"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative minutes roll over") + public void createANewClockWithAnInitialTimeNegativeMinutesRollOver() { + assertThat(new Clock(1, -160).toString()).isEqualTo("22:20"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative minutes roll over continuously") + public void createANewClockWithAnInitialTimeNegativeMinutesRollOverContinuous() { + assertThat(new Clock(1, -4820).toString()).isEqualTo("16:40"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative sixty minutes is previous hour") + public void createANewClockWithAnInitialTimeNegativeSixtyMinutesIsPreviousHou() { + assertThat(new Clock(2, -60).toString()).isEqualTo("01:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative hour and minutes both roll over") + public void createANewClockWithAnInitialTimeNegativeHourAndMinutesBothRollOve() { + assertThat(new Clock(-25, -160).toString()).isEqualTo("20:20"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Create a new clock with an initial time -> negative hour and minutes " + + "both roll over continuously") + public void createANewClockWithAnInitialTimeNegativeHourAndMinutesBothRollOve2() { + assertThat(new Clock(-121, -5810).toString()).isEqualTo("22:10"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Add minutes -> add minutes") + public void addMinutesAddMinutes() { + Clock clock = new Clock(10, 0); + clock.add(3); + assertThat(clock.toString()).isEqualTo("10:03"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Add minutes -> add no minutes") + public void addMinutesAddNoMinutes() { + Clock clock = new Clock(6, 41); + clock.add(0); + assertThat(clock.toString()).isEqualTo("06:41"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Add minutes -> add to next hour") + public void addMinutesAddToNextHour() { + Clock clock = new Clock(0, 45); + clock.add(40); + assertThat(clock.toString()).isEqualTo("01:25"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Add minutes -> add more than one hour") + public void addMinutesAddMoreThanOneHour() { + Clock clock = new Clock(10, 0); + clock.add(61); + assertThat(clock.toString()).isEqualTo("11:01"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Add minutes -> add more than two hours with carry") + public void addMinutesAddMoreThanTwoHoursWithCarry() { + Clock clock = new Clock(0, 45); + clock.add(160); + assertThat(clock.toString()).isEqualTo("03:25"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Add minutes -> add across midnight") + public void addMinutesAddAcrossMidnight() { + Clock clock = new Clock(23, 59); + clock.add(2); + assertThat(clock.toString()).isEqualTo("00:01"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Add minutes -> add more than one day (1500 min = 25 hrs)") + public void addMinutesAddMoreThanOneDay1500Min25Hrs() { + Clock clock = new Clock(5, 32); + clock.add(1500); + assertThat(clock.toString()).isEqualTo("06:32"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Add minutes -> add more than two days") + public void addMinutesAddMoreThanTwoDays() { + Clock clock = new Clock(1, 1); + clock.add(3500); + assertThat(clock.toString()).isEqualTo("11:21"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Subtract minutes -> subtract minutes") + public void subtractMinutesSubtractMinutes() { + Clock clock = new Clock(10, 3); + clock.add(-3); + assertThat(clock.toString()).isEqualTo("10:00"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Subtract minutes -> subtract to previous hour") + public void subtractMinutesSubtractToPreviousHour() { + Clock clock = new Clock(10, 3); + clock.add(-30); + assertThat(clock.toString()).isEqualTo("09:33"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Subtract minutes -> subtract more than an hour") + public void subtractMinutesSubtractMoreThanAnHour() { + Clock clock = new Clock(10, 3); + clock.add(-70); + assertThat(clock.toString()).isEqualTo("08:53"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Subtract minutes -> subtract across midnight") + public void subtractMinutesSubtractAcrossMidnight() { + Clock clock = new Clock(0, 3); + clock.add(-4); + assertThat(clock.toString()).isEqualTo("23:59"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Subtract minutes -> subtract more than two hours") + public void subtractMinutesSubtractMoreThanTwoHours() { + Clock clock = new Clock(0, 0); + clock.add(-160); + assertThat(clock.toString()).isEqualTo("21:20"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Subtract minutes -> subtract more than two hours with borrow") + public void subtractMinutesSubtractMoreThanTwoHoursWithBorrow() { + Clock clock = new Clock(6, 15); + clock.add(-160); + assertThat(clock.toString()).isEqualTo("03:35"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Subtract minutes -> subtract more than one day (1500 min = 25 hrs)") + public void subtractMinutesSubtractMoreThanOneDay1500Min25Hrs() { + Clock clock = new Clock(5, 32); + clock.add(-1500); + assertThat(clock.toString()).isEqualTo("04:32"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Subtract minutes -> subtract more than two days") + public void subtractMinutesSubtractMoreThanTwoDays() { + Clock clock = new Clock(2, 20); + clock.add(-3000); + assertThat(clock.toString()).isEqualTo("00:20"); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with same time") + public void compareTwoClocksForEqualityClocksWithSameTime() { + Clock clock1 = new Clock(15, 37); + Clock clock2 = new Clock(15, 37); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks a minute apart") + public void compareTwoClocksForEqualityClocksAMinuteApart() { + Clock clock1 = new Clock(15, 36); + Clock clock2 = new Clock(15, 37); + assertThat(clock1).isNotEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks an hour apart") + public void compareTwoClocksForEqualityClocksAnHourApart() { + Clock clock1 = new Clock(14, 37); + Clock clock2 = new Clock(15, 37); + assertThat(clock1).isNotEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with hour overflow") + public void compareTwoClocksForEqualityClocksWithHourOverflow() { + Clock clock1 = new Clock(10, 37); + Clock clock2 = new Clock(34, 37); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with hour overflow by several days") + public void compareTwoClocksForEqualityClocksWithHourOverflowBySeveralDays() { + Clock clock1 = new Clock(3, 11); + Clock clock2 = new Clock(99, 11); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with negative hour") + public void compareTwoClocksForEqualityClocksWithNegativeHour() { + Clock clock1 = new Clock(22, 40); + Clock clock2 = new Clock(-2, 40); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with negative hour that wraps") + public void compareTwoClocksForEqualityClocksWithNegativeHourThatWraps() { + Clock clock1 = new Clock(17, 3); + Clock clock2 = new Clock(-31, 3); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with negative hour that " + + "wraps multiple times") + public void compareTwoClocksForEqualityClocksWithNegativeHourThatWrapsMultipl() { + Clock clock1 = new Clock(13, 49); + Clock clock2 = new Clock(-83, 49); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with minute overflow") + public void compareTwoClocksForEqualityClocksWithMinuteOverflow() { + Clock clock1 = new Clock(0, 1); + Clock clock2 = new Clock(0, 1441); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with minute overflow by several days") + public void compareTwoClocksForEqualityClocksWithMinuteOverflowBySeveralDays() { + Clock clock1 = new Clock(2, 2); + Clock clock2 = new Clock(2, 4322); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with negative minute") + public void compareTwoClocksForEqualityClocksWithNegativeMinute() { + Clock clock1 = new Clock(2, 40); + Clock clock2 = new Clock(3, -20); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with negative minute that wraps") + public void compareTwoClocksForEqualityClocksWithNegativeMinuteThatWraps() { + Clock clock1 = new Clock(4, 10); + Clock clock2 = new Clock(5, -1490); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with negative minute that " + + "wraps multiple times") + public void compareTwoClocksForEqualityClocksWithNegativeMinuteThatWrapsMulti() { + Clock clock1 = new Clock(6, 15); + Clock clock2 = new Clock(6, -4305); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with negative hours and minutes") + public void compareTwoClocksForEqualityClocksWithNegativeHoursAndMinutes() { + Clock clock1 = new Clock(7, 32); + Clock clock2 = new Clock(-12, -268); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> clocks with negative hours and minutes that wrap") + public void compareTwoClocksForEqualityClocksWithNegativeHoursAndMinutesThatW() { + Clock clock1 = new Clock(18, 7); + Clock clock2 = new Clock(-54, -11513); + assertThat(clock1).isEqualTo(clock2); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("Compare two clocks for equality -> full clock and zeroed clock") + public void compareTwoClocksForEqualityFullClockAndZeroedClock() { + Clock clock1 = new Clock(24, 0); + Clock clock2 = new Clock(0, 0); + assertThat(clock1).isEqualTo(clock2); + } + +} diff --git a/exercises/practice/collatz-conjecture/.meta/template.hbs b/exercises/practice/collatz-conjecture/.meta/template.hbs new file mode 100644 index 000000000..81bcdc874 --- /dev/null +++ b/exercises/practice/collatz-conjecture/.meta/template.hbs @@ -0,0 +1,27 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class CollatzCalculatorTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError~}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new CollatzCalculator().computeStepCount({{{formattedInputs.number}}})) + .withMessage("Only positive integers are allowed"); + {{~else~}} + assertThat(new CollatzCalculator().computeStepCount({{{formattedInputs.number}}})) + .isEqualTo({{{expectedValue}}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/complex-numbers/.meta/template.hbs b/exercises/practice/complex-numbers/.meta/template.hbs new file mode 100644 index 000000000..fe82e8ff4 --- /dev/null +++ b/exercises/practice/complex-numbers/.meta/template.hbs @@ -0,0 +1,33 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.withPrecision; + +public class {{testClassName}} { + + private static final double DOUBLE_EQUALITY_TOLERANCE = 1e-15; + + private void assertDoublesEqual(double d1, double d2, String numberPart) { + String errorMessage = "While testing " + numberPart + " part of number"; + + assertThat(d1).as(errorMessage).isCloseTo(d2, withPrecision(DOUBLE_EQUALITY_TOLERANCE)); + } + + private void assertComplexNumbersEqual(ComplexNumber c1, ComplexNumber c2) { + assertDoublesEqual(c1.getReal(), c2.getReal(), "real"); + assertDoublesEqual(c1.getImaginary(), c2.getImaginary(), "imaginary"); + } +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderComplexNumberCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/connect/.meta/template.hbs b/exercises/practice/connect/.meta/template.hbs new file mode 100644 index 000000000..f02642049 --- /dev/null +++ b/exercises/practice/connect/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderConnectCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/crypto-square/.meta/template.hbs b/exercises/practice/crypto-square/.meta/template.hbs new file mode 100644 index 000000000..0016519e0 --- /dev/null +++ b/exercises/practice/crypto-square/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class CryptoSquareTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderCryptoSquareCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/custom-set/.meta/template.hbs b/exercises/practice/custom-set/.meta/template.hbs new file mode 100644 index 000000000..13d1715b8 --- /dev/null +++ b/exercises/practice/custom-set/.meta/template.hbs @@ -0,0 +1,21 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderCustomSetCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/diamond/.meta/template.hbs b/exercises/practice/diamond/.meta/template.hbs new file mode 100644 index 000000000..d08bc4cc9 --- /dev/null +++ b/exercises/practice/diamond/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DiamondPrinterTest { + + private DiamondPrinter diamondPrinter = new DiamondPrinter(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(diamondPrinter.printToList({{{toChar formattedInputs.letter}}})) + .containsExactly({{{formatElements rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/difference-of-squares/.meta/template.hbs b/exercises/practice/difference-of-squares/.meta/template.hbs new file mode 100644 index 000000000..285b21051 --- /dev/null +++ b/exercises/practice/difference-of-squares/.meta/template.hbs @@ -0,0 +1,28 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DifferenceOfSquaresCalculatorTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "squareOfSum")~}} + assertThat(new DifferenceOfSquaresCalculator().computeSquareOfSumTo({{{formattedInputs.number}}})) + .isEqualTo({{{expectedValue}}}); + {{~else if (eq property "sumOfSquares")~}} + assertThat(new DifferenceOfSquaresCalculator().computeSumOfSquaresTo({{{formattedInputs.number}}})) + .isEqualTo({{{expectedValue}}}); + {{~else~}} + assertThat(new DifferenceOfSquaresCalculator().computeDifferenceOfSquares({{{formattedInputs.number}}})) + .isEqualTo({{{expectedValue}}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/dnd-character/.meta/template.hbs b/exercises/practice/dnd-character/.meta/template.hbs new file mode 100644 index 000000000..56a0d3edb --- /dev/null +++ b/exercises/practice/dnd-character/.meta/template.hbs @@ -0,0 +1,48 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DnDCharacterTest { + + private DnDCharacter dndCharacter = new DnDCharacter(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "modifier")}} + assertThat(dndCharacter.modifier({{rawCase.input.score}})) + .isEqualTo({{rawCase.expected}}); + {{else if (eq property "ability")}} + for (int i = 0; i < 1000; i++) { + int score = dndCharacter.ability(dndCharacter.rollDice()); + assertThat(score).isGreaterThan(2).isLessThan(19); + } + {{else if rawCase.expected.hitpoints}} + for (int i = 0; i < 1000; i++) { + DnDCharacter character = new DnDCharacter(); + assertThat(character.getStrength()).isGreaterThan(2).isLessThan(19); + assertThat(character.getDexterity()).isGreaterThan(2).isLessThan(19); + assertThat(character.getConstitution()).isGreaterThan(2).isLessThan(19); + assertThat(character.getIntelligence()).isGreaterThan(2).isLessThan(19); + assertThat(character.getWisdom()).isGreaterThan(2).isLessThan(19); + assertThat(character.getCharisma()).isGreaterThan(2).isLessThan(19); + assertThat(character.getHitpoints()).isEqualTo(10 + character.modifier(character.getConstitution())); + } + {{else}} + DnDCharacter character = new DnDCharacter(); + assertThat(character.getStrength()).isEqualTo(character.getStrength()); + assertThat(character.getDexterity()).isEqualTo(character.getDexterity()); + assertThat(character.getConstitution()).isEqualTo(character.getConstitution()); + assertThat(character.getIntelligence()).isEqualTo(character.getIntelligence()); + assertThat(character.getWisdom()).isEqualTo(character.getWisdom()); + assertThat(character.getCharisma()).isEqualTo(character.getCharisma()); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/dominoes/.meta/template.hbs b/exercises/practice/dominoes/.meta/template.hbs new file mode 100644 index 000000000..1ea52e1f7 --- /dev/null +++ b/exercises/practice/dominoes/.meta/template.hbs @@ -0,0 +1,87 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class DominoesTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() throws ChainNotFoundException { + Dominoes dominoes = new Dominoes(); + List dominoesList = {{{asDominoList rawCase}}}; + + {{#if (eq rawCase.expected true)}} + List chain = dominoes.formChain(dominoesList); + assertValidChain(dominoesList, chain); + {{else}} + assertThatExceptionOfType(ChainNotFoundException.class) + .isThrownBy(() -> dominoes.formChain(dominoesList)) + .withMessage("No domino chain found."); + {{/if}} + } +{{/each}} + + private void assertValidChain(List inputDominoes, List outputDominoes) { + assertSameDominoes(inputDominoes, outputDominoes); + assertEndDominoesMatch(outputDominoes); + assertConsecutiveDominoes(outputDominoes); + } + + private void assertEndDominoesMatch(List outputDominoes) { + if (outputDominoes.isEmpty()) { + return; + } + int leftValueOfFirstDomino = outputDominoes.get(0).getLeft(); + int rightValueOfLastDomino = outputDominoes.get(outputDominoes.size() - 1).getRight(); + String errorMessage = "The left value of the first domino (" + + leftValueOfFirstDomino + + ") needs to match the right value of the last domino (" + + rightValueOfLastDomino + + ")."; + + assertThat(leftValueOfFirstDomino).withFailMessage(errorMessage).isEqualTo(rightValueOfLastDomino); + } + + private void assertSameDominoes(List inputDominoes, List outputDominoes) { + String errorMessage = "The number of dominoes in the input list (" + inputDominoes.size() + + ") needs to match the number of dominoes in the output chain (" + outputDominoes.size() + ")"; + + assertThat(inputDominoes).withFailMessage(errorMessage).hasSameSizeAs(outputDominoes); + + for (Domino domino : inputDominoes) { + int inputFrequency = Collections.frequency(inputDominoes, domino); + int outputFrequency = Collections.frequency(outputDominoes, domino); + + String frequencyErrorMessage = "The frequency of domino (" + domino.getLeft() + ", " + + domino.getRight() + ")" + + " in the input is (" + inputFrequency + "), but (" + outputFrequency + ") in the output."; + + assertThat(inputFrequency).withFailMessage(frequencyErrorMessage).isEqualTo(outputFrequency); + } + } + + private void assertConsecutiveDominoes(List dominoes) { + for (int i = 0; i < dominoes.size() - 1; i++) { + int rightValueOfIthDomino = dominoes.get(i).getRight(); + int leftValueOfNextDomino = dominoes.get(i + 1).getLeft(); + String errorMessage = "The right value of domino number " + i + " (" + + rightValueOfIthDomino + + ") needs to match the left value of domino number " + (i + 1) + " (" + + leftValueOfNextDomino + + ")."; + + assertThat(dominoes.get(i).getRight()).withFailMessage(errorMessage) + .isEqualTo(dominoes.get(i + 1).getLeft()); + } + } +} diff --git a/exercises/practice/dot-dsl/.meta/template.hbs b/exercises/practice/dot-dsl/.meta/template.hbs new file mode 100644 index 000000000..ae99c23b9 --- /dev/null +++ b/exercises/practice/dot-dsl/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Collections; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GraphTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderDotDslCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/etl/.meta/template.hbs b/exercises/practice/etl/.meta/template.hbs new file mode 100644 index 000000000..cbee2f031 --- /dev/null +++ b/exercises/practice/etl/.meta/template.hbs @@ -0,0 +1,27 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class EtlTest { + + private final Etl etl = new Etl(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + Map> legacy = {{{formatEtlInput inputNodes.legacy}}}; + Map expected = {{{formatEtlExpected rawCase.expected}}}; + + assertThat(etl.transform(legacy)).isEqualTo(expected); + } +{{/each}} +} diff --git a/exercises/practice/flower-field/.meta/template.hbs b/exercises/practice/flower-field/.meta/template.hbs new file mode 100644 index 000000000..64ce245e4 --- /dev/null +++ b/exercises/practice/flower-field/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FlowerFieldBoardTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + List inputBoard = {{{asFlowerFieldBoard rawCase.input.garden}}}; + List expected = {{{asFlowerFieldBoard rawCase.expected}}}; + List actual = new FlowerFieldBoard(inputBoard).withNumbers(); + + assertThat(actual).isEqualTo(expected); + } +{{/each}} +} diff --git a/exercises/practice/food-chain/.meta/template.hbs b/exercises/practice/food-chain/.meta/template.hbs new file mode 100644 index 000000000..f52bde7cd --- /dev/null +++ b/exercises/practice/food-chain/.meta/template.hbs @@ -0,0 +1,27 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class FoodChainTest { + + private FoodChain foodChain = new FoodChain(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq rawCase.input.startVerse rawCase.input.endVerse)}} + assertThat(foodChain.verse({{{formattedInputs.startVerse}}})) + .isEqualTo({{{foodChainExpected rawCase.expected}}}); + {{else}} + assertThat(foodChain.verses({{{formattedInputs.startVerse}}}, {{{formattedInputs.endVerse}}})) + .isEqualTo({{{foodChainExpected rawCase.expected}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/forth/.meta/template.hbs b/exercises/practice/forth/.meta/template.hbs new file mode 100644 index 000000000..73dbad194 --- /dev/null +++ b/exercises/practice/forth/.meta/template.hbs @@ -0,0 +1,24 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class {{testClassName}} { + + private ForthEvaluator forthEvaluator = new ForthEvaluator(); +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderForthCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/game-of-life/.meta/template.hbs b/exercises/practice/game-of-life/.meta/template.hbs new file mode 100644 index 000000000..03047fe4e --- /dev/null +++ b/exercises/practice/game-of-life/.meta/template.hbs @@ -0,0 +1,23 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GameOfLifeTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + int[][] matrix = {{{as2DIntArray rawCase.input.matrix 8}}}; + int[][] expected = {{{as2DIntArray rawCase.expected 8}}}; + + assertThat(new GameOfLife().tick(matrix)) + .isDeepEqualTo(expected); + } +{{/each}} +} diff --git a/exercises/practice/gigasecond/.meta/template.hbs b/exercises/practice/gigasecond/.meta/template.hbs new file mode 100644 index 000000000..2d0cebd86 --- /dev/null +++ b/exercises/practice/gigasecond/.meta/template.hbs @@ -0,0 +1,33 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.time.LocalDate; +import java.time.LocalDateTime; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GigasecondTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "isEqual")~}} + LocalDateTime input = LocalDateTime.parse({{{formattedInputs.moment}}}); + new Gigasecond(input).getDateTime(); + + assertThat(input).isEqualTo(LocalDateTime.parse({{{formattedInputs.moment}}})); + {{~else if (contains formattedInputs.moment "T")~}} + assertThat(new Gigasecond(LocalDateTime.parse({{{formattedInputs.moment}}})).getDateTime()) + .isEqualTo(LocalDateTime.parse("{{{rawCase.expected.asText}}}")); + {{~else~}} + assertThat(new Gigasecond(LocalDate.parse({{{formattedInputs.moment}}})).getDateTime()) + .isEqualTo(LocalDateTime.parse("{{{rawCase.expected.asText}}}")); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/go-counting/.meta/template.hbs b/exercises/practice/go-counting/.meta/template.hbs new file mode 100644 index 000000000..d38167133 --- /dev/null +++ b/exercises/practice/go-counting/.meta/template.hbs @@ -0,0 +1,24 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.awt.Point; +import java.util.Map; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class GoCountingTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderGoCountingCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/grade-school/.meta/template.hbs b/exercises/practice/grade-school/.meta/template.hbs new file mode 100644 index 000000000..817a21834 --- /dev/null +++ b/exercises/practice/grade-school/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SchoolTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderSchoolCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/grains/.meta/template.hbs b/exercises/practice/grains/.meta/template.hbs new file mode 100644 index 000000000..e474812a1 --- /dev/null +++ b/exercises/practice/grains/.meta/template.hbs @@ -0,0 +1,36 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.math.BigInteger; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class GrainsTest { + + private Grains grains = new Grains(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "total")}} + assertThat(grains.grainsOnBoard()) + .isEqualTo(new BigInteger("{{{rawCase.expected}}}")); + {{else}} + {{#if expectedError}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> grains.grainsOnSquare({{{formattedInputs.square}}})) + .withMessage("square must be between 1 and 64"); + {{else}} + assertThat(grains.grainsOnSquare({{{formattedInputs.square}}})) + .isEqualTo(new BigInteger("{{{rawCase.expected}}}")); + {{/if}} + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/grep/.meta/template.hbs b/exercises/practice/grep/.meta/template.hbs new file mode 100644 index 000000000..f9027f904 --- /dev/null +++ b/exercises/practice/grep/.meta/template.hbs @@ -0,0 +1,91 @@ +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GrepToolTest { + + private GrepTool grepTool; + + @BeforeEach + public void setUp() throws IOException { + List iliadText = List.of( + "Achilles sing, O Goddess! Peleus' son;", + "His wrath pernicious, who ten thousand woes", + "Caused to Achaia's host, sent many a soul", + "Illustrious into Ades premature,", + "And Heroes gave (so stood the will of Jove)", + "To dogs and to all ravening fowls a prey,", + "When fierce dispute had separated once", + "The noble Chief Achilles from the son", + "Of Atreus, Agamemnon, King of men." + ); + writeToFile("iliad.txt", iliadText); + + List midsummerNightText = List.of( + "I do entreat your grace to pardon me.", + "I know not by what power I am made bold,", + "Nor how it may concern my modesty,", + "In such a presence here to plead my thoughts;", + "But I beseech your grace that I may know", + "The worst that may befall me in this case,", + "If I refuse to wed Demetrius." + ); + writeToFile("midsummer-night.txt", midsummerNightText); + + List paradiseLostText = List.of( + "Of Mans First Disobedience, and the Fruit", + "Of that Forbidden Tree, whose mortal tast", + "Brought Death into the World, and all our woe,", + "With loss of Eden, till one greater Man", + "Restore us, and regain the blissful Seat,", + "Sing Heav'nly Muse, that on the secret top", + "Of Oreb, or of Sinai, didst inspire", + "That Shepherd, who first taught the chosen Seed" + ); + writeToFile("paradise-lost.txt", paradiseLostText); + + grepTool = new GrepTool(); + } + + @AfterEach + public void tearDown() throws IOException { + deleteFile("iliad.txt"); + deleteFile("midsummer-night.txt"); + deleteFile("paradise-lost.txt"); + } +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(grepTool.grep( + "{{escapeJava rawCase.input.pattern}}", + {{{formatJava inputNodes.flags}}}, + {{{formatJava inputNodes.files}}})) + .isEqualTo({{{joinLines rawCase.expected}}}); + } +{{/each}} + + private void writeToFile(String filename, List contents) throws IOException { + Path file = Paths.get(filename); + Files.write(file, contents, StandardCharsets.UTF_8); + } + + private void deleteFile(String filename) throws IOException { + Files.deleteIfExists(Paths.get(filename)); + } +} diff --git a/exercises/practice/hamming/.meta/template.hbs b/exercises/practice/hamming/.meta/template.hbs new file mode 100644 index 000000000..2e6fe8a10 --- /dev/null +++ b/exercises/practice/hamming/.meta/template.hbs @@ -0,0 +1,27 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + @DisplayName("{{{description}}}") + public void {{methodName}}() { + {{#if expectedError}} + assertThatExceptionOfType({{expectedException}}.class) + .isThrownBy(() -> new Hamming({{{formattedInputs.strand1}}}, {{{formattedInputs.strand2}}})) + .withMessage("{{{expectedErrorMessage}}}"); + {{else}} + assertThat(new Hamming({{{formattedInputs.strand1}}}, {{{formattedInputs.strand2}}}).getHammingDistance()) + .isEqualTo({{{expectedValue}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/hangman/.meta/tests.toml b/exercises/practice/hangman/.meta/tests.toml new file mode 100644 index 000000000..de2f7ee47 --- /dev/null +++ b/exercises/practice/hangman/.meta/tests.toml @@ -0,0 +1,52 @@ +# This is an auto-generated file by configlet to track which test cases +# are implemented by this exercise. + +[2419ffe6-16d8-4059-856a-9a101998a418] +description = "Initially 9 failures are allowed and no letters are guessed" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[17c4296d-daab-44dc-8155-37c77caa52c1] +description = "After 10 failures the game is over" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[77c9ae1f-bbc4-4ed4-b67e-08110cbcfc17] +description = "Losing with several correct guesses" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[25101d8d-9874-405b-9825-193a14b69753] +description = "Feeding a correct letter removes underscores" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[8e6bd521-bc9b-458f-9cce-f57f4140c173] +description = "Feeding a correct letter twice counts as a failure" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[5e6971b7-5e5f-49c2-b85d-1dd6aeb53bd5] +description = "Guessing a repeated letter reveals all instances" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[a6c69d92-01ef-4b81-b9d9-801131e79bbb] +description = "Getting all the letters right makes for a win" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[2dc47994-b434-4a26-b70c-1eebeff77fe4] +description = "Winning on the last guess is still a win" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[52801d56-6963-494b-a901-5736e46ddc12] +description = "Guessing after a lose is error" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" + +[29a874f3-a413-4e1b-9a60-6be018e70b60] +description = "Guessing after a win is error" +include = false +comment = "Java track uses RxJava reactive streams (FRP) instead of synchronous guess()" diff --git a/exercises/practice/hello-world/.meta/template.hbs b/exercises/practice/hello-world/.meta/template.hbs new file mode 100644 index 000000000..4d620f7a3 --- /dev/null +++ b/exercises/practice/hello-world/.meta/template.hbs @@ -0,0 +1,16 @@ +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class GreeterTest { +{{#each testCases}} + + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new Greeter().getGreeting()) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/high-scores/.meta/template.hbs b/exercises/practice/high-scores/.meta/template.hbs new file mode 100644 index 000000000..26b884f58 --- /dev/null +++ b/exercises/practice/high-scores/.meta/template.hbs @@ -0,0 +1,40 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class HighScoresTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "latestAfterTopThree")~}} + HighScores highScores = new HighScores({{{formattedInputs.scores}}}); + highScores.personalTopThree(); + assertThat(highScores.latest()).isEqualTo({{{expectedValue}}}); + {{~else if (eq property "scoresAfterTopThree")~}} + HighScores highScores = new HighScores({{{formattedInputs.scores}}}); + highScores.personalTopThree(); + assertThat(highScores.scores()).isEqualTo({{{expectedValue}}}); + {{~else if (eq property "latestAfterBest")~}} + HighScores highScores = new HighScores({{{formattedInputs.scores}}}); + highScores.personalBest(); + assertThat(highScores.latest()).isEqualTo({{{expectedValue}}}); + {{~else if (eq property "scoresAfterBest")~}} + HighScores highScores = new HighScores({{{formattedInputs.scores}}}); + highScores.personalBest(); + assertThat(highScores.scores()).isEqualTo({{{expectedValue}}}); + {{~else~}} + assertThat(new HighScores({{{formattedInputs.scores}}}).{{property}}()) + .isEqualTo({{{expectedValue}}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/house/.meta/template.hbs b/exercises/practice/house/.meta/template.hbs new file mode 100644 index 000000000..ac98ccd90 --- /dev/null +++ b/exercises/practice/house/.meta/template.hbs @@ -0,0 +1,30 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class HouseTest { + + private House house = new House(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq rawCase.input.startVerse rawCase.input.endVerse)}} + assertThat(house.verse({{{formattedInputs.startVerse}}})) + .isEqualTo({{{houseExpected rawCase.expected}}}); + {{else}}{{#if (and (eq rawCase.input.startVerse 1) (eq rawCase.input.endVerse 12))}} + assertThat(house.sing()) + .isEqualTo({{{houseExpected rawCase.expected}}}); + {{else}} + assertThat(house.verses({{{formattedInputs.startVerse}}}, {{{formattedInputs.endVerse}}})) + .isEqualTo({{{houseExpected rawCase.expected}}}); + {{/if}}{{/if}} + } +{{/each}} +} diff --git a/exercises/practice/intergalactic-transmission/.meta/template.hbs b/exercises/practice/intergalactic-transmission/.meta/template.hbs new file mode 100644 index 000000000..e8441e8b6 --- /dev/null +++ b/exercises/practice/intergalactic-transmission/.meta/template.hbs @@ -0,0 +1,38 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class IntergalacticTransmissionTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq rawCase.property "transmitSequence")}} + List input = {{{asHexIntList rawCase.input.message}}}; + List expected = {{{asHexIntList rawCase.expected}}}; + assertThat(IntergalacticTransmission.getTransmitSequence(input)) + .isEqualTo(expected); + {{else if (eq rawCase.property "decodeMessage")}} + {{#if rawCase.expected.error}} + List input = {{{asHexIntList rawCase.input.message}}}; + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> IntergalacticTransmission.decodeSequence(input)); + {{else}} + List input = {{{asHexIntList rawCase.input.message}}}; + List expected = {{{asHexIntList rawCase.expected}}}; + assertThat(IntergalacticTransmission.decodeSequence(input)) + .isEqualTo(expected); + {{/if}} + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/killer-sudoku-helper/.meta/template.hbs b/exercises/practice/killer-sudoku-helper/.meta/template.hbs new file mode 100644 index 000000000..9baecfc2b --- /dev/null +++ b/exercises/practice/killer-sudoku-helper/.meta/template.hbs @@ -0,0 +1,34 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class KillerSudokuHelperTest { + + private KillerSudokuHelper helper = new KillerSudokuHelper(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (hasElements rawCase.input.cage.exclude)}} + assertThat(helper.combinationsInCage( + {{field rawCase.input.cage "sum"}}, + {{field rawCase.input.cage "size"}}, + {{{asIntList rawCase.input.cage.exclude}}})) + .isEqualTo({{{as2DIntList rawCase.expected}}}); + {{else}} + assertThat(helper.combinationsInCage( + {{field rawCase.input.cage "sum"}}, + {{field rawCase.input.cage "size"}})) + .isEqualTo({{{as2DIntList rawCase.expected}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/kindergarten-garden/.meta/template.hbs b/exercises/practice/kindergarten-garden/.meta/template.hbs new file mode 100644 index 000000000..cc2871008 --- /dev/null +++ b/exercises/practice/kindergarten-garden/.meta/template.hbs @@ -0,0 +1,21 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class KindergartenGardenTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new KindergartenGarden({{{formattedInputs.diagram}}}) + .getPlantsOfStudent({{{formattedInputs.student}}})) + .containsExactly({{{asPlants rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/knapsack/.meta/template.hbs b/exercises/practice/knapsack/.meta/template.hbs new file mode 100644 index 000000000..4093b69e3 --- /dev/null +++ b/exercises/practice/knapsack/.meta/template.hbs @@ -0,0 +1,26 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class KnapsackTest { + + private Knapsack knapsack = new Knapsack(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + List items = {{{asKnapsackItems rawCase.input.items}}}; + + assertThat(knapsack.maximumValue({{{formattedInputs.maximumWeight}}}, items)) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/largest-series-product/.meta/template.hbs b/exercises/practice/largest-series-product/.meta/template.hbs new file mode 100644 index 000000000..4f33efd1c --- /dev/null +++ b/exercises/practice/largest-series-product/.meta/template.hbs @@ -0,0 +1,29 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class LargestSeriesProductCalculatorTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new LargestSeriesProductCalculator({{{formattedInputs.digits}}}) + .calculateLargestProductForSeriesLength({{{formattedInputs.span}}})) + .withMessage("{{{largestSeriesProductExpectedMessage this}}}"); + {{else}} + assertThat(new LargestSeriesProductCalculator({{{formattedInputs.digits}}}) + .calculateLargestProductForSeriesLength({{{formattedInputs.span}}})) + .isEqualTo({{{asLong expectedValue}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/leap/.meta/template.hbs b/exercises/practice/leap/.meta/template.hbs new file mode 100644 index 000000000..7ea8d3cb3 --- /dev/null +++ b/exercises/practice/leap/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class LeapTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new Leap().isLeapYear({{{formattedInputs.year}}})) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/ledger/.meta/template.hbs b/exercises/practice/ledger/.meta/template.hbs new file mode 100644 index 000000000..206aaa1c7 --- /dev/null +++ b/exercises/practice/ledger/.meta/template.hbs @@ -0,0 +1,27 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; + +import static org.assertj.core.api.Assertions.assertThat; + +@ExtendWith(LocaleExtension.class) +public class LedgerTest { + + private Ledger ledger = new Ledger(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(ledger.format( + "{{rawCase.input.currency}}", + "{{ledgerLocale rawCase.input.locale}}", + {{{formatLedgerEntries rawCase.input.entries}}})) + .isEqualTo({{{formatLedgerExpected rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/linked-list/.meta/template.hbs b/exercises/practice/linked-list/.meta/template.hbs new file mode 100644 index 000000000..1e315deca --- /dev/null +++ b/exercises/practice/linked-list/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class DoublyLinkedListTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderDoublyLinkedListOperations rawCase.input.operations}}} + } +{{/each}} +} diff --git a/exercises/practice/list-ops/.meta/template.hbs b/exercises/practice/list-ops/.meta/template.hbs new file mode 100644 index 000000000..e2d235931 --- /dev/null +++ b/exercises/practice/list-ops/.meta/template.hbs @@ -0,0 +1,21 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderListOpsCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/luhn/.meta/template.hbs b/exercises/practice/luhn/.meta/template.hbs new file mode 100644 index 000000000..77fde88c2 --- /dev/null +++ b/exercises/practice/luhn/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class LuhnValidatorTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq expectedValue "true")~}} + assertThat(new LuhnValidator().isValid({{{formattedInputs.value}}})) + .isTrue(); + {{~else~}} + assertThat(new LuhnValidator().isValid({{{formattedInputs.value}}})) + .isFalse(); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/matching-brackets/.meta/template.hbs b/exercises/practice/matching-brackets/.meta/template.hbs new file mode 100644 index 000000000..d63e629fa --- /dev/null +++ b/exercises/practice/matching-brackets/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class BracketCheckerTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new BracketChecker({{{formattedInputs.value}}}).areBracketsMatchedAndNestedCorrectly()) + .{{#if (eq expectedValue "true")}}isTrue(){{else}}isFalse(){{/if}}; + } +{{/each}} +} diff --git a/exercises/practice/matrix/.meta/template.hbs b/exercises/practice/matrix/.meta/template.hbs new file mode 100644 index 000000000..c06dfd423 --- /dev/null +++ b/exercises/practice/matrix/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MatrixTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "row")~}} + assertThat(new Matrix({{{formattedInputs.string}}}).getRow({{{formattedInputs.index}}})) + .isEqualTo({{asIntArray rawCase.expected}}); + {{~else~}} + assertThat(new Matrix({{{formattedInputs.string}}}).getColumn({{{formattedInputs.index}}})) + .isEqualTo({{asIntArray rawCase.expected}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/meetup/.meta/template.hbs b/exercises/practice/meetup/.meta/template.hbs new file mode 100644 index 000000000..29b760cd9 --- /dev/null +++ b/exercises/practice/meetup/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.time.DayOfWeek; +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MeetupTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + LocalDate expected = {{{asLocalDate rawCase.expected}}}; + Meetup meetup = new Meetup({{rawCase.input.month}}, {{rawCase.input.year}}); + assertThat(meetup.day(DayOfWeek.{{upper rawCase.input.dayofweek}}, MeetupSchedule.{{upper rawCase.input.week}})) + .isEqualTo(expected); + } +{{/each}} +} diff --git a/exercises/practice/nth-prime/.meta/template.hbs b/exercises/practice/nth-prime/.meta/template.hbs new file mode 100644 index 000000000..c96107aa4 --- /dev/null +++ b/exercises/practice/nth-prime/.meta/template.hbs @@ -0,0 +1,26 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class PrimeCalculatorTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError~}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new PrimeCalculator().nth({{{formattedInputs.number}}})); + {{~else~}} + assertThat(new PrimeCalculator().nth({{{formattedInputs.number}}})) + .isEqualTo({{{expectedValue}}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/nucleotide-count/.meta/template.hbs b/exercises/practice/nucleotide-count/.meta/template.hbs new file mode 100644 index 000000000..b678d2e42 --- /dev/null +++ b/exercises/practice/nucleotide-count/.meta/template.hbs @@ -0,0 +1,33 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +public class NucleotideCounterTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError}} + assertThatThrownBy(() -> new NucleotideCounter({{{formattedInputs.strand}}})) + .isInstanceOf(IllegalArgumentException.class); + {{else}} + NucleotideCounter counter = new NucleotideCounter( + {{{formattedInputs.strand}}}); + + assertThat(counter.nucleotideCounts()) + .containsExactlyInAnyOrderEntriesOf( + Map.of('A', {{rawCase.expected.A}}, 'C', {{rawCase.expected.C}}, + 'G', {{rawCase.expected.G}}, 'T', {{rawCase.expected.T}})); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/ocr-numbers/.meta/template.hbs b/exercises/practice/ocr-numbers/.meta/template.hbs new file mode 100644 index 000000000..5bc9edca6 --- /dev/null +++ b/exercises/practice/ocr-numbers/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderOcrCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/palindrome-products/.meta/template.hbs b/exercises/practice/palindrome-products/.meta/template.hbs new file mode 100644 index 000000000..06ef3b6c8 --- /dev/null +++ b/exercises/practice/palindrome-products/.meta/template.hbs @@ -0,0 +1,38 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.SortedMap; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class {{testClassName}} { + + private PalindromeCalculator palindromeCalculator = new PalindromeCalculator(); + + private void checkPalindromeWithFactorsMatchesExpected(List> expectedPalindromeFactors, + long expectedValueOfPalindrome, + SortedMap>> actualPalindromes, + long actualValueOfPalindrome) { + assertThat(actualPalindromes).isNotNull(); + assertThat(actualPalindromes.isEmpty()).isFalse(); + + assertThat(actualValueOfPalindrome).isEqualTo(expectedValueOfPalindrome); + + List> actualPalindromeFactors = actualPalindromes.get(actualValueOfPalindrome); + assertThat(actualPalindromeFactors).containsExactlyInAnyOrderElementsOf(expectedPalindromeFactors); + } +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderPalindromeProductsCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/parallel-letter-frequency/.meta/template.hbs b/exercises/practice/parallel-letter-frequency/.meta/template.hbs new file mode 100644 index 000000000..93c4be1d0 --- /dev/null +++ b/exercises/practice/parallel-letter-frequency/.meta/template.hbs @@ -0,0 +1,31 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Arrays; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ParallelLetterFrequencyTest { + + private static String[] createIdenticalTexts(int count, String text) { + String[] arr = new String[count]; + Arrays.fill(arr, text); + return arr; + } + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + String[] input = {{{formatFrequencyTexts rawCase.input.texts}}}; + ParallelLetterFrequency p = new ParallelLetterFrequency(input); + + assertThat(p.countLetters()).isEqualTo({{{formatFrequencyExpected rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/pascals-triangle/.meta/template.hbs b/exercises/practice/pascals-triangle/.meta/template.hbs new file mode 100644 index 000000000..59c22ad7b --- /dev/null +++ b/exercises/practice/pascals-triangle/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class PascalsTriangleGeneratorTest { + + private PascalsTriangleGenerator pascalsTriangleGenerator = new PascalsTriangleGenerator(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(pascalsTriangleGenerator.generateTriangle({{{formattedInputs.count}}})) + .isDeepEqualTo({{{as2DIntArray rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/perfect-numbers/.meta/template.hbs b/exercises/practice/perfect-numbers/.meta/template.hbs new file mode 100644 index 000000000..584e89be6 --- /dev/null +++ b/exercises/practice/perfect-numbers/.meta/template.hbs @@ -0,0 +1,27 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class NaturalNumberTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError~}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new NaturalNumber({{{formattedInputs.number}}})) + .withMessage("You must supply a natural number (positive integer)"); + {{~else~}} + assertThat(new NaturalNumber({{{formattedInputs.number}}}).getClassification()) + .isEqualTo(Classification.{{#if (eq expectedValue "\"perfect\"")}}PERFECT{{else if (eq expectedValue "\"abundant\"")}}ABUNDANT{{else}}DEFICIENT{{/if}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/phone-number/.meta/template.hbs b/exercises/practice/phone-number/.meta/template.hbs new file mode 100644 index 000000000..d964b4cd8 --- /dev/null +++ b/exercises/practice/phone-number/.meta/template.hbs @@ -0,0 +1,27 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class PhoneNumberTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new PhoneNumber({{{formattedInputs.phrase}}})) + .withMessage("{{{escapeJava expectedErrorMessage}}}"); + {{else}} + assertThat(new PhoneNumber({{{formattedInputs.phrase}}}).getNumber()) + .isEqualTo({{{expectedValue}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/piecing-it-together/.meta/template.hbs b/exercises/practice/piecing-it-together/.meta/template.hbs new file mode 100644 index 000000000..babf87258 --- /dev/null +++ b/exercises/practice/piecing-it-together/.meta/template.hbs @@ -0,0 +1,49 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class PiecingItTogetherTest { + + private static final double DOUBLE_EQUALITY_TOLERANCE = 1e-9; + + private void assertJigsawInfoEquals(JigsawInfo actual, JigsawInfo expected) { + assertThat(actual.getPieces()).isEqualTo(expected.getPieces()); + assertThat(actual.getBorder()).isEqualTo(expected.getBorder()); + assertThat(actual.getInside()).isEqualTo(expected.getInside()); + assertThat(actual.getRows()).isEqualTo(expected.getRows()); + assertThat(actual.getColumns()).isEqualTo(expected.getColumns()); + assertThat(actual.getFormat()).isEqualTo(expected.getFormat()); + + Double actualAspect = actual.getAspectRatio() + .orElseThrow(() -> new AssertionError("Missing aspect ratio in actual result")); + Double expectedAspect = expected.getAspectRatio() + .orElseThrow(() -> new AssertionError("Missing aspect ratio in expected result")); + + assertThat(actualAspect).isCloseTo(expectedAspect, + org.assertj.core.api.Assertions.within(DOUBLE_EQUALITY_TOLERANCE)); + } + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if rawCase.expected.error}} + JigsawInfo input = {{{asJigsawInfo rawCase.input}}}; + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> PiecingItTogether.getCompleteInformation(input)) + .withMessage("{{{escapeJava rawCase.expected.error}}}"); + {{else}} + JigsawInfo input = {{{asJigsawInfo rawCase.input}}}; + JigsawInfo expected = {{{asJigsawInfo rawCase.expected}}}; + JigsawInfo actual = PiecingItTogether.getCompleteInformation(input); + assertJigsawInfoEquals(actual, expected); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/poker/.meta/template.hbs b/exercises/practice/poker/.meta/template.hbs new file mode 100644 index 000000000..42045ff9e --- /dev/null +++ b/exercises/practice/poker/.meta/template.hbs @@ -0,0 +1,23 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class PokerTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + Poker poker = new Poker({{{asStringList rawCase.input.hands}}}); + List expected = {{{asStringList rawCase.expected}}}; + assertThat(poker.getBestHands()).containsExactlyInAnyOrderElementsOf(expected); + } +{{/each}} +} diff --git a/exercises/practice/pov/.meta/template.hbs b/exercises/practice/pov/.meta/template.hbs new file mode 100644 index 000000000..3c5c6eefd --- /dev/null +++ b/exercises/practice/pov/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderPovCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/prime-factors/.meta/template.hbs b/exercises/practice/prime-factors/.meta/template.hbs new file mode 100644 index 000000000..c9e34aa8c --- /dev/null +++ b/exercises/practice/prime-factors/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class PrimeFactorsCalculatorTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new PrimeFactorsCalculator().calculatePrimeFactorsOf({{asLong formattedInputs.value}})) + .isEqualTo({{{asLongList rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/prism/.meta/template.hbs b/exercises/practice/prism/.meta/template.hbs new file mode 100644 index 000000000..be5e49a24 --- /dev/null +++ b/exercises/practice/prism/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class PrismTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + Prism.LaserInfo laser = {{{asLaserInfo rawCase.input.start}}}; + List prisms = {{{asPrismInfoList rawCase.input.prisms}}}; + + assertThat(Prism.findSequence(laser, prisms)) + .isEqualTo({{{asIntList rawCase.expected.sequence}}}); + } +{{/each}} +} diff --git a/exercises/practice/protein-translation/.meta/template.hbs b/exercises/practice/protein-translation/.meta/template.hbs new file mode 100644 index 000000000..378661e91 --- /dev/null +++ b/exercises/practice/protein-translation/.meta/template.hbs @@ -0,0 +1,31 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class ProteinTranslatorTest { + + private ProteinTranslator proteinTranslator = new ProteinTranslator(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> proteinTranslator.translate({{{formattedInputs.strand}}})) + .withMessage("{{{escapeJava expectedErrorMessage}}}"); + {{else}} + assertThat(proteinTranslator.translate({{{formattedInputs.strand}}})) + .isEqualTo({{{expectedValue}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/proverb/.meta/template.hbs b/exercises/practice/proverb/.meta/template.hbs new file mode 100644 index 000000000..28c5b5274 --- /dev/null +++ b/exercises/practice/proverb/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ProverbTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new Proverb({{{asStringArray rawCase.input.strings}}}).recite()) + .isEqualTo({{{joinLines rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/pythagorean-triplet/.meta/template.hbs b/exercises/practice/pythagorean-triplet/.meta/template.hbs new file mode 100644 index 000000000..c3c1ff7ef --- /dev/null +++ b/exercises/practice/pythagorean-triplet/.meta/template.hbs @@ -0,0 +1,21 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderPythagoreanCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/queen-attack/.meta/template.hbs b/exercises/practice/queen-attack/.meta/template.hbs new file mode 100644 index 000000000..60f9ed731 --- /dev/null +++ b/exercises/practice/queen-attack/.meta/template.hbs @@ -0,0 +1,38 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class QueenAttackCalculatorTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq rawCase.property "create")}} + {{#if rawCase.expected.error}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new Queen({{rawCase.input.queen.position.row}}, {{rawCase.input.queen.position.column}})); + {{else}} + new Queen({{rawCase.input.queen.position.row}}, {{rawCase.input.queen.position.column}}); + {{/if}} + {{else if (eq rawCase.property "canAttack")}} + QueenAttackCalculator calculator = new QueenAttackCalculator( + new Queen({{rawCase.input.white_queen.position.row}}, {{rawCase.input.white_queen.position.column}}), + new Queen({{rawCase.input.black_queen.position.row}}, {{rawCase.input.black_queen.position.column}}) + ); + + {{#if (eq rawCase.expected true)}} + assertThat(calculator.canQueensAttackOneAnother()).isTrue(); + {{else}} + assertThat(calculator.canQueensAttackOneAnother()).isFalse(); + {{/if}} + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/rail-fence-cipher/.meta/template.hbs b/exercises/practice/rail-fence-cipher/.meta/template.hbs new file mode 100644 index 000000000..12359fef3 --- /dev/null +++ b/exercises/practice/rail-fence-cipher/.meta/template.hbs @@ -0,0 +1,21 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RailFenceCipherTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new RailFenceCipher({{{formattedInputs.rails}}}) + .{{#if (eq property "encode")}}getEncryptedData{{else}}getDecryptedData{{/if}}({{{formattedInputs.msg}}})) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/rational-numbers/.meta/template.hbs b/exercises/practice/rational-numbers/.meta/template.hbs new file mode 100644 index 000000000..303477826 --- /dev/null +++ b/exercises/practice/rational-numbers/.meta/template.hbs @@ -0,0 +1,26 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.within; + +public class {{testClassName}} { + + private static final double DOUBLE_EQUALITY_TOLERANCE = 1e-8; + + private void assertDoublesEqual(double x, double y) { + assertThat(x).isCloseTo(y, within(DOUBLE_EQUALITY_TOLERANCE)); + } +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderRationalCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/react/.meta/template.hbs b/exercises/practice/react/.meta/template.hbs new file mode 100644 index 000000000..ea2781b1e --- /dev/null +++ b/exercises/practice/react/.meta/template.hbs @@ -0,0 +1,23 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.Consumer; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ReactTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderReactCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/rectangles/.meta/template.hbs b/exercises/practice/rectangles/.meta/template.hbs new file mode 100644 index 000000000..ac1fed935 --- /dev/null +++ b/exercises/practice/rectangles/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderRectanglesCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/relative-distance/.meta/template.hbs b/exercises/practice/relative-distance/.meta/template.hbs new file mode 100644 index 000000000..ee9207d87 --- /dev/null +++ b/exercises/practice/relative-distance/.meta/template.hbs @@ -0,0 +1,30 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RelativeDistanceTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + Map> familyTree = {{{formatJava inputNodes.familyTree}}}; + RelativeDistance rd = new RelativeDistance(familyTree); + + assertThat(rd.degreeOfSeparation("{{escapeJava rawCase.input.personA}}", "{{escapeJava rawCase.input.personB}}")) + {{#if isNullExpected}} + .isEqualTo(-1); + {{else}} + .isEqualTo({{rawCase.expected}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/resistor-color-duo/.meta/template.hbs b/exercises/practice/resistor-color-duo/.meta/template.hbs new file mode 100644 index 000000000..f8cf17dc6 --- /dev/null +++ b/exercises/practice/resistor-color-duo/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ResistorColorDuoTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new ResistorColorDuo().value({{{asStringArray inputNodes.colors}}})) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/resistor-color-trio/.meta/template.hbs b/exercises/practice/resistor-color-trio/.meta/template.hbs new file mode 100644 index 000000000..c1d0e1b5b --- /dev/null +++ b/exercises/practice/resistor-color-trio/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ResistorColorTrioTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new ResistorColorTrio().label({{{asStringArray inputNodes.colors}}})) + .isEqualTo({{{formatResistorLabel rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/resistor-color/.meta/template.hbs b/exercises/practice/resistor-color/.meta/template.hbs new file mode 100644 index 000000000..9200dbcfb --- /dev/null +++ b/exercises/practice/resistor-color/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ResistorColorTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "colors")~}} + assertThat(new ResistorColor().colors()) + .containsExactly({{{formatElements rawCase.expected}}}); + {{~else~}} + assertThat(new ResistorColor().colorCode({{{formattedInputs.color}}})) + .isEqualTo({{{expectedValue}}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/rest-api/.meta/template.hbs b/exercises/practice/rest-api/.meta/template.hbs new file mode 100644 index 000000000..290a30016 --- /dev/null +++ b/exercises/practice/rest-api/.meta/template.hbs @@ -0,0 +1,21 @@ +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RestApiTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderRestApiCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/rna-transcription/.meta/template.hbs b/exercises/practice/rna-transcription/.meta/template.hbs new file mode 100644 index 000000000..de536b9a1 --- /dev/null +++ b/exercises/practice/rna-transcription/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RnaTranscriptionTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new RnaTranscription().transcribe({{{formattedInputs.dna}}})) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/robot-simulator/.meta/template.hbs b/exercises/practice/robot-simulator/.meta/template.hbs new file mode 100644 index 000000000..c8c2f7fa6 --- /dev/null +++ b/exercises/practice/robot-simulator/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RobotTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderRobotCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/roman-numerals/.meta/template.hbs b/exercises/practice/roman-numerals/.meta/template.hbs new file mode 100644 index 000000000..47d7c103e --- /dev/null +++ b/exercises/practice/roman-numerals/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RomanNumeralsTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new RomanNumerals({{{formattedInputs.number}}}).getRomanNumeral()) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/rotational-cipher/.meta/template.hbs b/exercises/practice/rotational-cipher/.meta/template.hbs new file mode 100644 index 000000000..ec2270295 --- /dev/null +++ b/exercises/practice/rotational-cipher/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RotationalCipherTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new RotationalCipher({{{formattedInputs.shiftKey}}}).rotate({{{formattedInputs.text}}})) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/run-length-encoding/.meta/template.hbs b/exercises/practice/run-length-encoding/.meta/template.hbs new file mode 100644 index 000000000..f9a824398 --- /dev/null +++ b/exercises/practice/run-length-encoding/.meta/template.hbs @@ -0,0 +1,27 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RunLengthEncodingTest { + + private RunLengthEncoding runLengthEncoding = new RunLengthEncoding(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq property "consistency")}} + assertThat(runLengthEncoding.decode(runLengthEncoding.encode("{{{escapeJava rawCase.input.string}}}"))) + .isEqualTo("{{{escapeJava rawCase.expected}}}"); + {{else}} + assertThat(runLengthEncoding.{{property}}("{{{escapeJava rawCase.input.string}}}")) + .isEqualTo("{{{escapeJava rawCase.expected}}}"); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/saddle-points/.meta/template.hbs b/exercises/practice/saddle-points/.meta/template.hbs new file mode 100644 index 000000000..9cc5f01fe --- /dev/null +++ b/exercises/practice/saddle-points/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +public class MatrixTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + Matrix matrix = new Matrix({{{as2DIntList rawCase.input.matrix}}}); + + assertThat(matrix.getSaddlePoints()) + .isEqualTo({{{asMatrixCoordinates rawCase.expected}}}); + } +{{/each}} +} diff --git a/exercises/practice/satellite/.meta/template.hbs b/exercises/practice/satellite/.meta/template.hbs new file mode 100644 index 000000000..499e08709 --- /dev/null +++ b/exercises/practice/satellite/.meta/template.hbs @@ -0,0 +1,24 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class {{testClassName}} { + + private Satellite satellite = new Satellite(); +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderSatelliteCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/scrabble-score/.meta/template.hbs b/exercises/practice/scrabble-score/.meta/template.hbs new file mode 100644 index 000000000..2a42a3bab --- /dev/null +++ b/exercises/practice/scrabble-score/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class ScrabbleScoreTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new Scrabble({{{formattedInputs.word}}}).getScore()) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/secret-handshake/.meta/template.hbs b/exercises/practice/secret-handshake/.meta/template.hbs new file mode 100644 index 000000000..c3cd2f7bb --- /dev/null +++ b/exercises/practice/secret-handshake/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class HandshakeCalculatorTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq rawCase.expected.size 0)~}} + assertThat(new HandshakeCalculator().calculateHandshake({{{formattedInputs.number}}})) + .isEmpty(); + {{~else~}} + assertThat(new HandshakeCalculator().calculateHandshake({{{formattedInputs.number}}})) + .containsExactly({{{asSignals rawCase.expected}}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/series/.meta/template.hbs b/exercises/practice/series/.meta/template.hbs new file mode 100644 index 000000000..0aa80bce4 --- /dev/null +++ b/exercises/practice/series/.meta/template.hbs @@ -0,0 +1,39 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class SeriesTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError~}} + {{#if (eq formattedInputs.series "\"\"")~}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new Series({{{formattedInputs.series}}})) + .withMessage("series cannot be empty"); + {{~else if (lte formattedInputs.sliceLength 0)~}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new Series({{{formattedInputs.series}}}).slices({{{formattedInputs.sliceLength}}})) + .withMessage("slice length cannot be negative or zero"); + {{~else~}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> new Series({{{formattedInputs.series}}}).slices({{{formattedInputs.sliceLength}}})) + .withMessage("slice length cannot be greater than series length"); + {{~/if}} + {{~else~}} + assertThat(new Series({{{formattedInputs.series}}}).slices({{{formattedInputs.sliceLength}}})) + .isEqualTo({{{expectedValue}}}); + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/sgf-parsing/.meta/template.hbs b/exercises/practice/sgf-parsing/.meta/template.hbs new file mode 100644 index 000000000..7e55f2346 --- /dev/null +++ b/exercises/practice/sgf-parsing/.meta/template.hbs @@ -0,0 +1,23 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class SgfParsingTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() throws SgfParsingException { + {{{renderSgfCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/sieve/.meta/template.hbs b/exercises/practice/sieve/.meta/template.hbs new file mode 100644 index 000000000..b09ec18bc --- /dev/null +++ b/exercises/practice/sieve/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SieveTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new Sieve({{{formattedInputs.limit}}}).getPrimes()) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/simple-cipher/.meta/src/reference/java/Cipher.java b/exercises/practice/simple-cipher/.meta/src/reference/java/Cipher.java index 2d43669bf..fa2b0247a 100644 --- a/exercises/practice/simple-cipher/.meta/src/reference/java/Cipher.java +++ b/exercises/practice/simple-cipher/.meta/src/reference/java/Cipher.java @@ -66,15 +66,16 @@ private char encodeCharacter(String plainText, int index, String key) { public String decode(String cipherText) { StringBuilder plainText = new StringBuilder(cipherText.length()); + String sameLengthKey = getSufficientlyLongKeyForPlaintext(cipherText, key); for (int i = 0; i < cipherText.length(); i++) { - plainText.append(decodeCharacter(cipherText, i)); + plainText.append(decodeCharacter(cipherText, i, sameLengthKey)); } return plainText.toString(); } - private char decodeCharacter(String cipherText, int index) { + private char decodeCharacter(String cipherText, int index, String key) { int alphabetIdx = ALPHABET .indexOf(cipherText.toCharArray()[index]) - ALPHABET.indexOf(key.toCharArray()[index]); diff --git a/exercises/practice/simple-cipher/.meta/template.hbs b/exercises/practice/simple-cipher/.meta/template.hbs new file mode 100644 index 000000000..5f72c42c4 --- /dev/null +++ b/exercises/practice/simple-cipher/.meta/template.hbs @@ -0,0 +1,28 @@ +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { + + private Cipher randomKeyCipher; + private Cipher substitutionCipher = new Cipher("abcdefghij"); + + @BeforeEach + public void setup() { + randomKeyCipher = new Cipher(); + } +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderSimpleCipherCase this}}} + } +{{/each}} +} diff --git a/exercises/practice/simple-linked-list/.meta/template.hbs b/exercises/practice/simple-linked-list/.meta/template.hbs new file mode 100644 index 000000000..bd9161483 --- /dev/null +++ b/exercises/practice/simple-linked-list/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.NoSuchElementException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class SimpleLinkedListTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderSimpleLinkedListCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/space-age/.meta/template.hbs b/exercises/practice/space-age/.meta/template.hbs new file mode 100644 index 000000000..a108d16b7 --- /dev/null +++ b/exercises/practice/space-age/.meta/template.hbs @@ -0,0 +1,23 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.offset; + +public class SpaceAgeTest { + + private static final double MAXIMUM_DELTA = 1E-02; +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new SpaceAge({{{asLong formattedInputs.seconds}}}).{{spaceAgeMethod inputNodes.planet}}()) + .isEqualTo({{{expectedValue}}}, offset(MAXIMUM_DELTA)); + } +{{/each}} +} diff --git a/exercises/practice/spiral-matrix/.meta/template.hbs b/exercises/practice/spiral-matrix/.meta/template.hbs new file mode 100644 index 000000000..a3c56522a --- /dev/null +++ b/exercises/practice/spiral-matrix/.meta/template.hbs @@ -0,0 +1,32 @@ +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SpiralMatrixBuilderTest { + + private SpiralMatrixBuilder spiralMatrixBuilder; + + @BeforeEach + public void setUp() { + spiralMatrixBuilder = new SpiralMatrixBuilder(); + } + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq rawCase.input.size 0)}} + assertThat(spiralMatrixBuilder.buildMatrixOfSize(0)).isEmpty(); + {{else}} + int[][] expected = {{{as2DIntArray rawCase.expected 8}}}; + assertThat(spiralMatrixBuilder.buildMatrixOfSize({{rawCase.input.size}})).isDeepEqualTo(expected); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/split-second-stopwatch/.meta/template.hbs b/exercises/practice/split-second-stopwatch/.meta/template.hbs new file mode 100644 index 000000000..2fc22f255 --- /dev/null +++ b/exercises/practice/split-second-stopwatch/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class SplitSecondStopwatchTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderStopwatchCommands rawCase.input.commands}}} + } +{{/each}} +} diff --git a/exercises/practice/state-of-tic-tac-toe/.meta/template.hbs b/exercises/practice/state-of-tic-tac-toe/.meta/template.hbs new file mode 100644 index 000000000..a13ff8cce --- /dev/null +++ b/exercises/practice/state-of-tic-tac-toe/.meta/template.hbs @@ -0,0 +1,29 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class StateOfTicTacToeTest { + + private StateOfTicTacToe stateOfTicTacToe = new StateOfTicTacToe(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> stateOfTicTacToe.determineState({{{asStringArray rawCase.input.board}}})) + .withMessage("{{{escapeJava expectedErrorMessage}}}"); + {{else}} + assertThat(stateOfTicTacToe.determineState({{{asStringArray rawCase.input.board}}})) + .isEqualTo(GameState.{{{upper rawCase.expected}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/sublist/.meta/template.hbs b/exercises/practice/sublist/.meta/template.hbs new file mode 100644 index 000000000..7388cb491 --- /dev/null +++ b/exercises/practice/sublist/.meta/template.hbs @@ -0,0 +1,23 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +public class RelationshipComputerTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + Relationship relationship = new RelationshipComputer() + .computeRelationship({{{asIntList rawCase.input.listOne}}}, {{{asIntList rawCase.input.listTwo}}}); + assertThat(relationship).isEqualTo(Relationship.{{upper rawCase.expected}}); + } +{{/each}} +} diff --git a/exercises/practice/sum-of-multiples/.meta/template.hbs b/exercises/practice/sum-of-multiples/.meta/template.hbs new file mode 100644 index 000000000..ca5006044 --- /dev/null +++ b/exercises/practice/sum-of-multiples/.meta/template.hbs @@ -0,0 +1,20 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SumOfMultiplesTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new SumOfMultiples({{{formattedInputs.limit}}}, {{{asIntArray inputNodes.factors}}}).getSum()) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/swift-scheduling/.meta/template.hbs b/exercises/practice/swift-scheduling/.meta/template.hbs new file mode 100644 index 000000000..edcee2b26 --- /dev/null +++ b/exercises/practice/swift-scheduling/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.time.LocalDateTime; + +import static org.assertj.core.api.Assertions.assertThat; + +public class SwiftSchedulingTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + LocalDateTime meetingStart = LocalDateTime.parse("{{{escapeJava rawCase.input.meetingStart}}}"); + LocalDateTime expected = LocalDateTime.parse("{{{escapeJava rawCase.expected}}}"); + + assertThat(SwiftScheduling.convertToDeliveryDate(meetingStart, "{{{escapeJava rawCase.input.description}}}")) + .isEqualTo(expected); + } +{{/each}} +} diff --git a/exercises/practice/tournament/.meta/template.hbs b/exercises/practice/tournament/.meta/template.hbs new file mode 100644 index 000000000..81a443498 --- /dev/null +++ b/exercises/practice/tournament/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TournamentTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderTournamentCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/transpose/.meta/template.hbs b/exercises/practice/transpose/.meta/template.hbs new file mode 100644 index 000000000..a52e449d2 --- /dev/null +++ b/exercises/practice/transpose/.meta/template.hbs @@ -0,0 +1,19 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TransposeTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderTransposeCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/tree-building/.meta/template.hbs b/exercises/practice/tree-building/.meta/template.hbs new file mode 100644 index 000000000..ae7de060e --- /dev/null +++ b/exercises/practice/tree-building/.meta/template.hbs @@ -0,0 +1,30 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class BuildTreeTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() throws InvalidRecordsException { + {{{renderTreeBuildingCase rawCase}}} + } +{{/each}} + + private void assertNode(TreeNode actual, int expectedId, int... expectedChildren) { + assertThat(actual.getNodeId()).isEqualTo(expectedId); + assertThat(actual.getChildren()).hasSize(expectedChildren.length); + for (int i = 0; i < expectedChildren.length; i++) { + assertThat(actual.getChildren().get(i).getNodeId()).isEqualTo(expectedChildren[i]); + } + } +} diff --git a/exercises/practice/triangle/.meta/template.hbs b/exercises/practice/triangle/.meta/template.hbs new file mode 100644 index 000000000..528b1f26e --- /dev/null +++ b/exercises/practice/triangle/.meta/template.hbs @@ -0,0 +1,26 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class TriangleTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() throws TriangleException { + {{#if (isIllegalTriangle inputNodes.sides)~}} + assertThatExceptionOfType(TriangleException.class) + .isThrownBy(() -> new Triangle({{{formatElements inputNodes.sides}}})); + {{~else~}} + assertThat(new Triangle({{{formatElements inputNodes.sides}}}).is{{pascalCase property}}()) + .{{#if (eq expectedValue "true")}}isTrue(){{else}}isFalse(){{/if}}; + {{~/if}} + } +{{/each}} +} diff --git a/exercises/practice/twelve-days/.meta/template.hbs b/exercises/practice/twelve-days/.meta/template.hbs new file mode 100644 index 000000000..422d9c124 --- /dev/null +++ b/exercises/practice/twelve-days/.meta/template.hbs @@ -0,0 +1,30 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class TwelveDaysTest { + + private TwelveDays twelveDays = new TwelveDays(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if (eq rawCase.input.startVerse rawCase.input.endVerse)}} + assertThat(twelveDays.verse({{{formattedInputs.startVerse}}})) + .isEqualTo({{{twelveDaysExpected rawCase.expected}}}); + {{else}}{{#if (and (eq rawCase.input.startVerse 1) (eq rawCase.input.endVerse 12))}} + assertThat(twelveDays.sing()) + .isEqualTo({{{twelveDaysExpected rawCase.expected}}}); + {{else}} + assertThat(twelveDays.verses({{{formattedInputs.startVerse}}}, {{{formattedInputs.endVerse}}})) + .isEqualTo({{{twelveDaysExpected rawCase.expected}}}); + {{/if}}{{/if}} + } +{{/each}} +} diff --git a/exercises/practice/two-bucket/.meta/template.hbs b/exercises/practice/two-bucket/.meta/template.hbs new file mode 100644 index 000000000..870351493 --- /dev/null +++ b/exercises/practice/two-bucket/.meta/template.hbs @@ -0,0 +1,39 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class TwoBucketTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if rawCase.expected.error}} + assertThatExceptionOfType(UnreachableGoalException.class) + .isThrownBy(() -> new TwoBucket( + {{rawCase.input.bucketOne}}, + {{rawCase.input.bucketTwo}}, + {{rawCase.input.goal}}, + "{{rawCase.input.startBucket}}" + ).getResult()); + {{else}} + Result bucketResult = new TwoBucket( + {{rawCase.input.bucketOne}}, + {{rawCase.input.bucketTwo}}, + {{rawCase.input.goal}}, + "{{rawCase.input.startBucket}}" + ).getResult(); + + assertThat(bucketResult.getTotalMoves()).isEqualTo({{rawCase.expected.moves}}); + assertThat(bucketResult.getFinalBucket()).isEqualTo("{{rawCase.expected.goalBucket}}"); + assertThat(bucketResult.getOtherBucket()).isEqualTo({{rawCase.expected.otherBucket}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/two-fer/.meta/template.hbs b/exercises/practice/two-fer/.meta/template.hbs new file mode 100644 index 000000000..d004e3371 --- /dev/null +++ b/exercises/practice/two-fer/.meta/template.hbs @@ -0,0 +1,28 @@ +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { + + private Twofer twofer; + + @BeforeEach + public void setup() { + twofer = new Twofer(); + } +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + @DisplayName("{{{description}}}") + public void {{methodName}}() { + assertThat(twofer.twofer({{{formattedInputs.name}}})) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/variable-length-quantity/.meta/template.hbs b/exercises/practice/variable-length-quantity/.meta/template.hbs new file mode 100644 index 000000000..4e8eee2ba --- /dev/null +++ b/exercises/practice/variable-length-quantity/.meta/template.hbs @@ -0,0 +1,31 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class VariableLengthQuantityTest { + + private VariableLengthQuantity variableLengthQuantity = new VariableLengthQuantity(); +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if expectedError}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> variableLengthQuantity.decode({{{asHexLongList rawCase.input.integers}}})) + .withMessage("Invalid variable-length quantity encoding"); + {{else}} + assertThat(variableLengthQuantity.{{rawCase.property}}({{{asHexLongList rawCase.input.integers}}})) + .isEqualTo({{{asHexStringList rawCase.expected}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/word-count/.meta/template.hbs b/exercises/practice/word-count/.meta/template.hbs new file mode 100644 index 000000000..a0efdaf7d --- /dev/null +++ b/exercises/practice/word-count/.meta/template.hbs @@ -0,0 +1,22 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.assertj.core.api.Assertions.assertThat; + +public class WordCountTest { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new WordCount().phrase({{{formattedInputs.sentence}}})) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/word-search/.meta/template.hbs b/exercises/practice/word-search/.meta/template.hbs new file mode 100644 index 000000000..4d8122573 --- /dev/null +++ b/exercises/practice/word-search/.meta/template.hbs @@ -0,0 +1,24 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +public class WordSearcherTest { + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderWordSearchCase rawCase}}} + } +{{/each}} +} diff --git a/exercises/practice/wordy/.meta/template.hbs b/exercises/practice/wordy/.meta/template.hbs new file mode 100644 index 000000000..3aa7805f3 --- /dev/null +++ b/exercises/practice/wordy/.meta/template.hbs @@ -0,0 +1,28 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; + +public class WordProblemSolverTest { + + private WordProblemSolver solver = new WordProblemSolver(); + +{{#each testCases}} + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{#if rawCase.expected.error}} + assertThatExceptionOfType(IllegalArgumentException.class) + .isThrownBy(() -> solver.solve("{{{escapeJava rawCase.input.question}}}")) + .withMessage("I'm sorry, I don't understand the question!"); + {{else}} + assertThat(solver.solve("{{{escapeJava rawCase.input.question}}}")).isEqualTo({{rawCase.expected}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/yacht/.meta/template.hbs b/exercises/practice/yacht/.meta/template.hbs new file mode 100644 index 000000000..ae809b5a9 --- /dev/null +++ b/exercises/practice/yacht/.meta/template.hbs @@ -0,0 +1,21 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class YachtTest { +{{#each testCases}} + + {{#if disabled}} + @Disabled("Remove to run test") + {{/if}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + assertThat(new Yacht({{{asIntArray rawCase.input.dice}}}, YachtCategory.{{{toYachtCategory rawCase.input.category}}}) + .score()) + .isEqualTo({{{expectedValue}}}); + } +{{/each}} +} diff --git a/exercises/practice/zebra-puzzle/.meta/template.hbs b/exercises/practice/zebra-puzzle/.meta/template.hbs new file mode 100644 index 000000000..c1c172b63 --- /dev/null +++ b/exercises/practice/zebra-puzzle/.meta/template.hbs @@ -0,0 +1,25 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + @DisplayName("{{{description}}}") + public void {{methodName}}() { + ZebraPuzzle zebraPuzzle = new ZebraPuzzle(); + {{#if (eq property "drinksWater")}} + assertThat(zebraPuzzle.getWaterDrinker()).isEqualTo({{{expectedValue}}}); + {{/if}} + {{#if (eq property "ownsZebra")}} + assertThat(zebraPuzzle.getZebraOwner()).isEqualTo({{{expectedValue}}}); + {{/if}} + } +{{/each}} +} diff --git a/exercises/practice/zipper/.meta/template.hbs b/exercises/practice/zipper/.meta/template.hbs new file mode 100644 index 000000000..f8041d70b --- /dev/null +++ b/exercises/practice/zipper/.meta/template.hbs @@ -0,0 +1,34 @@ +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class {{testClassName}} { + + Zipper zipper; + BinaryTree binaryTree; + + @BeforeEach + public void setup() { + zipper = new Zipper(1); + binaryTree = new BinaryTree(zipper); + + zipper.setLeft(new Zipper(2)); + zipper.left.setRight(new Zipper(3)); + + zipper.setRight(new Zipper(4)); + } +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{renderZipperCase this}}} + } +{{/each}} +} diff --git a/test-generator/README.md b/test-generator/README.md new file mode 100644 index 000000000..c2393e2ae --- /dev/null +++ b/test-generator/README.md @@ -0,0 +1,91 @@ +# Exercism Java Test Generator + +The **Java Track Test Generator** is an automated tool that synchronizes and generates JUnit 5 practice exercise test suites directly from upstream canonical data ([`exercism/problem-specifications`](https://github.com/exercism/problem-specifications)) and the track's [`.meta/tests.toml`](https://exercism.org/docs/building/tracks/tests-toml) configuration. + +## Features + +- **Upstream Synchronization**: Fetches `canonical-data.json` directly from GitHub, local sibling directories (`../problem-specifications`), or cached downloads. +- **`tests.toml` Awareness**: Automatically includes active tests and excludes any tests marked `include = false`. Respects `reimplements` UUID mappings. +- **Idiomatic JUnit 5 + AssertJ**: Generates standard annotations (`@Test`, `@DisplayName`, `@Disabled("Remove to run test")` on subsequent tests, and `assertThat` / `assertThatExceptionOfType`). +- **Zero-Config Formatting**: Automatically cleans up and normalizes indentation and annotation spacing in generated files. +- **Template-Driven**: Uses Handlebars templates with a clean fallback system: + 1. If an exercise has `.meta/template.hbs`, that template is rendered. + 2. Otherwise, the built-in `default.hbs` template is used. +- **Dry-run Support**: Preview generated test suites in the console before writing to disk. + +--- + +## Usage + +### 1. Using the CLI Script (Recommended) + +From the repository root, use the `bin/generate-tests` wrapper (it builds the distribution binary on first run): + +```bash +# Show help and all CLI options +./bin/generate-tests --help + +# Generate tests for a single exercise +./bin/generate-tests -e acronym + +# Generate tests for multiple exercises +./bin/generate-tests -e acronym -e two-fer -e hamming + +# Dry run (print generated test suite to console without writing to disk) +./bin/generate-tests -e two-fer -d + +# Generate tests for all practice exercises +./bin/generate-tests -a + +# Bypass cache and re-fetch canonical data from upstream GitHub +./bin/generate-tests -e acronym -f + +# Use a local problem-specifications directory instead of downloading +./bin/generate-tests -a -p ../problem-specifications +``` + +### 2. Using Gradle Directly + +From the `test-generator/` directory: + +```bash +# Build & install the distribution binary +./gradlew installDist + +# Run unit tests +./gradlew test + +# Run generator via Gradle +./gradlew run --args="-e acronym" +./gradlew run --args="-a" +``` + +--- + +## Exercise-Specific Templates + +If an exercise has a custom API (such as stateful objects, builder patterns, or custom method signatures), add a `template.hbs` inside the exercise's `.meta/` directory: + +`exercises/practice//.meta/template.hbs` + +### Available Context Variables: +- `testClassName`: e.g. `AcronymTest` +- `solutionClassName`: e.g. `Acronym` +- `hasExceptions`: boolean (true if any active test case expects an error) +- `testCases`: list of active test cases, each containing: + - `uuid`: canonical test UUID + - `description`: canonical test description + - `methodName`: sanitized camelCase Java method name + - `disabled`: boolean (true for all tests after the first one) + - `expectedError`: boolean (true if an exception is expected) + - `expectedException`: e.g. `IllegalArgumentException` + - `expectedErrorMessage`: message expected from the exception + - `expectedValue`: formatted Java literal (e.g. `"PNG"`, `List.of(...)`, `42L`) + - `formattedInputs`: map of parameter names to formatted Java literals (e.g. `formattedInputs.phrase`) + - `invocationCode`: default method invocation string + - `rawCase`: raw canonical JSON case node (for custom helper inspection) + +### Built-in Helpers: +- `renderExceptionAssertion`: formats standard AssertJ `assertThatExceptionOfType` blocks +- `asIntList`, `asStringList`, `as2DIntArray`, `asStringArray`: helpers for array/list literals +- Exercise-specific helpers registered in `TemplateRenderer` (e.g., `renderClockCase`, `renderListOpsCase`, etc.) diff --git a/test-generator/build.gradle b/test-generator/build.gradle new file mode 100644 index 000000000..2605cb8d4 --- /dev/null +++ b/test-generator/build.gradle @@ -0,0 +1,42 @@ +plugins { + id 'application' + id 'java' +} + +repositories { + mavenCentral() +} + +java { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 +} + +dependencies { + implementation 'info.picocli:picocli:4.7.6' + annotationProcessor 'info.picocli:picocli-codegen:4.7.6' + + implementation 'com.fasterxml.jackson.core:jackson-databind:2.18.1' + implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-toml:2.18.1' + + implementation 'com.github.jknack:handlebars:4.3.1' + implementation 'com.github.jknack:handlebars-jackson2:4.3.1' + implementation 'org.slf4j:slf4j-nop:1.7.36' + + testImplementation platform('org.junit:junit-bom:5.10.2') + testImplementation 'org.junit.jupiter:junit-jupiter' + testImplementation 'org.assertj:assertj-core:3.25.3' + testRuntimeOnly 'org.junit.platform:junit-platform-launcher' +} + +application { + mainClass = 'exercism.testgenerator.TestGeneratorApp' +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +test { + useJUnitPlatform() +} diff --git a/test-generator/gradle/wrapper/gradle-wrapper.jar b/test-generator/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..b1b8ef56b Binary files /dev/null and b/test-generator/gradle/wrapper/gradle-wrapper.jar differ diff --git a/test-generator/gradle/wrapper/gradle-wrapper.properties b/test-generator/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..6394b4647 --- /dev/null +++ b/test-generator/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.5.0-bin.zip +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/test-generator/gradlew b/test-generator/gradlew new file mode 100644 index 000000000..b9bb139f7 --- /dev/null +++ b/test-generator/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 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. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# 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/3d91ce3b8caaf77ad09f381f43615b715b53f72c/platforms/jvm/plugins-application/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 + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# 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 + + + +# 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 + if ! command -v java >/dev/null 2>&1 + then + 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 +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + 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" ) + + 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 + + +# 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"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# 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/test-generator/gradlew.bat b/test-generator/gradlew.bat new file mode 100644 index 000000000..24c62d56f --- /dev/null +++ b/test-generator/gradlew.bat @@ -0,0 +1,82 @@ +@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 +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables, and ensure extensions are enabled +setlocal EnableExtensions + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +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% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +"%COMSPEC%" /c exit 1 + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +@rem endlocal doesn't take effect until after the line is parsed and variables are expanded +@rem which allows us to clear the local environment before executing the java command +endlocal & "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* & call :exitWithErrorLevel + +:exitWithErrorLevel +@rem Use "%COMSPEC%" /c exit to allow operators to work properly in scripts +"%COMSPEC%" /c exit %ERRORLEVEL% diff --git a/test-generator/settings.gradle b/test-generator/settings.gradle new file mode 100644 index 000000000..b1dab54ce --- /dev/null +++ b/test-generator/settings.gradle @@ -0,0 +1 @@ +rootProject.name = 'test-generator' diff --git a/test-generator/src/main/java/exercism/testgenerator/TestGeneratorApp.java b/test-generator/src/main/java/exercism/testgenerator/TestGeneratorApp.java new file mode 100644 index 000000000..97c391d8e --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/TestGeneratorApp.java @@ -0,0 +1,241 @@ +package exercism.testgenerator; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import exercism.testgenerator.model.CanonicalDataNotFoundException; +import exercism.testgenerator.service.ExerciseTestGenerator; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.stream.Stream; +import picocli.CommandLine; +import picocli.CommandLine.Command; +import picocli.CommandLine.Option; + +@Command( + name = "test-generator", + mixinStandardHelpOptions = true, + version = "1.1.0", + description = "Generates and updates JUnit test files for Exercism Java practice exercises from upstream canonical data." +) +public class TestGeneratorApp implements Callable { + + @Option( + names = {"-e", "--exercise"}, + description = "One or more exercise slugs to generate tests for (e.g. -e acronym -e two-fer)" + ) + private List exercises = new ArrayList<>(); + + @Option( + names = {"-a", "--all"}, + description = "Generate tests for all practice exercises" + ) + private boolean all; + + @Option( + names = {"-d", "--dry-run"}, + description = "Print generated code to console without writing files" + ) + private boolean dryRun; + + @Option( + names = {"--audit"}, + description = "Run track audit across exercises without writing files, summarizing template usage and issues" + ) + private boolean audit; + + @Option( + names = {"--include-deprecated"}, + description = "Include deprecated exercises when running with --all" + ) + private boolean includeDeprecated; + + @Option( + names = {"-p", "--path"}, + description = "Path to the root of the exercism/java repository" + ) + private Path repositoryRoot; + + private final ExerciseTestGenerator generator = new ExerciseTestGenerator(); + private final ObjectMapper mapper = new ObjectMapper(); + + public static void main(String[] args) { + int exitCode = new CommandLine(new TestGeneratorApp()).execute(args); + System.exit(exitCode); + } + + @Override + public Integer call() { + Path repoRoot = resolveRepositoryRoot(); + if (repoRoot == null) { + System.err.println("Error: Could not locate exercism/java repository root with 'exercises/practice' folder."); + return 1; + } + + Path practiceDir = repoRoot.resolve("exercises").resolve("practice"); + if (!Files.isDirectory(practiceDir)) { + System.err.println("Error: Directory not found: " + practiceDir); + return 1; + } + + Set deprecatedSlugs = loadDeprecatedExercises(repoRoot); + List targets = new ArrayList<>(exercises); + + if (all) { + try (Stream stream = Files.list(practiceDir)) { + List allSlugs = stream + .filter(Files::isDirectory) + .filter(p -> Files.exists(p.resolve(".meta").resolve("config.json"))) + .map(p -> p.getFileName().toString()) + .filter(slug -> includeDeprecated || !deprecatedSlugs.contains(slug)) + .sorted() + .toList(); + targets.addAll(allSlugs); + } catch (IOException e) { + System.err.println("Failed to list exercises: " + e.getMessage()); + return 1; + } + } + + if (targets.isEmpty()) { + System.err.println("Error: Please specify at least one exercise using -e/--exercise or use --all."); + new CommandLine(this).usage(System.out); + return 1; + } + + System.out.printf("🚀 Running Exercism Java Test Generator for %d exercise(s)...%n%n", targets.size()); + + int defaultTemplateCount = 0; + int customTemplateCount = 0; + int noCanonicalDataCount = 0; + int failureCount = 0; + + for (String slug : targets) { + Path exerciseDir = practiceDir.resolve(slug); + if (!Files.isDirectory(exerciseDir)) { + System.err.printf("❌ Exercise '%s' not found at %s%n", slug, exerciseDir); + failureCount++; + continue; + } + + boolean hasCustomTemplate = Files.exists(exerciseDir.resolve(".meta").resolve("template.hbs")); + + try { + if (!audit) { + System.out.printf("🔄 Processing '%s'...", slug); + } + ExerciseTestGenerator.GenerationResult result = generator.generate(exerciseDir); + + if (result.includedCasesCount() == 0) { + noCanonicalDataCount++; + if (audit) { + System.out.printf(" [SKIP] %-28s (all test cases excluded in tests.toml)%n", slug); + } else { + System.out.printf(" ⚠️ Skipped '%s': all test cases excluded in tests.toml%n", slug); + } + continue; + } + + if (hasCustomTemplate) { + customTemplateCount++; + } else { + defaultTemplateCount++; + } + + if (audit) { + String templateType = hasCustomTemplate ? "custom template" : "default template"; + System.out.printf(" [OK] %-30s (%2d cases, %s)%n", slug, result.includedCasesCount(), templateType); + } else if (dryRun) { + System.out.printf(" [DRY RUN - %d tests included, %d excluded]%n", + result.includedCasesCount(), result.excludedCasesCount()); + System.out.println("----------------------------------------"); + System.out.println(result.content()); + System.out.println("----------------------------------------"); + } else { + result.writeToFile(); + System.out.printf(" ✅ Generated %s (%d test cases included, %d excluded)%n", + repoRoot.relativize(result.targetTestPath()), + result.includedCasesCount(), + result.excludedCasesCount()); + } + } catch (CanonicalDataNotFoundException e) { + noCanonicalDataCount++; + if (audit) { + System.out.printf(" [SKIP] %-28s (track-specific, no upstream canonical data)%n", slug); + } else { + System.out.printf(" ⚠️ Skipped: %s%n", e.getMessage()); + } + } catch (Exception e) { + failureCount++; + if (audit) { + System.out.printf(" [FAIL] %-28s : %s%n", slug, e.getMessage()); + } else { + System.out.printf(" ❌ Failed: %s%n", e.getMessage()); + } + } + } + + int totalEvaluated = defaultTemplateCount + customTemplateCount + noCanonicalDataCount + failureCount; + System.out.println(); + System.out.println("============================================================"); + System.out.println("Test Generator Summary"); + System.out.println("============================================================"); + System.out.printf("Total evaluated: %d%n", totalEvaluated); + System.out.printf(" - With default template: %d%n", defaultTemplateCount); + System.out.printf(" - With custom template: %d%n", customTemplateCount); + System.out.printf(" - Track-specific (skipped): %d%n", noCanonicalDataCount); + System.out.printf(" - Failures: %d%n", failureCount); + if (!includeDeprecated && !deprecatedSlugs.isEmpty()) { + System.out.printf(" - Deprecated (skipped): %d%n", deprecatedSlugs.size()); + } + System.out.println("============================================================"); + + return failureCount == 0 ? 0 : 1; + } + + private Set loadDeprecatedExercises(Path repoRoot) { + Set deprecated = new HashSet<>(); + Path configPath = repoRoot.resolve("config.json"); + if (!Files.exists(configPath)) { + return deprecated; + } + + try { + JsonNode root = mapper.readTree(configPath.toFile()); + JsonNode practice = root.path("exercises").path("practice"); + if (practice.isArray()) { + for (JsonNode node : practice) { + if ("deprecated".equalsIgnoreCase(node.path("status").asText())) { + deprecated.add(node.path("slug").asText()); + } + } + } + } catch (Exception ignored) { + } + return deprecated; + } + + private Path resolveRepositoryRoot() { + if (repositoryRoot != null) { + return repositoryRoot.toAbsolutePath().normalize(); + } + + Path current = Paths.get("").toAbsolutePath().normalize(); + if (Files.isDirectory(current.resolve("exercises").resolve("practice"))) { + return current; + } + + Path parent = current.getParent(); + if (parent != null && Files.isDirectory(parent.resolve("exercises").resolve("practice"))) { + return parent; + } + + return null; + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/model/CanonicalCase.java b/test-generator/src/main/java/exercism/testgenerator/model/CanonicalCase.java new file mode 100644 index 000000000..11ce70807 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/model/CanonicalCase.java @@ -0,0 +1,27 @@ +package exercism.testgenerator.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record CanonicalCase( + String uuid, + String description, + String property, + JsonNode input, + JsonNode expected, + List scenarios, + List comments +) { + public boolean isErrorExpected() { + return expected != null && expected.isObject() && expected.has("error"); + } + + public String getExpectedErrorMessage() { + if (isErrorExpected()) { + return expected.get("error").asText(); + } + return null; + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/model/CanonicalData.java b/test-generator/src/main/java/exercism/testgenerator/model/CanonicalData.java new file mode 100644 index 000000000..193bac064 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/model/CanonicalData.java @@ -0,0 +1,12 @@ +package exercism.testgenerator.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record CanonicalData( + String exercise, + List cases, + List comments +) {} diff --git a/test-generator/src/main/java/exercism/testgenerator/model/CanonicalDataNotFoundException.java b/test-generator/src/main/java/exercism/testgenerator/model/CanonicalDataNotFoundException.java new file mode 100644 index 000000000..dd89d5d61 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/model/CanonicalDataNotFoundException.java @@ -0,0 +1,16 @@ +package exercism.testgenerator.model; + +import java.io.IOException; + +public class CanonicalDataNotFoundException extends IOException { + private final String exerciseSlug; + + public CanonicalDataNotFoundException(String exerciseSlug, String message) { + super(message); + this.exerciseSlug = exerciseSlug; + } + + public String getExerciseSlug() { + return exerciseSlug; + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/model/ExerciseConfig.java b/test-generator/src/main/java/exercism/testgenerator/model/ExerciseConfig.java new file mode 100644 index 000000000..bc41f9ffc --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/model/ExerciseConfig.java @@ -0,0 +1,53 @@ +package exercism.testgenerator.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.List; +import java.util.Map; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record ExerciseConfig( + Map> files, + String blurb +) { + public String getTestFilePath() { + if (files != null && files.containsKey("test") && !files.get("test").isEmpty()) { + return files.get("test").get(0); + } + return null; + } + + public String getSolutionFilePath() { + if (files != null && files.containsKey("solution") && !files.get("solution").isEmpty()) { + return files.get("solution").get(0); + } + return null; + } + + public String getTestClassName() { + String testPath = getTestFilePath(); + if (testPath == null) { + return null; + } + Path path = Paths.get(testPath); + String fileName = path.getFileName().toString(); + if (fileName.endsWith(".java")) { + return fileName.substring(0, fileName.length() - 5); + } + return fileName; + } + + public String getSolutionClassName() { + String solPath = getSolutionFilePath(); + if (solPath == null) { + return null; + } + Path path = Paths.get(solPath); + String fileName = path.getFileName().toString(); + if (fileName.endsWith(".java")) { + return fileName.substring(0, fileName.length() - 5); + } + return fileName; + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/model/RenderedExercise.java b/test-generator/src/main/java/exercism/testgenerator/model/RenderedExercise.java new file mode 100644 index 000000000..4ef8725c8 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/model/RenderedExercise.java @@ -0,0 +1,20 @@ +package exercism.testgenerator.model; + +import java.util.List; + +public record RenderedExercise( + String exerciseSlug, + String testClassName, + String solutionClassName, + boolean hasExceptions, + boolean hasFloatingPoint, + boolean hasList, + boolean hasMap, + boolean hasSet, + boolean hasDisabled, + List testCases +) { + public boolean hasCollections() { + return hasList || hasMap || hasSet; + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/model/RenderedTestCase.java b/test-generator/src/main/java/exercism/testgenerator/model/RenderedTestCase.java new file mode 100644 index 000000000..3e7000a70 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/model/RenderedTestCase.java @@ -0,0 +1,70 @@ +package exercism.testgenerator.model; + +import com.fasterxml.jackson.databind.JsonNode; +import java.util.Map; + +public record RenderedTestCase( + String uuid, + String description, + String methodName, + boolean disabled, + boolean expectedError, + String expectedException, + String expectedErrorMessage, + boolean isNullExpected, + boolean isBooleanExpected, + boolean booleanValue, + boolean isFloatingPointExpected, + String expectedValue, + String invocationCode, + String property, + Map formattedInputs, + Map inputNodes, + JsonNode rawInput, + CanonicalCase rawCase +) { + public String assertionCode() { + if (expectedError) { + String msg = (expectedErrorMessage != null && !expectedErrorMessage.isBlank()) + ? "\n .withMessage(\"" + exercism.testgenerator.service.JavaTypeFormatter.escapeJavaString(expectedErrorMessage) + "\")" + : ""; + return "assertThatExceptionOfType(" + expectedException + ".class)\n" + + " .isThrownBy(() -> " + invocationCode + ")" + + msg + ";"; + } + if (isNullExpected) { + return "assertThat(" + invocationCode + ")\n .isNull();"; + } + if (isBooleanExpected) { + return "assertThat(" + invocationCode + ")\n ." + (booleanValue ? "isTrue" : "isFalse") + "();"; + } + if (isFloatingPointExpected) { + return "assertThat(" + invocationCode + ")\n .isEqualTo(" + expectedValue + ", offset(0.01));"; + } + return "assertThat(" + invocationCode + ")\n .isEqualTo(" + expectedValue + ");"; + } + + public String displayNameAnnotation() { + if (description == null || description.isBlank()) { + return "@DisplayName(\"\")"; + } + String escaped = exercism.testgenerator.service.JavaTypeFormatter.escapeJavaString(description); + if (escaped.length() <= 85) { + return "@DisplayName(\"" + escaped + "\")"; + } + java.util.List chunks = new java.util.ArrayList<>(); + int start = 0; + while (start < escaped.length()) { + int end = Math.min(start + 70, escaped.length()); + if (end < escaped.length()) { + int lastSpace = escaped.lastIndexOf(' ', end); + if (lastSpace > start + 30) { + end = lastSpace + 1; + } + } + chunks.add("\"" + escaped.substring(start, end) + "\""); + start = end; + } + return "@DisplayName(" + String.join("\n + ", chunks) + ")"; + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/model/TestCaseConfig.java b/test-generator/src/main/java/exercism/testgenerator/model/TestCaseConfig.java new file mode 100644 index 000000000..a65fc8eb4 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/model/TestCaseConfig.java @@ -0,0 +1,16 @@ +package exercism.testgenerator.model; + +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; +import com.fasterxml.jackson.annotation.JsonProperty; + +@JsonIgnoreProperties(ignoreUnknown = true) +public record TestCaseConfig( + String description, + @JsonProperty("include") Boolean include, + String reimplements, + String comment +) { + public boolean isIncluded() { + return include == null || Boolean.TRUE.equals(include); + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/service/CaseFlattener.java b/test-generator/src/main/java/exercism/testgenerator/service/CaseFlattener.java new file mode 100644 index 000000000..5e2cfd681 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/service/CaseFlattener.java @@ -0,0 +1,75 @@ +package exercism.testgenerator.service; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import exercism.testgenerator.model.CanonicalCase; +import java.util.ArrayList; +import java.util.List; + +public class CaseFlattener { + + private final ObjectMapper objectMapper; + + public CaseFlattener() { + this(new ObjectMapper()); + } + + public CaseFlattener(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + public List flatten(List rawCases) { + List flattened = new ArrayList<>(); + if (rawCases == null) { + return flattened; + } + + for (JsonNode node : rawCases) { + collectCases(node, new ArrayList<>(), flattened); + } + return flattened; + } + + private void collectCases(JsonNode node, List parentDescriptions, List result) { + if (node == null || node.isNull()) { + return; + } + + if (node.hasNonNull("uuid")) { + try { + CanonicalCase rawCase = objectMapper.treeToValue(node, CanonicalCase.class); + String fullDescription; + if (!parentDescriptions.isEmpty()) { + String desc = (rawCase.description() != null && !rawCase.description().isBlank()) + ? rawCase.description() + : ""; + fullDescription = String.join(" -> ", parentDescriptions) + (!desc.isEmpty() ? " -> " + desc : ""); + } else { + fullDescription = rawCase.description(); + } + + CanonicalCase canonicalCase = new CanonicalCase( + rawCase.uuid(), + fullDescription, + rawCase.property(), + rawCase.input(), + rawCase.expected(), + rawCase.scenarios(), + rawCase.comments() + ); + result.add(canonicalCase); + } catch (JsonProcessingException e) { + throw new RuntimeException("Failed to parse canonical case: " + node, e); + } + } else if (node.has("cases") && node.get("cases").isArray()) { + List nextParents = new ArrayList<>(parentDescriptions); + if (node.hasNonNull("description") && !node.get("description").asText().isBlank()) { + nextParents.add(node.get("description").asText().trim()); + } + for (JsonNode subNode : node.get("cases")) { + collectCases(subNode, nextParents, result); + } + } + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/service/ExerciseConfigService.java b/test-generator/src/main/java/exercism/testgenerator/service/ExerciseConfigService.java new file mode 100644 index 000000000..6d7f322b6 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/service/ExerciseConfigService.java @@ -0,0 +1,31 @@ +package exercism.testgenerator.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import exercism.testgenerator.model.ExerciseConfig; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; + +public class ExerciseConfigService { + + private final ObjectMapper objectMapper; + + public ExerciseConfigService() { + this(new ObjectMapper()); + } + + public ExerciseConfigService(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + public ExerciseConfig parseConfig(Path configPath) throws IOException { + if (!Files.exists(configPath)) { + throw new IOException("Exercise config file not found at: " + configPath); + } + return parseConfig(Files.readString(configPath)); + } + + public ExerciseConfig parseConfig(String jsonContent) throws IOException { + return objectMapper.readValue(jsonContent, ExerciseConfig.class); + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/service/ExerciseTestGenerator.java b/test-generator/src/main/java/exercism/testgenerator/service/ExerciseTestGenerator.java new file mode 100644 index 000000000..41e1f0e31 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/service/ExerciseTestGenerator.java @@ -0,0 +1,233 @@ +package exercism.testgenerator.service; + +import com.fasterxml.jackson.databind.JsonNode; +import exercism.testgenerator.model.CanonicalCase; +import exercism.testgenerator.model.CanonicalData; +import exercism.testgenerator.model.ExerciseConfig; +import exercism.testgenerator.model.RenderedExercise; +import exercism.testgenerator.model.RenderedTestCase; +import exercism.testgenerator.model.TestCaseConfig; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +public class ExerciseTestGenerator { + + private final ProblemSpecService problemSpecService; + private final TestsTomlService testsTomlService; + private final ExerciseConfigService exerciseConfigService; + private final CaseFlattener caseFlattener; + private final TemplateRenderer templateRenderer; + + public ExerciseTestGenerator() { + this( + new ProblemSpecService(), + new TestsTomlService(), + new ExerciseConfigService(), + new CaseFlattener(), + new TemplateRenderer() + ); + } + + public ExerciseTestGenerator( + ProblemSpecService problemSpecService, + TestsTomlService testsTomlService, + ExerciseConfigService exerciseConfigService, + CaseFlattener caseFlattener, + TemplateRenderer templateRenderer + ) { + this.problemSpecService = problemSpecService; + this.testsTomlService = testsTomlService; + this.exerciseConfigService = exerciseConfigService; + this.caseFlattener = caseFlattener; + this.templateRenderer = templateRenderer; + } + + public GenerationResult generate(Path exerciseDirectory) throws IOException, InterruptedException { + String slug = exerciseDirectory.getFileName().toString(); + Path metaDir = exerciseDirectory.resolve(".meta"); + Path configPath = metaDir.resolve("config.json"); + Path testsTomlPath = metaDir.resolve("tests.toml"); + + ExerciseConfig config = exerciseConfigService.parseConfig(configPath); + Map tomlConfigs = testsTomlService.parseTestsToml(testsTomlPath); + + CanonicalData canonicalData = problemSpecService.fetchCanonicalData(slug); + List allCases = caseFlattener.flatten(canonicalData.cases()); + + List activeCases = allCases.stream() + .filter(c -> testsTomlService.isCaseIncluded(tomlConfigs, c.uuid())) + .toList(); + + Path targetTestPath = exerciseDirectory.resolve(config.getTestFilePath()); + if (activeCases.isEmpty()) { + return new GenerationResult(slug, targetTestPath, null, 0, allCases.size()); + } + + String testClassName = config.getTestClassName(); + if (testClassName == null || testClassName.isBlank()) { + testClassName = JavaNamingHelper.toPascalCase(slug) + "Test"; + } + + String solutionClassName = config.getSolutionClassName(); + if (solutionClassName == null || solutionClassName.isBlank()) { + solutionClassName = JavaNamingHelper.toPascalCase(slug); + } + + List renderedCases = new ArrayList<>(); + boolean hasExceptions = false; + boolean hasFloatingPoint = false; + boolean hasList = false; + boolean hasMap = false; + boolean hasSet = false; + Map methodNameCounts = new LinkedHashMap<>(); + + for (int i = 0; i < activeCases.size(); i++) { + CanonicalCase c = activeCases.get(i); + boolean disabled = (i > 0); + + String baseMethodName = JavaNamingHelper.toMethodName(c.description()); + int count = methodNameCounts.getOrDefault(baseMethodName, 0) + 1; + methodNameCounts.put(baseMethodName, count); + String methodName = (count == 1) ? baseMethodName : baseMethodName + count; + Map formattedInputs = new LinkedHashMap<>(); + Map inputNodes = new LinkedHashMap<>(); + List rawArgValues = new ArrayList<>(); + + if (c.input() != null && c.input().isObject()) { + Iterator> fields = c.input().fields(); + while (fields.hasNext()) { + Map.Entry field = fields.next(); + String formatted = JavaTypeFormatter.format(field.getValue()); + formattedInputs.put(field.getKey(), formatted); + inputNodes.put(field.getKey(), field.getValue()); + rawArgValues.add(formatted); + } + } else if (c.input() != null) { + String formatted = JavaTypeFormatter.format(c.input()); + formattedInputs.put("input", formatted); + inputNodes.put("input", c.input()); + rawArgValues.add(formatted); + } + + String property = c.property() != null ? c.property() : "run"; + String singleLineArgs = String.join(", ", rawArgValues); + String invocationCode; + if (singleLineArgs.length() > 60 && rawArgValues.size() > 1) { + invocationCode = "new " + solutionClassName + "()." + property + "(\n" + + " " + String.join(",\n ", rawArgValues) + + "\n )"; + } else { + invocationCode = "new " + solutionClassName + "()." + property + "(" + singleLineArgs + ")"; + } + + boolean expectedError = c.isErrorExpected(); + String expectedException = expectedError ? "IllegalArgumentException" : null; + String expectedErrorMessage = expectedError ? c.getExpectedErrorMessage() : null; + + boolean isNullExpected = false; + boolean isBooleanExpected = false; + boolean booleanValue = false; + boolean isFloatingPointExpected = false; + String expectedValue = null; + + if (expectedError) { + hasExceptions = true; + } else if (c.expected() == null || c.expected().isNull()) { + isNullExpected = true; + expectedValue = "null"; + } else if (c.expected().isBoolean()) { + isBooleanExpected = true; + booleanValue = c.expected().asBoolean(); + expectedValue = Boolean.toString(booleanValue); + } else if (c.expected().isFloatingPointNumber()) { + isFloatingPointExpected = true; + hasFloatingPoint = true; + expectedValue = JavaTypeFormatter.format(c.expected()); + } else { + expectedValue = JavaTypeFormatter.format(c.expected()); + } + + if (invocationCode.contains("List.of(") || (expectedValue != null && expectedValue.contains("List.of("))) { + hasList = true; + } + if (invocationCode.contains("Map.of(") || (expectedValue != null && expectedValue.contains("Map.of(")) + || invocationCode.contains("Map.entry(") || (expectedValue != null && expectedValue.contains("Map.entry("))) { + hasMap = true; + } + if (invocationCode.contains("Set.of(") || (expectedValue != null && expectedValue.contains("Set.of("))) { + hasSet = true; + } + + renderedCases.add(new RenderedTestCase( + c.uuid(), + c.description(), + methodName, + disabled, + expectedError, + expectedException, + expectedErrorMessage, + isNullExpected, + isBooleanExpected, + booleanValue, + isFloatingPointExpected, + expectedValue, + invocationCode, + property, + formattedInputs, + inputNodes, + c.input(), + c + )); + } + + RenderedExercise renderedExercise = new RenderedExercise( + slug, + testClassName, + solutionClassName, + hasExceptions, + hasFloatingPoint, + hasList, + hasMap, + hasSet, + renderedCases.size() > 1, + renderedCases + ); + + String generatedContent = templateRenderer.render(renderedExercise, exerciseDirectory); + generatedContent = cleanWhitespace(generatedContent); + + return new GenerationResult(slug, targetTestPath, generatedContent, renderedCases.size(), allCases.size() - renderedCases.size()); + } + + private String cleanWhitespace(String code) { + if (code == null) return ""; + // Normalize line endings to \n + String normalized = code.replace("\r\n", "\n").replace('\r', '\n'); + // Collapse 3 or more consecutive newlines into 2 newlines + normalized = normalized.replaceAll("\n{3,}", "\n\n"); + return normalized.trim() + "\n"; + } + + public record GenerationResult( + String slug, + Path targetTestPath, + String content, + int includedCasesCount, + int excludedCasesCount + ) { + public void writeToFile() throws IOException { + if (content == null || includedCasesCount == 0) { + return; + } + Files.createDirectories(targetTestPath.getParent()); + Files.writeString(targetTestPath, content, StandardCharsets.UTF_8); + } + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/service/JavaNamingHelper.java b/test-generator/src/main/java/exercism/testgenerator/service/JavaNamingHelper.java new file mode 100644 index 000000000..5c81728b1 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/service/JavaNamingHelper.java @@ -0,0 +1,89 @@ +package exercism.testgenerator.service; + +import java.util.Set; + +public class JavaNamingHelper { + + private static final Set JAVA_KEYWORDS = Set.of( + "abstract", "assert", "boolean", "break", "byte", "case", "catch", "char", + "class", "const", "continue", "default", "do", "double", "else", "enum", + "extends", "final", "finally", "float", "for", "goto", "if", "implements", + "import", "instanceof", "int", "interface", "long", "native", "new", "package", + "private", "protected", "public", "return", "short", "static", "strictfp", + "super", "switch", "synchronized", "this", "throw", "throws", "transient", + "try", "void", "volatile", "while", "record", "sealed", "permits", "yield", + "var" + ); + + public static String toMethodName(String description) { + if (description == null || description.isBlank()) { + return "testMethod"; + } + + // Replace non-alphanumeric characters with spaces + StringBuilder cleaned = new StringBuilder(); + for (char c : description.toCharArray()) { + if (Character.isLetterOrDigit(c)) { + cleaned.append(c); + } else { + cleaned.append(' '); + } + } + + String[] parts = cleaned.toString().trim().split("\\s+"); + if (parts.length == 0 || parts[0].isEmpty()) { + return "testMethod"; + } + + StringBuilder methodName = new StringBuilder(); + for (int i = 0; i < parts.length; i++) { + String part = parts[i]; + if (part.isEmpty()) { + continue; + } + if (methodName.length() == 0) { + methodName.append(part.toLowerCase()); + } else { + methodName.append(Character.toUpperCase(part.charAt(0))); + if (part.length() > 1) { + methodName.append(part.substring(1).toLowerCase()); + } + } + } + + String result = methodName.toString(); + // If it starts with digit or is not a valid Java identifier start + if (result.isEmpty() || !Character.isJavaIdentifierStart(result.charAt(0))) { + result = "test" + Character.toUpperCase(result.charAt(0)) + (result.length() > 1 ? result.substring(1) : ""); + } + + // If it is a keyword, prefix with "test" + if (JAVA_KEYWORDS.contains(result)) { + result = "test" + Character.toUpperCase(result.charAt(0)) + result.substring(1); + } + + // Cap method name length so that 'public void methodName() {' stays well within 120 chars + if (result.length() > 65) { + result = result.substring(0, 65); + } + + return result; + } + + public static String toPascalCase(String slug) { + if (slug == null || slug.isBlank()) { + return ""; + } + String[] parts = slug.split("[-_\\s]+"); + StringBuilder sb = new StringBuilder(); + for (String part : parts) { + if (!part.isEmpty()) { + sb.append(Character.toUpperCase(part.charAt(0))); + if (part.length() > 1) { + sb.append(part.substring(1).toLowerCase()); + } + } + } + return sb.toString(); + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/service/JavaTypeFormatter.java b/test-generator/src/main/java/exercism/testgenerator/service/JavaTypeFormatter.java new file mode 100644 index 000000000..2adf6196b --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/service/JavaTypeFormatter.java @@ -0,0 +1,158 @@ +package exercism.testgenerator.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Map; + +public class JavaTypeFormatter { + + public static String format(JsonNode node) { + if (node == null || node.isNull()) { + return "null"; + } + + if (node.isBoolean()) { + return Boolean.toString(node.asBoolean()); + } + + if (node.isTextual()) { + String text = node.asText(); + String escaped = escapeJavaString(text); + if (escaped.length() > 70) { + List chunks = new ArrayList<>(); + int start = 0; + while (start < escaped.length()) { + int end = Math.min(start + 65, escaped.length()); + if (end < escaped.length()) { + int lastSpace = escaped.lastIndexOf(' ', end); + if (lastSpace > start + 30) { + end = lastSpace + 1; + } + } + chunks.add("\"" + escaped.substring(start, end) + "\""); + start = end; + } + return String.join("\n + ", chunks); + } + return "\"" + escaped + "\""; + } + + if (node.isLong() || (node.isIntegralNumber() && (node.asLong() > Integer.MAX_VALUE || node.asLong() < Integer.MIN_VALUE))) { + return node.asText() + "L"; + } + + if (node.isInt()) { + return node.asText(); + } + + if (node.isFloatingPointNumber()) { + double val = node.asDouble(); + // ensure there is a decimal or scientific notation + String s = Double.toString(val); + return s; + } + + if (node.isArray()) { + ArrayNode arrayNode = (ArrayNode) node; + if (arrayNode.isEmpty()) { + return "List.of()"; + } + boolean hasNull = false; + for (JsonNode elem : arrayNode) { + if (elem.isNull()) { + hasNull = true; + break; + } + } + + if (hasNull && arrayNode.size() == 1) { + return "java.util.Collections.singletonList(null)"; + } + + String factory = hasNull ? "java.util.Arrays.asList" : "List.of"; + List elements = new ArrayList<>(); + for (JsonNode elem : arrayNode) { + elements.add(format(elem)); + } + String joined = String.join(", ", elements); + if (joined.length() > 60 || elements.size() > 8) { + return factory + "(\n" + + " " + String.join(",\n ", elements) + + "\n )"; + } + return factory + "(" + joined + ")"; + } + + if (node.isObject()) { + ObjectNode objNode = (ObjectNode) node; + if (objNode.isEmpty()) { + return "Map.of()"; + } + List entries = new ArrayList<>(); + Iterator> fields = objNode.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + entries.add("\"" + escapeJavaString(entry.getKey()) + "\", " + format(entry.getValue())); + } + if (entries.size() <= 10) { + String joined = String.join(", ", entries); + if (joined.length() > 60 || entries.size() > 3) { + return "Map.of(\n" + + " " + String.join(",\n ", entries) + + "\n )"; + } + return "Map.of(" + joined + ")"; + } else { + return "Map.ofEntries(\n" + + " " + String.join(",\n ", entries.stream().map(e -> "Map.entry(" + e + ")").toList()) + + "\n )"; + } + } + + return node.asText(); + } + + public static String escapeJavaString(String input) { + if (input == null) { + return ""; + } + StringBuilder sb = new StringBuilder(); + for (char c : input.toCharArray()) { + switch (c) { + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\b': + sb.append("\\b"); + break; + case '\f': + sb.append("\\f"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + default: + if (Character.isISOControl(c)) { + sb.append(String.format("\\u%04x", (int) c)); + } else { + sb.append(c); + } + break; + } + } + return sb.toString(); + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/service/ProblemSpecService.java b/test-generator/src/main/java/exercism/testgenerator/service/ProblemSpecService.java new file mode 100644 index 000000000..79981993c --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/service/ProblemSpecService.java @@ -0,0 +1,136 @@ +package exercism.testgenerator.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import exercism.testgenerator.model.CanonicalCase; +import exercism.testgenerator.model.CanonicalData; +import exercism.testgenerator.model.CanonicalDataNotFoundException; +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.time.Duration; + +public class ProblemSpecService { + + private static final String RAW_CONTENT_URL_FORMAT = + "https://raw.githubusercontent.com/exercism/problem-specifications/main/exercises/%s/canonical-data.json"; + + private final HttpClient httpClient; + private final ObjectMapper objectMapper; + private final Path cacheDir; + + public ProblemSpecService() { + this( + HttpClient.newBuilder() + .connectTimeout(Duration.ofSeconds(10)) + .followRedirects(HttpClient.Redirect.NORMAL) + .build(), + new ObjectMapper(), + Paths.get(System.getProperty("user.home"), ".exercism", "cache", "problem-specifications") + ); + } + + public ProblemSpecService(HttpClient httpClient, ObjectMapper objectMapper) { + this( + httpClient, + objectMapper, + Paths.get(System.getProperty("user.home"), ".exercism", "cache", "problem-specifications") + ); + } + + public ProblemSpecService(HttpClient httpClient, ObjectMapper objectMapper, Path cacheDir) { + this.httpClient = httpClient; + this.objectMapper = objectMapper; + this.cacheDir = cacheDir; + } + + public CanonicalData fetchCanonicalData(String exerciseSlug) throws IOException, InterruptedException { + // 1. Check environment variable for local problem-specifications repo + String envPath = System.getenv("PROBLEM_SPECIFICATIONS_PATH"); + if (envPath != null && !envPath.isBlank()) { + Path candidate = Paths.get(envPath, "exercises", exerciseSlug, "canonical-data.json"); + if (Files.isRegularFile(candidate)) { + return parseCanonicalData(Files.readString(candidate, StandardCharsets.UTF_8)); + } + } + + // 2. Check sibling repository: ../problem-specifications + Path siblingPath = Paths.get("..", "problem-specifications", "exercises", exerciseSlug, "canonical-data.json"); + if (Files.isRegularFile(siblingPath)) { + return parseCanonicalData(Files.readString(siblingPath, StandardCharsets.UTF_8)); + } + + // 3. Check two levels up: ../../problem-specifications + Path twoLevelsUp = Paths.get("..", "..", "problem-specifications", "exercises", exerciseSlug, "canonical-data.json"); + if (Files.isRegularFile(twoLevelsUp)) { + return parseCanonicalData(Files.readString(twoLevelsUp, StandardCharsets.UTF_8)); + } + + // 4. Check local cache directory + if (cacheDir != null) { + Path cachedFile = cacheDir.resolve(exerciseSlug).resolve("canonical-data.json"); + if (Files.isRegularFile(cachedFile)) { + return parseCanonicalData(Files.readString(cachedFile, StandardCharsets.UTF_8)); + } + } + + // 5. Fetch from GitHub raw content + String url = String.format(RAW_CONTENT_URL_FORMAT, exerciseSlug); + HttpRequest request = HttpRequest.newBuilder() + .uri(URI.create(url)) + .header("User-Agent", "Exercism-Java-Test-Generator") + .timeout(Duration.ofSeconds(15)) + .GET() + .build(); + + IOException lastException = null; + for (int attempt = 1; attempt <= 3; attempt++) { + try { + HttpResponse response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); + + if (response.statusCode() == 404) { + throw new CanonicalDataNotFoundException(exerciseSlug, + "Canonical data not found for exercise '" + exerciseSlug + "' at: " + url); + } + + if (response.statusCode() != 200) { + throw new IOException("Failed to fetch canonical data for '" + exerciseSlug + "'. HTTP " + + response.statusCode() + " from " + url); + } + + String body = response.body(); + + // Save to local cache for future offline / fast runs + if (cacheDir != null) { + try { + Path cachedFile = cacheDir.resolve(exerciseSlug).resolve("canonical-data.json"); + Files.createDirectories(cachedFile.getParent()); + Files.writeString(cachedFile, body, StandardCharsets.UTF_8); + } catch (Exception ignored) { + // Caching failure shouldn't fail the execution + } + } + + return parseCanonicalData(body); + } catch (CanonicalDataNotFoundException e) { + throw e; + } catch (IOException e) { + lastException = e; + if (attempt < 3) { + Thread.sleep(1000L * attempt); + } + } + } + + throw lastException != null ? lastException : new IOException("Failed to fetch: " + url); + } + + public CanonicalData parseCanonicalData(String jsonContent) throws IOException { + return objectMapper.readValue(jsonContent, CanonicalData.class); + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java b/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java new file mode 100644 index 000000000..df05a285c --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/service/TemplateRenderer.java @@ -0,0 +1,3529 @@ +package exercism.testgenerator.service; + +import com.fasterxml.jackson.databind.JsonNode; +import com.github.jknack.handlebars.Context; +import com.github.jknack.handlebars.Handlebars; +import com.github.jknack.handlebars.Helper; +import com.github.jknack.handlebars.Options; +import com.github.jknack.handlebars.Template; +import com.github.jknack.handlebars.JsonNodeValueResolver; +import com.github.jknack.handlebars.context.FieldValueResolver; +import com.github.jknack.handlebars.context.JavaBeanValueResolver; +import com.github.jknack.handlebars.context.MapValueResolver; +import com.github.jknack.handlebars.context.MethodValueResolver; +import com.github.jknack.handlebars.io.ClassPathTemplateLoader; +import com.github.jknack.handlebars.io.TemplateLoader; +import exercism.testgenerator.model.CanonicalCase; +import exercism.testgenerator.model.RenderedExercise; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; + +public class TemplateRenderer { + + private final Handlebars handlebars; + + public TemplateRenderer() { + TemplateLoader loader = new ClassPathTemplateLoader("/templates", ".hbs"); + this.handlebars = new Handlebars(loader); + registerHelpers(); + } + + private void registerHelpers() { + handlebars.registerHelper("eq", (a, options) -> { + Object b = options.param(0, null); + if (a == null && b == null) { + return true; + } + if (a != null && b != null) { + // If both are numbers, compare their string forms or numerical values + if (a.toString().equals(b.toString())) return true; + } + return a != null && a.equals(b); + }); + + handlebars.registerHelper("not", (a, options) -> { + return a == null || Boolean.FALSE.equals(a) || "false".equalsIgnoreCase(a.toString()); + }); + + handlebars.registerHelper("and", (a, options) -> { + boolean first = a != null && !Boolean.FALSE.equals(a) && !"false".equalsIgnoreCase(a.toString()); + if (!first) return false; + for (Object param : options.params) { + boolean val = param != null && !Boolean.FALSE.equals(param) && !"false".equalsIgnoreCase(param.toString()); + if (!val) return false; + } + return true; + }); + + handlebars.registerHelper("or", (a, options) -> { + boolean first = a != null && !Boolean.FALSE.equals(a) && !"false".equalsIgnoreCase(a.toString()); + if (first) return true; + for (Object param : options.params) { + boolean val = param != null && !Boolean.FALSE.equals(param) && !"false".equalsIgnoreCase(param.toString()); + if (val) return true; + } + return false; + }); + + handlebars.registerHelper("contains", (a, options) -> { + if (a == null) return false; + Object b = options.param(0, null); + if (b == null) return false; + return a.toString().contains(b.toString()); + }); + + handlebars.registerHelper("lte", (context, options) -> { + if (context == null) return false; + try { + long val = Long.parseLong(context.toString()); + long limit = Long.parseLong(options.param(0).toString()); + return val <= limit; + } catch (Exception e) { + return false; + } + }); + + handlebars.registerHelper("camelCase", (context, options) -> { + if (context == null) return ""; + return JavaNamingHelper.toMethodName(context.toString()); + }); + + handlebars.registerHelper("pascalCase", (context, options) -> { + if (context == null) return ""; + return JavaNamingHelper.toPascalCase(context.toString()); + }); + + handlebars.registerHelper("escapeJava", (context, options) -> { + if (context == null) return ""; + String text = context instanceof JsonNode node ? node.asText() : context.toString(); + return JavaTypeFormatter.escapeJavaString(text); + }); + + handlebars.registerHelper("formatJava", (context, options) -> { + if (context instanceof JsonNode node) { + return JavaTypeFormatter.format(node); + } + return context == null ? "null" : context.toString(); + }); + + handlebars.registerHelper("formatElements", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode item : node) { + list.add(JavaTypeFormatter.format(item)); + } + String joined = String.join(", ", list); + if (joined.length() > 50 || list.size() > 5) { + return "\n " + String.join(",\n ", list); + } + return joined; + } + return ""; + }); + + handlebars.registerHelper("asIntArray", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode item : node) { + list.add(item.asText()); + } + String joined = String.join(", ", list); + if (joined.length() > 50 || list.size() > 8) { + return "new int[]{\n " + String.join(",\n ", list) + "\n }"; + } + return "new int[]{" + joined + "}"; + } + return "new int[]{}"; + }); + + handlebars.registerHelper("asStringArray", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode item : node) { + list.add("\"" + JavaTypeFormatter.escapeJavaString(item.asText()) + "\""); + } + String joined = String.join(", ", list); + if (joined.length() > 50 || list.size() > 5) { + return "new String[]{\n " + + String.join(",\n ", list) + + "\n }"; + } + return "new String[]{" + joined + "}"; + } + return "new String[]{}"; + }); + + handlebars.registerHelper("joinLines", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "\"\""; + } + if (node.size() == 1) { + return "\"" + JavaTypeFormatter.escapeJavaString(node.get(0).asText()) + "\""; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < node.size(); i++) { + String line = JavaTypeFormatter.escapeJavaString(node.get(i).asText()); + if (i > 0) { + sb.append("\n + "); + } + sb.append("\"").append(line); + if (i < node.size() - 1) { + sb.append("\\n\""); + } else { + sb.append("\""); + } + } + return sb.toString(); + } + return "\"\""; + }); + + handlebars.registerHelper("asLong", (context, options) -> { + if (context == null) return "0L"; + String s = context.toString(); + return s.endsWith("L") || s.endsWith("l") ? s : s + "L"; + }); + + handlebars.registerHelper("asLongList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "List.of()"; + } + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode item : node) { + list.add(item.asText() + "L"); + } + String joined = String.join(", ", list); + if (joined.length() > 50 || list.size() > 8) { + return "List.of(\n " + String.join(",\n ", list) + "\n )"; + } + return "List.of(" + joined + ")"; + } + return "List.of()"; + }); + + handlebars.registerHelper("asSignals", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return ""; + } + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode item : node) { + String text = item.asText(); + String enumName = switch (text) { + case "wink" -> "Signal.WINK"; + case "double blink" -> "Signal.DOUBLE_BLINK"; + case "close your eyes" -> "Signal.CLOSE_YOUR_EYES"; + case "jump" -> "Signal.JUMP"; + default -> "Signal." + text.toUpperCase().replace(" ", "_"); + }; + list.add(enumName); + } + String joined = String.join(", ", list); + if (joined.length() > 50) { + return "\n " + String.join(",\n ", list); + } + return joined; + } + return ""; + }); + + handlebars.registerHelper("formatResistorLabel", (context, options) -> { + if (context instanceof JsonNode node && node.isObject()) { + return "\"" + node.path("value").asText() + " " + node.path("unit").asText() + "\""; + } + return "\"\""; + }); + + handlebars.registerHelper("spaceAgeMethod", (context, options) -> { + if (context == null) return "onEarth"; + String planet = context instanceof JsonNode node ? node.asText() : context.toString(); + return "on" + Character.toUpperCase(planet.charAt(0)) + planet.substring(1); + }); + + handlebars.registerHelper("isIllegalTriangle", (context, options) -> { + if (context instanceof JsonNode node && node.isArray() && node.size() == 3) { + double a = node.get(0).asDouble(); + double b = node.get(1).asDouble(); + double c = node.get(2).asDouble(); + return (a <= 0 || b <= 0 || c <= 0 || a + b <= c || a + c <= b || b + c <= a); + } + return false; + }); + + handlebars.registerHelper("allYourBaseErrorMessage", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return "Bases must be at least 2."; + int inBase = c.input().path("inputBase").asInt(2); + int outBase = c.input().path("outputBase").asInt(2); + if (inBase < 2 || outBase < 2) { + return "Bases must be at least 2."; + } + JsonNode digits = c.input().path("digits"); + if (digits.isArray()) { + for (JsonNode d : digits) { + if (d.asInt() < 0) { + return "Digits may not be negative."; + } + } + for (JsonNode d : digits) { + if (d.asInt() >= inBase) { + return "All digits must be strictly less than the base."; + } + } + } + return "Bases must be at least 2."; + }); + + handlebars.registerHelper("largestSeriesProductExpectedMessage", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String digits = c.input().path("digits").asText(); + int span = c.input().path("span").asInt(); + if (!digits.chars().allMatch(Character::isDigit)) { + return "String to search may only contain digits."; + } + if (span < 0) { + return "Series length must be non-negative."; + } + return "Series length must be less than or equal to the length of the string to search."; + }); + + handlebars.registerHelper("asAllergens", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) return ""; + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode item : node) { + list.add("Allergen." + item.asText().toUpperCase()); + } + String joined = String.join(", ", list); + if (joined.length() > 50 || list.size() > 4) { + return "\n " + String.join(",\n ", list); + } + return joined; + } + return ""; + }); + + handlebars.registerHelper("toAllergen", (context, options) -> { + if (context == null) return "Allergen.EGGS"; + String s = context instanceof JsonNode node ? node.asText() : context.toString(); + return "Allergen." + s.toUpperCase().replace("\"", ""); + }); + + handlebars.registerHelper("toChar", (context, options) -> { + if (context == null) return "' '"; + String s = context.toString().replace("\"", "").replace("'", ""); + return "'" + (s.isEmpty() ? ' ' : s.charAt(0)) + "'"; + }); + + handlebars.registerHelper("as2DIntArray", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "new int[][]{}"; + } + int baseIndent = 16; + int elemIndent = 24; + if (options.params.length > 0 && options.param(0) != null) { + try { + baseIndent = Integer.parseInt(options.param(0).toString()); + elemIndent = baseIndent == 8 ? 12 : baseIndent + 8; + } catch (Exception ignored) {} + } + String elemSpaces = " ".repeat(elemIndent); + String rcurlySpaces = " ".repeat(baseIndent); + + java.util.List rows = new java.util.ArrayList<>(); + for (JsonNode row : node) { + java.util.List elements = new java.util.ArrayList<>(); + for (JsonNode el : row) { + elements.add(el.asText()); + } + rows.add("{" + String.join(", ", elements) + "}"); + } + if (rows.size() <= 3 && String.join(", ", rows).length() <= 40) { + return "new int[][]{" + String.join(", ", rows) + "}"; + } + return "new int[][]{\n" + elemSpaces + + String.join(",\n" + elemSpaces, rows) + + "\n" + rcurlySpaces + "}"; + } + return "new int[][]{}"; + }); + + handlebars.registerHelper("twelveDaysExpected", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < node.size(); i++) { + String verse = node.get(i).asText() + "\n"; + if (i > 0) { + sb.append("\n + \"\\n\"\n + "); + } + sb.append(breakStringIntoChunks(verse, 26)); + } + return sb.toString(); + } + return "\"\""; + }); + + handlebars.registerHelper("asPlants", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode item : node) { + list.add("Plant." + item.asText().toUpperCase()); + } + String joined = String.join(", ", list); + if (joined.length() > 50 || list.size() > 4) { + return "\n " + String.join(",\n ", list); + } + return joined; + } + return ""; + }); + + handlebars.registerHelper("toYachtCategory", (context, options) -> { + if (context == null) return "YACHT"; + String s = context instanceof JsonNode node ? node.asText() : context.toString(); + return s.trim().toUpperCase().replace(" ", "_").replace("-", "_").replace("\"", ""); + }); + + handlebars.registerHelper("formatEtlInput", (context, options) -> { + if (context instanceof JsonNode node && node.isObject()) { + java.util.List entries = new java.util.ArrayList<>(); + var fields = node.fields(); + while (fields.hasNext()) { + var entry = fields.next(); + int score = Integer.parseInt(entry.getKey()); + JsonNode letters = entry.getValue(); + java.util.List letterList = new java.util.ArrayList<>(); + for (JsonNode l : letters) { + letterList.add("\"" + l.asText() + "\""); + } + entries.add("Map.entry(" + score + ", List.of(" + String.join(", ", letterList) + "))"); + } + if (entries.size() == 1) { + return "Map.ofEntries(" + entries.get(0) + ")"; + } + return "Map.ofEntries(\n " + String.join(",\n ", entries) + "\n )"; + } + return "Map.of()"; + }); + + handlebars.registerHelper("formatEtlExpected", (context, options) -> { + if (context instanceof JsonNode node && node.isObject()) { + java.util.List entries = new java.util.ArrayList<>(); + var fields = node.fields(); + while (fields.hasNext()) { + var entry = fields.next(); + entries.add("Map.entry(\"" + entry.getKey() + "\", " + entry.getValue().asInt() + ")"); + } + if (entries.size() <= 3) { + return "Map.ofEntries(" + String.join(", ", entries) + ")"; + } + return "Map.ofEntries(\n " + String.join(",\n ", entries) + "\n )"; + } + return "Map.of()"; + }); + + handlebars.registerHelper("bottleSongExpected", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < node.size(); i++) { + String line = node.get(i).asText(); + String lineWithNewline = line.isEmpty() ? "\\n" : (JavaTypeFormatter.escapeJavaString(line) + "\\n"); + if (i > 0) { + sb.append("\n + "); + } + sb.append("\"").append(lineWithNewline).append("\""); + } + return sb.toString(); + } + return "\"\""; + }); + + handlebars.registerHelper("as2DIntList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "List.of()"; + } + java.util.List innerLists = new java.util.ArrayList<>(); + for (JsonNode row : node) { + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode el : row) { + items.add(el.asText()); + } + innerLists.add("List.of(" + String.join(", ", items) + ")"); + } + if (innerLists.size() <= 2 && String.join(", ", innerLists).length() <= 40) { + return "List.of(" + String.join(", ", innerLists) + ")"; + } + return "List.of(\n " + + String.join(",\n ", innerLists) + + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("asIntList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "List.of()"; + } + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode el : node) { + items.add(el.asText()); + } + String joined = String.join(", ", items); + if (joined.length() > 60 || items.size() > 10) { + return "List.of(\n " + + String.join(",\n ", items) + + "\n )"; + } + return "List.of(" + joined + ")"; + } + return "List.of()"; + }); + + handlebars.registerHelper("asLaserInfo", (context, options) -> { + if (context instanceof JsonNode node) { + return "new Prism.LaserInfo(" + node.get("x") + ", " + node.get("y") + ", " + node.get("angle") + ")"; + } + if (context instanceof java.util.Map map) { + return "new Prism.LaserInfo(" + map.get("x") + ", " + map.get("y") + ", " + map.get("angle") + ")"; + } + return "new Prism.LaserInfo(0, 0, 0)"; + }); + + handlebars.registerHelper("asPrismInfoList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "List.of()"; + } + java.util.List prisms = new java.util.ArrayList<>(); + for (JsonNode p : node) { + prisms.add("new Prism.PrismInfo(" + p.get("id") + ", " + p.get("x") + ", " + p.get("y") + ", " + p.get("angle") + ")"); + } + if (prisms.size() <= 2 && String.join(", ", prisms).length() <= 60) { + return "List.of(" + String.join(", ", prisms) + ")"; + } + return "List.of(\n " + + String.join(",\n ", prisms) + + "\n )"; + } + if (context instanceof java.util.Collection col) { + if (col.isEmpty()) { + return "List.of()"; + } + java.util.List prisms = new java.util.ArrayList<>(); + for (Object item : col) { + if (item instanceof java.util.Map p) { + prisms.add("new Prism.PrismInfo(" + p.get("id") + ", " + p.get("x") + ", " + p.get("y") + ", " + p.get("angle") + ")"); + } else if (item instanceof JsonNode p) { + prisms.add("new Prism.PrismInfo(" + p.get("id") + ", " + p.get("x") + ", " + p.get("y") + ", " + p.get("angle") + ")"); + } + } + if (prisms.size() <= 2 && String.join(", ", prisms).length() <= 60) { + return "List.of(" + String.join(", ", prisms) + ")"; + } + return "List.of(\n " + + String.join(",\n ", prisms) + + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("asMatrixCoordinates", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "Set.of()"; + } + java.util.List coords = new java.util.ArrayList<>(); + for (JsonNode item : node) { + coords.add("new MatrixCoordinate(" + item.get("row").asInt() + ", " + item.get("column").asInt() + ")"); + } + return "Set.of(" + String.join(", ", coords) + ")"; + } + return "Set.of()"; + }); + + handlebars.registerHelper("asHexLongList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) return "List.of()"; + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode el : node) { + long val = el.asLong(); + list.add("0x" + Long.toHexString(val) + "L"); + } + if (list.size() <= 4 && String.join(", ", list).length() <= 45) { + return "List.of(" + String.join(", ", list) + ")"; + } + return "List.of(\n " + String.join(",\n ", list) + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("asHexStringList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) return "List.of()"; + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode el : node) { + long val = el.asLong(); + list.add("\"0x" + Long.toHexString(val) + "\""); + } + if (list.size() <= 4 && String.join(", ", list).length() <= 45) { + return "List.of(" + String.join(", ", list) + ")"; + } + return "List.of(\n " + String.join(",\n ", list) + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("asKnapsackItems", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "List.of()"; + } + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode item : node) { + items.add("new Item(" + item.get("weight").asInt() + ", " + item.get("value").asInt() + ")"); + } + if (items.size() <= 2) { + return "List.of(" + String.join(", ", items) + ")"; + } + return "List.of(\n " + String.join(",\n ", items) + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("upper", (context, options) -> { + if (context == null) return ""; + String s = context instanceof JsonNode node ? node.asText() : context.toString(); + return s.toUpperCase().replace("\"", ""); + }); + + handlebars.registerHelper("houseExpected", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < node.size(); i++) { + String verse = node.get(i).asText(); + if (i > 0) { + sb.append("\n + \"\\n\"\n + "); + } + sb.append(breakStringIntoChunks(verse, 26)); + } + return sb.toString(); + } + return "\"\""; + }); + + handlebars.registerHelper("foodChainExpected", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < node.size(); i++) { + String line = node.get(i).asText(); + if (i > 0) { + sb.append("\n + \"\\n\"\n + "); + } + sb.append(breakStringIntoChunks(line, 26)); + } + return sb.toString(); + } + return "\"\""; + }); + + handlebars.registerHelper("field", (context, options) -> { + String fieldName = options.param(0, "").toString(); + if (context instanceof JsonNode node && node.has(fieldName)) { + JsonNode val = node.get(fieldName); + if (val.isNumber()) { + return val.asText(); + } + if (val.isBoolean()) { + return val.asBoolean(); + } + return val.asText(); + } + if (context instanceof java.util.Map map && map.containsKey(fieldName)) { + Object val = map.get(fieldName); + return val == null ? "" : val.toString(); + } + return ""; + }); + + handlebars.registerHelper("hasElements", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + return !node.isEmpty(); + } + if (context instanceof java.util.Collection col) { + return !col.isEmpty(); + } + if (context instanceof java.util.Map map) { + return !map.isEmpty(); + } + return false; + }); + + handlebars.registerHelper("formatAlphameticsExpected", (context, options) -> { + if (context instanceof JsonNode node && node.isObject()) { + java.util.List entries = new java.util.ArrayList<>(); + node.fields().forEachRemaining(entry -> { + entries.add("entry('" + entry.getKey().charAt(0) + "', " + entry.getValue().asInt() + ")"); + }); + return "Map.ofEntries(\n " + + String.join(",\n ", entries) + + "\n )"; + } + if (context instanceof java.util.Map map) { + java.util.List entries = new java.util.ArrayList<>(); + map.forEach((k, v) -> { + entries.add("entry('" + k.toString().charAt(0) + "', " + v + ")"); + }); + return "Map.ofEntries(\n " + + String.join(",\n ", entries) + + "\n )"; + } + return "Map.of()"; + }); + + handlebars.registerHelper("alphameticsPuzzle", (context, options) -> { + String text = ""; + if (context instanceof JsonNode node) { + text = node.asText(); + } else if (context != null) { + text = context.toString(); + } + return breakStringIntoChunks(text, 24); + }); + + handlebars.registerHelper("formatLedgerEntries", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "new Ledger.LedgerEntry[]{}"; + } + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode item : node) { + String date = item.get("date").asText(); + String desc = JavaTypeFormatter.escapeJavaString(item.get("description").asText()); + int amount = item.get("amountInCents").asInt(); + items.add("ledger.createLedgerEntry(\"" + date + "\", \"" + desc + "\", " + amount + ")"); + } + return "new Ledger.LedgerEntry[]{\n " + + String.join(",\n ", items) + + "\n }"; + } + return "new Ledger.LedgerEntry[]{}"; + }); + + handlebars.registerHelper("ledgerLocale", (context, options) -> { + if (context == null) return "en-US"; + String s = context instanceof JsonNode node ? node.asText() : context.toString(); + return s.replace("_", "-"); + }); + + handlebars.registerHelper("formatLedgerExpected", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "\"\""; + } + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < node.size(); i++) { + String line = node.get(i).asText(); + if (node.get(0).asText().startsWith("Datum")) { + line = line.replaceFirst("^(\\d{2})-(\\d{2})-(\\d{4})", "$1/$2/$3"); + } + if (i > 0) { + sb.append("\n + "); + } + sb.append("\"").append(JavaTypeFormatter.escapeJavaString(line)); + if (i < node.size() - 1) { + sb.append("\\n\""); + } else { + sb.append("\""); + } + } + return sb.toString(); + } + return "\"\""; + }); + + handlebars.registerHelper("renderStopwatchCommands", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + java.util.List statements = new java.util.ArrayList<>(); + for (JsonNode cmd : node) { + String name = cmd.path("command").asText(); + if ("new".equals(name)) { + statements.add("SplitSecondStopwatch stopwatch = new SplitSecondStopwatch();"); + } else if (cmd.has("by")) { + String by = JavaTypeFormatter.escapeJavaString(cmd.get("by").asText()); + statements.add("stopwatch.advanceTime(\"" + by + "\");"); + } else if (cmd.has("expected")) { + JsonNode exp = cmd.get("expected"); + if (exp.isObject() && exp.has("error")) { + String error = JavaTypeFormatter.escapeJavaString(exp.get("error").asText()); + statements.add("assertThatExceptionOfType(IllegalStateException.class)\n" + + " .isThrownBy(stopwatch::" + name + ")\n" + + " .withMessage(\"" + error + "\");"); + } else if ("previousLaps".equals(name)) { + if (exp.isArray() && exp.isEmpty()) { + statements.add("assertThat(stopwatch.previousLaps()).isEmpty();"); + } else if (exp.isArray()) { + java.util.List laps = new java.util.ArrayList<>(); + for (JsonNode lap : exp) { + laps.add("\"" + JavaTypeFormatter.escapeJavaString(lap.asText()) + "\""); + } + statements.add("assertThat(stopwatch.previousLaps()).containsExactly(" + String.join(", ", laps) + ");"); + } + } else { + String expectedStr = JavaTypeFormatter.escapeJavaString(exp.asText()); + statements.add("assertThat(stopwatch." + name + "()).isEqualTo(\"" + expectedStr + "\");"); + } + } else { + statements.add("stopwatch." + name + "();"); + } + } + return String.join("\n ", statements); + } + return ""; + }); + + handlebars.registerHelper("asLocalDateList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) { + return "List.of()"; + } + if (node.size() == 1) { + return "List.of(LocalDate.parse(\"" + node.get(0).asText() + "\"))"; + } + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode item : node) { + items.add("LocalDate.parse(\"" + item.asText() + "\")"); + } + String singleLine = "List.of(" + String.join(", ", items) + ")"; + if (singleLine.length() <= 80) { + return singleLine; + } + return "List.of(\n " + + String.join(",\n ", items) + + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("renderBankAccountCase", (context, options) -> { + JsonNode ops = null; + JsonNode expectedNode = null; + if (context instanceof exercism.testgenerator.model.CanonicalCase c) { + ops = c.input() != null ? c.input().path("operations") : null; + expectedNode = c.expected(); + } else if (context instanceof exercism.testgenerator.model.RenderedTestCase r) { + ops = r.rawCase().input() != null ? r.rawCase().input().path("operations") : null; + expectedNode = r.rawCase().expected(); + } else if (context instanceof JsonNode rawCase) { + ops = rawCase.path("input").path("operations"); + expectedNode = rawCase.path("expected"); + } + if (ops == null || !ops.isArray()) return ""; + boolean hasError = expectedNode != null && expectedNode.has("error"); + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("BankAccount bankAccount = new BankAccount();"); + + int lastIndex = ops.size() - 1; + for (int i = 0; i <= lastIndex; i++) { + JsonNode op = ops.get(i); + String operation = op.path("operation").asText(); + boolean isLast = (i == lastIndex); + + if (hasError && isLast) { + String call = switch (operation) { + case "open" -> "bankAccount.open()"; + case "close" -> "bankAccount.close()"; + case "deposit" -> "bankAccount.deposit(" + op.get("amount").asInt() + ")"; + case "withdraw" -> "bankAccount.withdraw(" + op.get("amount").asInt() + ")"; + case "balance" -> "bankAccount.getBalance()"; + default -> ""; + }; + lines.add("assertThatExceptionOfType(BankAccountActionInvalidException.class)"); + lines.add(" .isThrownBy(() -> " + call + ");"); + } else { + switch (operation) { + case "open" -> lines.add("bankAccount.open();"); + case "close" -> lines.add("bankAccount.close();"); + case "deposit" -> lines.add("bankAccount.deposit(" + op.get("amount").asInt() + ");"); + case "withdraw" -> lines.add("bankAccount.withdraw(" + op.get("amount").asInt() + ");"); + case "balance" -> { + if (!hasError && isLast) { + int expected = expectedNode.asInt(); + lines.add("assertThat(bankAccount.getBalance()).isEqualTo(" + expected + ");"); + } + } + case "concurrent" -> { + int num = op.path("number").asInt(1000); + lines.add("Random random = new Random();"); + lines.add("Thread[] threads = new Thread[" + num + "];"); + lines.add("for (int idx = 0; idx < " + num + "; idx++) {"); + lines.add(" threads[idx] = new Thread(() -> {"); + lines.add(" try {"); + lines.add(" bankAccount.deposit(1);"); + lines.add(" Thread.sleep(random.nextInt(10));"); + lines.add(" bankAccount.withdraw(1);"); + lines.add(" } catch (BankAccountActionInvalidException e) {"); + lines.add(" fail(\"Exception should not be thrown: \" + e.getMessage());"); + lines.add(" } catch (InterruptedException ignored) {"); + lines.add(" }"); + lines.add(" });"); + lines.add(" threads[idx].start();"); + lines.add("}"); + lines.add("for (Thread thread : threads) {"); + lines.add(" thread.join();"); + lines.add("}"); + } + default -> {} + } + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderBowlingCase", (context, options) -> { + JsonNode input = null; + JsonNode expected = null; + if (context instanceof exercism.testgenerator.model.CanonicalCase c) { + input = c.input(); + expected = c.expected(); + } else if (context instanceof exercism.testgenerator.model.RenderedTestCase r) { + input = r.rawCase().input(); + expected = r.rawCase().expected(); + } else if (context instanceof JsonNode rawCase) { + input = rawCase.path("input"); + expected = rawCase.path("expected"); + } + if (input == null || expected == null) return ""; + boolean hasError = expected.has("error"); + + JsonNode rollsNode = input.has("rolls") ? input.get("rolls") : input.get("previousRolls"); + java.util.List rollInts = new java.util.ArrayList<>(); + if (rollsNode != null && rollsNode.isArray()) { + for (JsonNode r : rollsNode) { + rollInts.add(String.valueOf(r.asInt())); + } + } + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("BowlingGame game = new BowlingGame();"); + String rollsArray; + if (rollInts.isEmpty()) { + rollsArray = "new int[]{}"; + } else if (rollInts.size() <= 8) { + rollsArray = "new int[]{" + String.join(", ", rollInts) + "}"; + } else { + java.util.List rollChunks = new java.util.ArrayList<>(); + for (int i = 0; i < rollInts.size(); i += 10) { + int end = Math.min(i + 10, rollInts.size()); + rollChunks.add(String.join(", ", rollInts.subList(i, end))); + } + rollsArray = "new int[]{\n " + + String.join(",\n ", rollChunks) + + "\n }"; + } + + lines.add("int[] rolls = " + rollsArray + ";"); + lines.add("for (int pins : rolls) {"); + lines.add(" game.roll(pins);"); + lines.add("}"); + + if (input.has("roll")) { + int roll = input.get("roll").asInt(); + String error = JavaTypeFormatter.escapeJavaString(expected.get("error").asText()); + lines.add("assertThatExceptionOfType(IllegalStateException.class)"); + lines.add(" .isThrownBy(() -> game.roll(" + roll + "))"); + lines.add(" .withMessage(\"" + error + "\");"); + } else if (hasError) { + String error = JavaTypeFormatter.escapeJavaString(expected.get("error").asText()); + lines.add("assertThatExceptionOfType(IllegalStateException.class)"); + lines.add(" .isThrownBy(game::score)"); + lines.add(" .withMessage(\"" + error + "\");"); + } else { + int score = expected.asInt(); + lines.add("assertThat(game.score()).isEqualTo(" + score + ");"); + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("asCamiciaCards", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) return "List.of()"; + java.util.List quoted = new java.util.ArrayList<>(); + for (JsonNode item : node) { + quoted.add("\"" + JavaTypeFormatter.escapeJavaString(item.asText()) + "\""); + } + if (quoted.size() <= 8) { + return "List.of(" + String.join(", ", quoted) + ")"; + } + java.util.List lines = new java.util.ArrayList<>(); + for (int i = 0; i < quoted.size(); i += 10) { + int end = Math.min(i + 10, quoted.size()); + lines.add(String.join(", ", quoted.subList(i, end))); + } + return "List.of(\n " + + String.join(",\n ", lines) + + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("asFlowerFieldBoard", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) return "List.of()"; + if (node.size() == 1) { + return "List.of(\"" + JavaTypeFormatter.escapeJavaString(node.get(0).asText()) + "\")"; + } + java.util.List lines = new java.util.ArrayList<>(); + for (JsonNode r : node) { + lines.add("\"" + JavaTypeFormatter.escapeJavaString(r.asText()) + "\""); + } + return "List.of(\n " + + String.join(",\n ", lines) + + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("renderSchoolCase", (context, options) -> { + String prop = ""; + JsonNode students = null; + JsonNode expected = null; + JsonNode desiredGradeNode = null; + if (context instanceof exercism.testgenerator.model.CanonicalCase c) { + prop = c.property(); + students = c.input() != null ? c.input().path("students") : null; + expected = c.expected(); + desiredGradeNode = c.input() != null ? c.input().path("desiredGrade") : null; + } else if (context instanceof exercism.testgenerator.model.RenderedTestCase r) { + prop = r.property(); + students = r.rawCase().input() != null ? r.rawCase().input().path("students") : null; + expected = r.rawCase().expected(); + desiredGradeNode = r.rawCase().input() != null ? r.rawCase().input().path("desiredGrade") : null; + } else if (context instanceof JsonNode rawCase) { + prop = rawCase.path("property").asText(); + students = rawCase.path("input").path("students"); + expected = rawCase.path("expected"); + desiredGradeNode = rawCase.path("input").path("desiredGrade"); + } + if (students == null) return ""; + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("School school = new School();"); + + if ("add".equals(prop)) { + if (students.isArray() && expected.isArray()) { + for (int i = 0; i < students.size(); i++) { + JsonNode s = students.get(i); + String name = s.get(0).asText(); + int grade = s.get(1).asInt(); + boolean exp = expected.get(i).asBoolean(); + lines.add("assertThat(school.add(\"" + name + "\", " + grade + ")).is" + + (exp ? "True" : "False") + "();"); + } + } + } else if ("roster".equals(prop)) { + if (students.isArray()) { + for (JsonNode s : students) { + String name = s.get(0).asText(); + int grade = s.get(1).asInt(); + lines.add("school.add(\"" + name + "\", " + grade + ");"); + } + } + if (expected.isArray() && expected.isEmpty()) { + lines.add("assertThat(school.roster()).isEmpty();"); + } else if (expected.isArray()) { + java.util.List names = new java.util.ArrayList<>(); + for (JsonNode n : expected) { + names.add("\"" + n.asText() + "\""); + } + lines.add("assertThat(school.roster()).containsExactly(" + String.join(", ", names) + ");"); + } + } else if ("grade".equals(prop)) { + if (students.isArray()) { + for (JsonNode s : students) { + String name = s.get(0).asText(); + int grade = s.get(1).asInt(); + lines.add("school.add(\"" + name + "\", " + grade + ");"); + } + } + int desiredGrade = desiredGradeNode != null ? desiredGradeNode.asInt() : 0; + if (expected.isArray() && expected.isEmpty()) { + lines.add("assertThat(school.grade(" + desiredGrade + ")).isEmpty();"); + } else if (expected.isArray()) { + java.util.List names = new java.util.ArrayList<>(); + for (JsonNode n : expected) { + names.add("\"" + n.asText() + "\""); + } + lines.add("assertThat(school.grade(" + desiredGrade + "))\n" + + " .containsExactly(" + String.join(", ", names) + ");"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("asHexIntList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) return "List.of()"; + java.util.List hexItems = new java.util.ArrayList<>(); + for (JsonNode item : node) { + hexItems.add(item.asText()); + } + if (hexItems.size() <= 8) { + return "List.of(" + String.join(", ", hexItems) + ")"; + } + java.util.List lines = new java.util.ArrayList<>(); + for (int i = 0; i < hexItems.size(); i += 8) { + int end = Math.min(i + 8, hexItems.size()); + lines.add(String.join(", ", hexItems.subList(i, end))); + } + return "List.of(\n " + + String.join(",\n ", lines) + + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("renderDoublyLinkedListOperations", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + java.util.List statements = new java.util.ArrayList<>(); + statements.add("DoublyLinkedList list = new DoublyLinkedList<>();"); + for (JsonNode op : node) { + String operation = op.path("operation").asText(); + if ("push".equals(operation)) { + statements.add("list.push(" + op.get("value").asInt() + ");"); + } else if ("unshift".equals(operation)) { + statements.add("list.unshift(" + op.get("value").asInt() + ");"); + } else if ("pop".equals(operation)) { + if (op.has("expected")) { + statements.add("assertThat(list.pop()).isEqualTo(" + op.get("expected").asInt() + ");"); + } else { + statements.add("list.pop();"); + } + } else if ("shift".equals(operation)) { + if (op.has("expected")) { + statements.add("assertThat(list.shift()).isEqualTo(" + op.get("expected").asInt() + ");"); + } else { + statements.add("list.shift();"); + } + } + } + return String.join("\n ", statements); + } + return ""; + }); + + handlebars.registerHelper("formatFrequencyTexts", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) return "new String[]{}"; + if (node.size() > 10) { + boolean allEqual = true; + String first = node.get(0).asText(); + for (JsonNode item : node) { + if (!first.equals(item.asText())) { + allEqual = false; + break; + } + } + if (allEqual) { + return "createIdenticalTexts(" + node.size() + ", \"" + + JavaTypeFormatter.escapeJavaString(first) + "\")"; + } + } + java.util.List stringExprs = new java.util.ArrayList<>(); + for (JsonNode item : node) { + String text = item.asText(); + if (text.length() > 60) { + stringExprs.add(breakStringIntoChunks(text, 16)); + } else { + stringExprs.add("\"" + JavaTypeFormatter.escapeJavaString(text) + "\""); + } + } + return "new String[]{\n " + + String.join(",\n ", stringExprs) + + "\n }"; + } + return "new String[]{}"; + }); + + handlebars.registerHelper("formatFrequencyExpected", (context, options) -> { + if (context instanceof JsonNode node && node.isObject()) { + if (node.isEmpty()) return "Map.of()"; + java.util.List entries = new java.util.ArrayList<>(); + var it = node.fields(); + while (it.hasNext()) { + var entry = it.next(); + String key = entry.getKey(); + int count = entry.getValue().asInt(); + String charLiteral = "'".equals(key) ? "'\\''" : ("\\".equals(key) ? "'\\\\'" : "'" + key + "'"); + entries.add("Map.entry(" + charLiteral + ", " + count + ")"); + } + if (entries.size() <= 8) { + java.util.List pairs = new java.util.ArrayList<>(); + var it2 = node.fields(); + while (it2.hasNext()) { + var entry = it2.next(); + String key = entry.getKey(); + int count = entry.getValue().asInt(); + String charLiteral = "'".equals(key) ? "'\\''" : ("\\".equals(key) ? "'\\\\'" : "'" + key + "'"); + pairs.add(charLiteral + ", " + count); + } + return "Map.of(" + String.join(", ", pairs) + ")"; + } + return "Map.ofEntries(\n " + + String.join(",\n ", entries) + + "\n )"; + } + return "Map.of()"; + }); + + handlebars.registerHelper("asJigsawInfo", (context, options) -> { + if (!(context instanceof JsonNode node)) return "null"; + java.util.List calls = new java.util.ArrayList<>(); + calls.add("new JigsawInfo.Builder()"); + if (node.has("pieces")) calls.add(".pieces(" + node.get("pieces").asInt() + ")"); + if (node.has("border")) calls.add(".border(" + node.get("border").asInt() + ")"); + if (node.has("inside")) calls.add(".inside(" + node.get("inside").asInt() + ")"); + if (node.has("rows")) calls.add(".rows(" + node.get("rows").asInt() + ")"); + if (node.has("columns")) calls.add(".columns(" + node.get("columns").asInt() + ")"); + if (node.has("aspectRatio")) calls.add(".aspectRatio(" + node.get("aspectRatio").asDouble() + ")"); + if (node.has("format")) { + calls.add(".format(\"" + JavaTypeFormatter.escapeJavaString(node.get("format").asText()) + "\")"); + } + calls.add(".build()"); + return String.join("\n ", calls); + }); + + handlebars.registerHelper("renderReactCase", (context, options) -> { + CanonicalCase cCase = toCanonicalCase(context); + if (cCase == null) return ""; + JsonNode input = cCase.input(); + JsonNode cells = input.path("cells"); + JsonNode operations = input.path("operations"); + + java.util.List lines = new java.util.ArrayList<>(); + + // 1. Emit cells + if (cells.isArray()) { + for (JsonNode cell : cells) { + String name = JavaNamingHelper.toMethodName(cell.path("name").asText()); + String type = cell.path("type").asText(); + if ("input".equals(type)) { + int initialVal = cell.path("initial_value").asInt(); + lines.add("var " + name + " = React.inputCell(" + initialVal + ");"); + } else if ("compute".equals(type)) { + String fn = translateComputeFunction(cell.path("compute_function").asText()); + JsonNode cellInputs = cell.path("inputs"); + java.util.List inNames = new java.util.ArrayList<>(); + if (cellInputs.isArray()) { + for (JsonNode in : cellInputs) { + inNames.add(JavaNamingHelper.toMethodName(in.asText())); + } + } + String inList = "List.of(" + String.join(", ", inNames) + ")"; + lines.add("var " + name + " = React.computeCell(" + fn + ", " + inList + ");"); + } + } + } + + // 2. Analyze callbacks across operations + java.util.Set removedCallbacks = new java.util.HashSet<>(); + java.util.LinkedHashSet allCallbacks = new java.util.LinkedHashSet<>(); + if (operations.isArray()) { + for (JsonNode op : operations) { + String opType = op.path("type").asText(); + if ("remove_callback".equals(opType)) { + removedCallbacks.add(op.path("name").asText()); + } + if ("add_callback".equals(opType)) { + allCallbacks.add(op.path("name").asText()); + } + } + } + + int totalCallbacks = allCallbacks.size(); + java.util.Map cbValuesVar = new java.util.HashMap<>(); + int cbIdx = 1; + for (String cb : allCallbacks) { + if (totalCallbacks == 1) { + cbValuesVar.put(cb, "values"); + } else { + String num = cb.replaceAll("\\D+", ""); + cbValuesVar.put(cb, num.isEmpty() ? ("values" + cbIdx) : ("values" + num)); + } + cbIdx++; + } + + // 3. Emit operations + if (operations.isArray()) { + for (int i = 0; i < operations.size(); i++) { + JsonNode op = operations.get(i); + String opType = op.path("type").asText(); + String cellName = JavaNamingHelper.toMethodName(op.path("cell").asText()); + + if ("expect_cell_value".equals(opType)) { + int expVal = op.path("value").asInt(); + lines.add(""); + lines.add("assertThat(" + cellName + ".getValue()).isEqualTo(" + expVal + ");"); + } else if ("add_callback".equals(opType)) { + String cbName = op.path("name").asText(); + String vVar = cbValuesVar.get(cbName); + lines.add(""); + lines.add("var " + vVar + " = new ArrayList();"); + if (removedCallbacks.contains(cbName)) { + lines.add("Consumer " + cbName + " = " + vVar + "::add;"); + lines.add(cellName + ".addCallback(" + cbName + ");"); + } else { + lines.add(cellName + ".addCallback(" + vVar + "::add);"); + } + } else if ("remove_callback".equals(opType)) { + String cbName = op.path("name").asText(); + lines.add(""); + lines.add(cellName + ".removeCallback(" + cbName + ");"); + } else if ("set_value".equals(opType)) { + int setVal = op.path("value").asInt(); + lines.add(""); + lines.add(cellName + ".setValue(" + setVal + ");"); + + boolean hasExpectCallbacks = op.has("expect_callbacks"); + boolean hasNotToBeCalled = op.has("expect_callbacks_not_to_be_called"); + + if (hasExpectCallbacks) { + JsonNode expCbs = op.get("expect_callbacks"); + java.util.List assertedVars = new java.util.ArrayList<>(); + expCbs.fields().forEachRemaining(entry -> { + String cb = entry.getKey(); + String vVar = cbValuesVar.get(cb); + int expectedVal = entry.getValue().asInt(); + lines.add("assertThat(" + vVar + ").containsExactly(" + expectedVal + ");"); + assertedVars.add(vVar); + }); + + boolean hasLaterOps = (i + 1 < operations.size()); + if (hasLaterOps) { + for (String aVar : assertedVars) { + lines.add(aVar + ".clear();"); + } + } + } + + if (hasNotToBeCalled) { + JsonNode notCbs = op.get("expect_callbacks_not_to_be_called"); + if (notCbs.isArray()) { + for (JsonNode notCb : notCbs) { + String cb = notCb.asText(); + String vVar = cbValuesVar.get(cb); + lines.add("assertThat(" + vVar + ").isEmpty();"); + } + } + } + } + } + } + + if (!lines.isEmpty() && lines.get(0).isEmpty()) { + lines.remove(0); + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderDotDslCase", (context, options) -> { + CanonicalCase cCase = toCanonicalCase(context); + if (cCase == null) return ""; + JsonNode textNode = cCase.input().path("text"); + if (!textNode.isArray()) return ""; + + java.util.LinkedHashMap graphAttrs = new java.util.LinkedHashMap<>(); + java.util.List nodes = new java.util.ArrayList<>(); + java.util.List edges = new java.util.ArrayList<>(); + + for (JsonNode lineNode : textNode) { + String line = lineNode.asText().trim(); + if (line.isEmpty() || line.equals("graph {") || line.equals("}")) continue; + if (line.endsWith(";")) line = line.substring(0, line.length() - 1).trim(); + + if (line.startsWith("[") && line.endsWith("]")) { + String inside = line.substring(1, line.length() - 1).trim(); + parseDotAttrs(inside, graphAttrs); + continue; + } + + if (line.contains("--")) { + String attrPart = ""; + String mainPart = line; + int bracketIdx = line.indexOf('['); + if (bracketIdx != -1 && line.endsWith("]")) { + attrPart = line.substring(bracketIdx + 1, line.length() - 1).trim(); + mainPart = line.substring(0, bracketIdx).trim(); + } + java.util.LinkedHashMap edgeAttrs = new java.util.LinkedHashMap<>(); + if (!attrPart.isEmpty()) { + parseDotAttrs(attrPart, edgeAttrs); + } + String[] parts = mainPart.split("\\s*--\\s*"); + if (parts.length > 2) { + for (String part : parts) { + nodes.add(new DotNode(part.trim(), new java.util.LinkedHashMap<>())); + } + } + for (int i = 0; i < parts.length - 1; i++) { + edges.add(new DotEdge(parts[i].trim(), parts[i + 1].trim(), new java.util.LinkedHashMap<>(edgeAttrs))); + } + continue; + } + + String attrPart = ""; + String nodeName = line; + int bracketIdx = line.indexOf('['); + if (bracketIdx != -1 && line.endsWith("]")) { + attrPart = line.substring(bracketIdx + 1, line.length() - 1).trim(); + nodeName = line.substring(0, bracketIdx).trim(); + } + java.util.LinkedHashMap nodeAttrs = new java.util.LinkedHashMap<>(); + if (!attrPart.isEmpty()) { + parseDotAttrs(attrPart, nodeAttrs); + } + nodes.add(new DotNode(nodeName, nodeAttrs)); + } + + java.util.List lines = new java.util.ArrayList<>(); + StringBuilder graphCall = new StringBuilder("Graph graph = new Graph("); + if (!graphAttrs.isEmpty()) { + graphCall.append(formatDotMapOf(graphAttrs)); + } + graphCall.append(")"); + java.util.List chainedCalls = new java.util.ArrayList<>(); + for (DotNode n : nodes) { + if (n.attrs.isEmpty()) { + chainedCalls.add(".node(\"" + n.name + "\")"); + } else { + chainedCalls.add(".node(\"" + n.name + "\", " + formatDotMapOf(n.attrs) + ")"); + } + } + for (DotEdge e : edges) { + if (e.attrs.isEmpty()) { + chainedCalls.add(".edge(\"" + e.start + "\", \"" + e.end + "\")"); + } else { + chainedCalls.add(".edge(\"" + e.start + "\", \"" + e.end + "\", " + formatDotMapOf(e.attrs) + ")"); + } + } + if (chainedCalls.isEmpty()) { + lines.add(graphCall.toString() + ";"); + } else if (chainedCalls.size() == 1 && graphAttrs.isEmpty()) { + lines.add(graphCall.toString() + chainedCalls.get(0) + ";"); + } else { + lines.add(graphCall.toString()); + for (int i = 0; i < chainedCalls.size(); i++) { + String semi = (i == chainedCalls.size() - 1) ? ";" : ""; + lines.add(" " + chainedCalls.get(i) + semi); + } + } + + lines.add(""); + + if (nodes.isEmpty()) { + lines.add("assertThat(graph.getNodes()).isEmpty();"); + } else if (nodes.size() == 1) { + DotNode n = nodes.get(0); + if (n.attrs.isEmpty()) { + lines.add("assertThat(graph.getNodes()).containsExactly(new Node(\"" + n.name + "\", Collections.emptyMap()));"); + } else { + lines.add("assertThat(graph.getNodes())"); + lines.add(" .containsExactly(new Node(\"" + n.name + "\", " + formatDotMapOf(n.attrs) + "));"); + } + } else { + java.util.List nodeExprs = new java.util.ArrayList<>(); + for (DotNode n : nodes) { + if (n.attrs.isEmpty()) { + nodeExprs.add("new Node(\"" + n.name + "\")"); + } else { + nodeExprs.add("new Node(\"" + n.name + "\", " + formatDotMapOf(n.attrs) + ")"); + } + } + lines.add("assertThat(graph.getNodes())"); + lines.add(" .containsExactlyInAnyOrder("); + for (int i = 0; i < nodeExprs.size(); i++) { + String comma = (i == nodeExprs.size() - 1) ? ");" : ","; + lines.add(" " + nodeExprs.get(i) + comma); + } + } + + if (edges.isEmpty()) { + lines.add("assertThat(graph.getEdges()).isEmpty();"); + } else if (edges.size() == 1) { + DotEdge e = edges.get(0); + if (e.attrs.isEmpty()) { + lines.add("assertThat(graph.getEdges())"); + lines.add(" .containsExactly(new Edge(\"" + e.start + "\", \"" + e.end + "\"));"); + } else { + lines.add("assertThat(graph.getEdges())"); + lines.add(" .containsExactly(new Edge(\"" + e.start + "\", \"" + e.end + "\", " + formatDotMapOf(e.attrs) + "));"); + } + } else { + java.util.List edgeExprs = new java.util.ArrayList<>(); + for (DotEdge e : edges) { + if (e.attrs.isEmpty()) { + edgeExprs.add("new Edge(\"" + e.start + "\", \"" + e.end + "\")"); + } else { + edgeExprs.add("new Edge(\"" + e.start + "\", \"" + e.end + "\", " + formatDotMapOf(e.attrs) + ")"); + } + } + lines.add("assertThat(graph.getEdges())"); + lines.add(" .containsExactlyInAnyOrder("); + for (int i = 0; i < edgeExprs.size(); i++) { + String comma = (i == edgeExprs.size() - 1) ? ");" : ","; + lines.add(" " + edgeExprs.get(i) + comma); + } + } + + if (graphAttrs.isEmpty()) { + lines.add("assertThat(graph.getAttributes()).isEmpty();"); + } else if (graphAttrs.size() == 1) { + var entry = graphAttrs.entrySet().iterator().next(); + lines.add("assertThat(graph.getAttributes()).containsEntry(\"" + entry.getKey() + "\", \"" + entry.getValue() + "\");"); + } else { + lines.add("assertThat(graph.getAttributes())"); + lines.add(" .containsExactlyInAnyOrderEntriesOf("); + lines.add(" " + formatDotMapOf(graphAttrs) + ");"); + } + + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderRestApiCase", (context, options) -> { + CanonicalCase cCase = toCanonicalCase(context); + if (cCase == null) return ""; + JsonNode input = cCase.input(); + JsonNode expected = cCase.expected(); + String prop = cCase.property(); + String url = input.path("url").asText(); + JsonNode payload = input.path("payload"); + JsonNode dbUsers = input.path("database").path("users"); + + java.util.List lines = new java.util.ArrayList<>(); + + String expectedCode = jsonNodeToOrgJson(expected, 16); + if (expectedCode.contains("\n")) { + lines.add("String expected = " + expectedCode); + lines.add(" .toString();"); + } else { + lines.add("String expected ="); + lines.add(" " + expectedCode + ".toString();"); + } + + lines.add("String url = \"" + JavaTypeFormatter.escapeJavaString(url) + "\";"); + + boolean hasPayload = payload.isObject() && !payload.isEmpty(); + if (hasPayload) { + String payloadCode = jsonNodeToOrgJson(payload, 16); + lines.add("JSONObject payload = " + payloadCode + ";"); + } + + java.util.List userVars = new java.util.ArrayList<>(); + if (dbUsers.isArray() && !dbUsers.isEmpty()) { + for (JsonNode u : dbUsers) { + String name = u.path("name").asText(); + String varName = JavaNamingHelper.toMethodName(name); + StringBuilder b = new StringBuilder(); + b.append("User ").append(varName).append(" = User.builder().setName(\"").append(name).append("\")"); + JsonNode owes = u.path("owes"); + if (owes.isObject()) { + owes.fields().forEachRemaining(entry -> { + b.append(".owes(\"").append(entry.getKey()).append("\", ").append(entry.getValue().asDouble()).append(")"); + }); + } + JsonNode owedBy = u.path("owed_by"); + if (!owedBy.isObject()) owedBy = u.path("owedBy"); + if (owedBy.isObject()) { + owedBy.fields().forEachRemaining(entry -> { + b.append(".owedBy(\"").append(entry.getKey()).append("\", ").append(entry.getValue().asDouble()).append(")"); + }); + } + b.append(".build();"); + lines.add(b.toString()); + userVars.add(varName); + } + } + + String restApiInst = userVars.isEmpty() ? "new RestApi()" : "new RestApi(" + String.join(", ", userVars) + ")"; + String call = restApiInst + "." + prop + "(url" + (hasPayload ? ", payload" : "") + ")"; + lines.add(""); + lines.add("assertThat(" + call + ").isEqualTo(expected);"); + + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderRobotCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode input = c.input(); + JsonNode expected = c.expected(); + int startX = input.path("position").path("x").asInt(); + int startY = input.path("position").path("y").asInt(); + String startDir = input.path("direction").asText().toUpperCase(); + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("Robot robot = new Robot(new GridPosition(" + startX + ", " + startY + "), Orientation." + startDir + ");"); + + if ("move".equals(c.property())) { + String inst = input.path("instructions").asText(); + if ("R".equals(inst)) { + lines.add("robot.turnRight();"); + } else if ("L".equals(inst)) { + lines.add("robot.turnLeft();"); + } else if ("A".equals(inst)) { + lines.add("robot.advance();"); + } else { + lines.add("robot.simulate(\"" + JavaTypeFormatter.escapeJavaString(inst) + "\");"); + } + } + + int expX = expected.path("position").path("x").asInt(); + int expY = expected.path("position").path("y").asInt(); + String expDir = expected.path("direction").asText().toUpperCase(); + + lines.add("assertThat(robot.getGridPosition()).isEqualTo(new GridPosition(" + expX + ", " + expY + "));"); + lines.add("assertThat(robot.getOrientation()).isEqualTo(Orientation." + expDir + ");"); + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderTournamentCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode inputRows = c.input().path("rows"); + JsonNode expectedRows = c.expected(); + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("Tournament tournament = new Tournament();"); + + if (inputRows.isArray() && !inputRows.isEmpty()) { + if (inputRows.size() == 1) { + lines.add("tournament.applyResults(\"" + JavaTypeFormatter.escapeJavaString(inputRows.get(0).asText()) + "\");"); + } else { + java.util.List parts = new java.util.ArrayList<>(); + for (JsonNode row : inputRows) { + parts.add("\"" + JavaTypeFormatter.escapeJavaString(row.asText()) + "\\n\""); + } + lines.add("tournament.applyResults(\n " + + String.join(" +\n ", parts) + "\n );"); + } + } + + if (expectedRows.isArray()) { + java.util.List parts = new java.util.ArrayList<>(); + for (JsonNode row : expectedRows) { + parts.add("\"" + JavaTypeFormatter.escapeJavaString(row.asText()) + "\\n\""); + } + if (parts.size() == 1) { + lines.add("assertThat(tournament.printTable()).isEqualTo(" + parts.get(0) + ");"); + } else { + lines.add("assertThat(tournament.printTable())\n" + + " .isEqualTo(\n " + + String.join(" +\n ", parts) + ");"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderTransposeCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode inputLines = c.input().path("lines"); + JsonNode expectedLines = c.expected(); + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("Transpose transpose = new Transpose();"); + + String inputExpr; + if (!inputLines.isArray() || inputLines.isEmpty()) { + inputExpr = "\"\""; + } else if (inputLines.size() == 1) { + inputExpr = "\"" + JavaTypeFormatter.escapeJavaString(inputLines.get(0).asText()) + "\""; + } else { + java.util.List parts = new java.util.ArrayList<>(); + for (int i = 0; i < inputLines.size(); i++) { + String line = JavaTypeFormatter.escapeJavaString(inputLines.get(i).asText()); + parts.add("\"" + line + (i < inputLines.size() - 1 ? "\\n\"" : "\"")); + } + inputExpr = "\n " + String.join(" +\n ", parts); + } + + String expectedExpr; + if (!expectedLines.isArray() || expectedLines.isEmpty()) { + expectedExpr = "\"\""; + } else if (expectedLines.size() == 1) { + expectedExpr = "\"" + JavaTypeFormatter.escapeJavaString(expectedLines.get(0).asText()) + "\""; + } else { + java.util.List parts = new java.util.ArrayList<>(); + for (int i = 0; i < expectedLines.size(); i++) { + String line = JavaTypeFormatter.escapeJavaString(expectedLines.get(i).asText()); + parts.add("\"" + line + (i < expectedLines.size() - 1 ? "\\n\"" : "\"")); + } + expectedExpr = "\n " + String.join(" +\n ", parts); + } + + lines.add("assertThat(transpose.transpose(" + inputExpr + "))\n" + + " .isEqualTo(" + expectedExpr + ");"); + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderBinarySearchTreeCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String prop = c.property(); + JsonNode treeData = c.input().path("treeData"); + JsonNode expected = c.expected(); + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("BinarySearchTree binarySearchTree = new BinarySearchTree<>();"); + + if ("sortedData".equals(prop)) { + if (treeData.isArray() && !treeData.isEmpty()) { + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode item : treeData) { + items.add("\"" + item.asText() + "\""); + } + lines.add("List treeData = List.of(" + String.join(", ", items) + ");"); + lines.add("treeData.forEach(binarySearchTree::insert);"); + } + if (expected.isArray()) { + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode item : expected) { + items.add("\"" + item.asText() + "\""); + } + lines.add("assertThat(binarySearchTree.getAsSortedList()).isEqualTo(List.of(" + String.join(", ", items) + "));"); + } + } else if ("data".equals(prop)) { + if (treeData.isArray() && !treeData.isEmpty()) { + for (JsonNode item : treeData) { + lines.add("binarySearchTree.insert(\"" + item.asText() + "\");"); + } + } + if (treeData.size() == 1) { + lines.add("BinarySearchTree.Node root = binarySearchTree.getRoot();"); + lines.add("assertThat(root).isNotNull();"); + lines.add("assertThat(root.getData()).isEqualTo(\"" + treeData.get(0).asText() + "\");"); + } else if (treeData.size() == 2) { + lines.add("BinarySearchTree.Node root = binarySearchTree.getRoot();"); + lines.add("assertThat(root).isNotNull();"); + lines.add("assertThat(root.getData()).isEqualTo(\"" + treeData.get(0).asText() + "\");"); + if (treeData.get(1).asText().compareTo(treeData.get(0).asText()) <= 0) { + lines.add("BinarySearchTree.Node left = root.getLeft();"); + lines.add("assertThat(left).isNotNull();"); + lines.add("assertThat(left.getData()).isEqualTo(\"" + treeData.get(1).asText() + "\");"); + } else { + lines.add("BinarySearchTree.Node right = root.getRight();"); + lines.add("assertThat(right).isNotNull();"); + lines.add("assertThat(right.getData()).isEqualTo(\"" + treeData.get(1).asText() + "\");"); + } + } else { + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode item : treeData) { + items.add("\"" + item.asText() + "\""); + } + lines.add("assertThat(binarySearchTree.getAsLevelOrderList()).isEqualTo(List.of(" + String.join(", ", items) + "));"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderClockCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String prop = c.property(); + JsonNode input = c.input(); + JsonNode expected = c.expected(); + + java.util.List lines = new java.util.ArrayList<>(); + + switch (prop) { + case "create" -> { + int h = input.path("hour").asInt(); + int m = input.path("minute").asInt(); + lines.add("assertThat(new Clock(" + h + ", " + m + ").toString()).isEqualTo(\"" + expected.asText() + "\");"); + } + case "add" -> { + int h = input.path("hour").asInt(); + int m = input.path("minute").asInt(); + int v = input.path("value").asInt(); + lines.add("Clock clock = new Clock(" + h + ", " + m + ");"); + lines.add("clock.add(" + v + ");"); + lines.add("assertThat(clock.toString()).isEqualTo(\"" + expected.asText() + "\");"); + } + case "subtract" -> { + int h = input.path("hour").asInt(); + int m = input.path("minute").asInt(); + int v = input.path("value").asInt(); + lines.add("Clock clock = new Clock(" + h + ", " + m + ");"); + lines.add("clock.add(" + (-v) + ");"); + lines.add("assertThat(clock.toString()).isEqualTo(\"" + expected.asText() + "\");"); + } + case "equal" -> { + int h1 = input.path("clock1").path("hour").asInt(); + int m1 = input.path("clock1").path("minute").asInt(); + int h2 = input.path("clock2").path("hour").asInt(); + int m2 = input.path("clock2").path("minute").asInt(); + lines.add("Clock clock1 = new Clock(" + h1 + ", " + m1 + ");"); + lines.add("Clock clock2 = new Clock(" + h2 + ", " + m2 + ");"); + if (expected.asBoolean()) { + lines.add("assertThat(clock1).isEqualTo(clock2);"); + } else { + lines.add("assertThat(clock1).isNotEqualTo(clock2);"); + } + } + default -> {} + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderCryptoSquareCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String pt = c.input().path("plaintext").asText(); + String exp = c.expected().asText(); + + java.util.List lines = new java.util.ArrayList<>(); + String ptExpr = pt.length() > 60 ? breakStringIntoChunks(pt, 16) : "\"" + JavaTypeFormatter.escapeJavaString(pt) + "\""; + String expExpr = exp.length() > 60 ? breakStringIntoChunks(exp, 16) : "\"" + JavaTypeFormatter.escapeJavaString(exp) + "\""; + lines.add("CryptoSquare cryptoSquare = new CryptoSquare(" + ptExpr + ");"); + lines.add("assertThat(cryptoSquare.getCiphertext()).isEqualTo(" + expExpr + ");"); + return String.join("\n ", lines); + }); + + handlebars.registerHelper("asDominoList", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + JsonNode dominoesNode = c != null ? c.input().path("dominoes") + : (context instanceof JsonNode n ? n : null); + if (dominoesNode == null || !dominoesNode.isArray() || dominoesNode.isEmpty()) { + return "List.of()"; + } + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode item : dominoesNode) { + if (item.isArray() && item.size() >= 2) { + items.add("new Domino(" + item.get(0).asInt() + ", " + item.get(1).asInt() + ")"); + } + } + if (items.size() <= 3 && String.join(", ", items).length() <= 50) { + return "List.of(" + String.join(", ", items) + ")"; + } + return "List.of(\n " + String.join(",\n ", items) + "\n )"; + }); + + handlebars.registerHelper("renderGoCountingCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String prop = c.property(); + JsonNode input = c.input(); + JsonNode expected = c.expected(); + JsonNode boardNode = input.path("board"); + + java.util.List lines = new java.util.ArrayList<>(); + String boardStr; + if (boardNode.isArray()) { + java.util.List bLines = new java.util.ArrayList<>(); + for (JsonNode b : boardNode) { + bLines.add("\"" + JavaTypeFormatter.escapeJavaString(b.asText()) + "\\n\""); + } + if (bLines.size() == 1) { + boardStr = "\"" + JavaTypeFormatter.escapeJavaString(boardNode.get(0).asText()) + "\""; + } else { + boardStr = "\n " + String.join(" +\n ", bLines); + } + } else { + boardStr = "\"\""; + } + + lines.add("GoCounting gocounting = new GoCounting(" + boardStr + ");"); + + if ("territory".equals(prop)) { + int x = input.path("x").asInt(); + int y = input.path("y").asInt(); + if (expected.has("error")) { + lines.add("assertThatExceptionOfType(IllegalArgumentException.class)"); + lines.add(" .isThrownBy(() -> gocounting.getTerritory(" + x + ", " + y + "))"); + lines.add(" .withMessage(\"Invalid coordinate\");"); + } else { + String owner = expected.path("owner").asText().toUpperCase(); + lines.add("assertThat(gocounting.getTerritoryOwner(" + x + ", " + y + ")).isEqualTo(Player." + + owner + ");"); + JsonNode terr = expected.path("territory"); + String setStr = formatPointSet(terr); + lines.add("assertThat(gocounting.getTerritory(" + x + ", " + y + ")).isEqualTo(" + setStr + ");"); + } + } else if ("territories".equals(prop)) { + lines.add("Set territoryBlack = " + formatPointSet(expected.path("territoryBlack")) + ";"); + lines.add("Set territoryWhite = " + formatPointSet(expected.path("territoryWhite")) + ";"); + lines.add("Set territoryNone = " + formatPointSet(expected.path("territoryNone")) + ";"); + lines.add("Map> expected = Map.of("); + lines.add(" Player.BLACK, territoryBlack,"); + lines.add(" Player.WHITE, territoryWhite,"); + lines.add(" Player.NONE, territoryNone"); + lines.add(");"); + lines.add("assertThat(gocounting.getTerritories()).isEqualTo(expected);"); + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("asLocalDate", (context, options) -> { + if (context == null) return "null"; + String s = context instanceof JsonNode n ? n.asText() : context.toString(); + s = s.replace("\"", ""); + String[] parts = s.split("-"); + if (parts.length == 3) { + return "LocalDate.of(" + Integer.parseInt(parts[0]) + ", " + + Integer.parseInt(parts[1]) + ", " + Integer.parseInt(parts[2]) + ")"; + } + return "LocalDate.parse(\"" + s + "\")"; + }); + + handlebars.registerHelper("asStringList", (context, options) -> { + if (context instanceof JsonNode node && node.isArray()) { + if (node.isEmpty()) return "List.of()"; + java.util.List list = new java.util.ArrayList<>(); + for (JsonNode item : node) { + list.add("\"" + JavaTypeFormatter.escapeJavaString(item.asText()) + "\""); + } + String joined = String.join(", ", list); + if (joined.length() <= 50 && list.size() <= 3) { + return "List.of(" + joined + ")"; + } + return "List.of(\n " + + String.join(",\n ", list) + + "\n )"; + } + return "List.of()"; + }); + + handlebars.registerHelper("renderSgfCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String encoded = c.input().path("encoded").asText(); + JsonNode expected = c.expected(); + + java.util.List lines = new java.util.ArrayList<>(); + String encExpr; + if (encoded.length() > 60) { + encExpr = breakStringIntoChunks(encoded, 16); + } else { + encExpr = "\"" + JavaTypeFormatter.escapeJavaString(encoded) + "\""; + } + + if (expected.has("error")) { + lines.add("assertThatExceptionOfType(SgfParsingException.class)"); + lines.add(" .isThrownBy(() -> new SgfParsing().parse(" + encExpr + "));"); + } else { + String nodeExpr = formatSgfNode(expected, 8); + lines.add("SgfNode expected = " + nodeExpr + ";"); + lines.add("assertThat(new SgfParsing().parse(" + encExpr + ")).isEqualTo(expected);"); + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderSimpleLinkedListCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode init = c.input().path("initialValues"); + JsonNode ops = c.input().path("operations"); + + java.util.List lines = new java.util.ArrayList<>(); + if (init.isArray() && !init.isEmpty()) { + java.util.List initVals = new java.util.ArrayList<>(); + for (JsonNode v : init) initVals.add(v.asText()); + lines.add("SimpleLinkedList list = new SimpleLinkedList<>(new Integer[]{" + + String.join(", ", initVals) + "});"); + } else { + lines.add("SimpleLinkedList list = new SimpleLinkedList<>();"); + } + + if (ops.isArray()) { + for (JsonNode op : ops) { + String opName = op.path("operation").asText(); + JsonNode exp = op.path("expected"); + switch (opName) { + case "count" -> { + lines.add("assertThat(list.size()).isEqualTo(" + exp.asInt() + ");"); + } + case "pop" -> { + if (exp.has("error")) { + lines.add("assertThatExceptionOfType(NoSuchElementException.class)" + + ".isThrownBy(list::pop);"); + } else { + lines.add("assertThat(list.pop()).isEqualTo(" + exp.asInt() + ");"); + } + } + case "push" -> { + lines.add("list.push(" + op.path("value").asInt() + ");"); + } + case "peek" -> { + if (exp.has("error")) { + lines.add("assertThatExceptionOfType(NoSuchElementException.class)" + + ".isThrownBy(list::peek);"); + } else { + lines.add("assertThat(list.peek()).isEqualTo(" + exp.asInt() + ");"); + } + } + case "toList" -> { + if (exp.isArray() && exp.isEmpty()) { + lines.add("assertThat(list.toList()).isEmpty();"); + } else if (exp.isArray()) { + java.util.List vals = new java.util.ArrayList<>(); + for (JsonNode v : exp) vals.add(v.asText()); + lines.add("assertThat(list.toList()).containsExactly(" + + String.join(", ", vals) + ");"); + } + } + case "reverse" -> { + lines.add("list.reverse();"); + } + default -> {} + } + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderTreeBuildingCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode recordsNode = c.input().path("records"); + JsonNode expected = c.expected(); + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("ArrayList records = new ArrayList<>();"); + if (recordsNode.isArray() && !recordsNode.isEmpty()) { + for (JsonNode r : recordsNode) { + int rId = r.path("recordId").asInt(); + int pId = r.path("parentId").asInt(); + lines.add("records.add(new Record(" + rId + ", " + pId + "));"); + } + } + + if (expected.has("error")) { + lines.add("assertThatExceptionOfType(InvalidRecordsException.class)"); + lines.add(" .isThrownBy(() -> new BuildTree().buildTree(records));"); + } else if (!expected.has("node")) { + lines.add("TreeNode root = new BuildTree().buildTree(records);"); + lines.add("assertThat(root).isNull();"); + } else { + lines.add("TreeNode root = new BuildTree().buildTree(records);"); + lines.add("assertThat(root).isNotNull();"); + generateTreeAssertions(expected.path("node"), "root", lines); + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderWordSearchCase", (context, options) -> { + exercism.testgenerator.model.CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode gridNode = c.input().path("grid"); + JsonNode wordsToSearch = c.input().has("wordsToSearchFor") + ? c.input().path("wordsToSearchFor") + : c.input().path("wordsToSearch"); + JsonNode expected = c.expected(); + + java.util.List lines = new java.util.ArrayList<>(); + lines.add("WordSearcher wordSearcher = new WordSearcher();"); + + java.util.List gridRows = new java.util.ArrayList<>(); + if (gridNode.isArray()) { + for (JsonNode row : gridNode) { + gridRows.add("\"" + JavaTypeFormatter.escapeJavaString(row.asText()) + "\".toCharArray()"); + } + } + if (gridRows.size() <= 2) { + lines.add("char[][] grid = new char[][]{" + String.join(", ", gridRows) + "};"); + } else { + lines.add("char[][] grid = new char[][]{"); + for (int i = 0; i < gridRows.size(); i++) { + lines.add(" " + gridRows.get(i) + (i < gridRows.size() - 1 ? "," : "")); + } + lines.add("};"); + } + + java.util.List words = new java.util.ArrayList<>(); + if (wordsToSearch.isArray()) { + for (JsonNode w : wordsToSearch) { + words.add("\"" + JavaTypeFormatter.escapeJavaString(w.asText()) + "\""); + } + } + if (words.size() <= 3 && String.join(", ", words).length() <= 50) { + lines.add("Set wordsToSearchFor = Set.of(" + String.join(", ", words) + ");"); + } else { + lines.add("Set wordsToSearchFor = Set.of("); + lines.add(" " + String.join(",\n ", words)); + lines.add(");"); + } + + lines.add("Map> expectedLocations = new HashMap<>();"); + if (expected.isObject()) { + expected.fields().forEachRemaining(entry -> { + String word = entry.getKey(); + JsonNode loc = entry.getValue(); + if (loc == null || loc.isNull()) { + lines.add("expectedLocations.put(\"" + word + "\", Optional.empty());"); + } else { + int startCol = loc.path("start").path("column").asInt(); + int startRow = loc.path("start").path("row").asInt(); + int endCol = loc.path("end").path("column").asInt(); + int endRow = loc.path("end").path("row").asInt(); + lines.add("expectedLocations.put(\"" + word + "\", Optional.of(new WordLocation("); + lines.add(" new Pair(" + startCol + ", " + startRow + "),"); + lines.add(" new Pair(" + endCol + ", " + endRow + ")"); + lines.add(")));"); + } + }); + } + + lines.add("Map> actualLocations = " + + "wordSearcher.search(wordsToSearchFor, grid);"); + lines.add("assertThat(actualLocations).isEqualTo(expectedLocations);"); + + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderZipperCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + java.util.List lines = new java.util.ArrayList<>(); + + if ("sameResultFromOperations".equals(c.property())) { + JsonNode ops1 = c.input().path("operations"); + JsonNode ops2 = c.expected().path("operations"); + lines.add("Zipper zipper1 = binaryTree.getRoot()" + buildZipperNavPath(ops1) + ";"); + lines.add("Zipper zipper2 = binaryTree.getRoot()" + buildZipperNavPath(ops2) + ";"); + lines.add("assertThat(zipper1).isEqualTo(zipper2);"); + return String.join("\n ", lines); + } + + JsonNode ops = c.input().path("operations"); + if (!ops.isArray() || ops.isEmpty()) return ""; + + if (ops.size() == 1 && "to_tree".equals(ops.get(0).path("operation").asText())) { + lines.add("assertThat(zipper.toTree()).isEqualTo(binaryTree);"); + return String.join("\n ", lines); + } + + int mutationIdx = -1; + for (int i = 0; i < ops.size(); i++) { + String opName = ops.get(i).path("operation").asText(); + if (opName.startsWith("set_")) { + mutationIdx = i; + break; + } + } + + if (mutationIdx != -1) { + JsonNode mutOp = ops.get(mutationIdx); + String mutName = mutOp.path("operation").asText(); + JsonNode item = mutOp.path("item"); + + boolean isSubtree = item.isObject() && (!item.path("left").isNull() || !item.path("right").isNull()); + if (isSubtree) { + int subVal = item.path("value").asInt(); + lines.add("BinaryTree subtree = new BinaryTree(" + subVal + ");"); + if (!item.path("left").isNull()) { + lines.add("subtree.getRoot().setLeft(new Zipper(" + item.path("left").path("value").asInt() + "));"); + } + if (!item.path("right").isNull()) { + lines.add("subtree.getRoot().setRight(new Zipper(" + item.path("right").path("value").asInt() + "));"); + } + } + + lines.add("zipper = binaryTree.getRoot();"); + if (mutationIdx > 0) { + StringBuilder nav = new StringBuilder(); + for (int i = 0; i < mutationIdx; i++) { + nav.append(".").append(ops.get(i).path("operation").asText()); + } + lines.add("zipper = zipper" + nav.toString() + ";"); + } + + if ("set_value".equals(mutName)) { + lines.add("zipper.setValue(" + item.asInt() + ");"); + } else if ("set_left".equals(mutName)) { + if (item.isNull()) { + lines.add("zipper.setLeft(null);"); + } else { + lines.add("zipper.setLeft(new Zipper(" + item.path("value").asInt() + "));"); + } + } else if ("set_right".equals(mutName)) { + if (item.isNull()) { + lines.add("zipper.setRight(null);"); + } else if (isSubtree) { + lines.add("zipper.setRight(subtree.getRoot());"); + } else { + lines.add("zipper.setRight(new Zipper(" + item.path("value").asInt() + "));"); + } + } + + JsonNode expVal = c.expected().path("value"); + String treeStr = formatZipperPrintTree(expVal); + lines.add("String expected ="); + lines.add(" " + breakZipperString(treeStr) + ";"); + lines.add("assertThat(zipper.toTree().printTree()).isEqualTo(expected);"); + return String.join("\n ", lines); + } + + lines.add("zipper = binaryTree.getRoot();"); + JsonNode lastOp = ops.get(ops.size() - 1); + String lastOpName = lastOp.path("operation").asText(); + + StringBuilder nav = new StringBuilder(); + for (int i = 0; i < ops.size() - 1; i++) { + nav.append(".").append(ops.get(i).path("operation").asText()); + } + + if ("value".equals(lastOpName)) { + int expVal = c.expected().path("value").asInt(); + lines.add("assertThat(zipper" + nav.toString() + ".getValue()).isEqualTo(" + expVal + ");"); + } else if ("to_tree".equals(lastOpName)) { + lines.add("assertThat(zipper" + nav.toString() + ".toTree()).isEqualTo(binaryTree);"); + } else { + nav.append(".").append(lastOpName); + lines.add("assertThat(zipper" + nav.toString() + ").isNull();"); + } + + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderBookStoreCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode basket = c.input().path("basket"); + java.util.List items = new java.util.ArrayList<>(); + if (basket.isArray()) { + for (JsonNode item : basket) { + items.add(String.valueOf(item.asInt())); + } + } + java.util.List lines = new java.util.ArrayList<>(); + String basketExpr; + if (items.isEmpty()) { + basketExpr = "List.of()"; + } else if (items.size() <= 8) { + basketExpr = "List.of(" + String.join(", ", items) + ")"; + } else { + basketExpr = "List.of(\n " + String.join(", ", items) + "\n )"; + } + lines.add("List books = " + basketExpr + ";"); + double dollars = c.expected().asDouble() / 100.0; + String dollarStr = String.format(java.util.Locale.ROOT, "%.2f", dollars); + lines.add("assertThat(bookStore.calculateBasketCost(books))"); + lines.add(" .isCloseTo(" + dollarStr + ", offset(EQUALITY_TOLERANCE));"); + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderChangeCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode coinsNode = c.input().path("coins"); + int target = c.input().path("target").asInt(); + java.util.List coins = new java.util.ArrayList<>(); + if (coinsNode.isArray()) { + for (JsonNode coin : coinsNode) { + coins.add(String.valueOf(coin.asInt())); + } + } + String coinsExpr = "asList(" + String.join(", ", coins) + ")"; + java.util.List lines = new java.util.ArrayList<>(); + lines.add("ChangeCalculator changeCalculator = new ChangeCalculator(" + coinsExpr + ");"); + lines.add(""); + + if (c.expected().isObject() && c.expected().has("error")) { + lines.add("assertThatExceptionOfType(IllegalArgumentException.class)"); + lines.add(" .isThrownBy(() -> changeCalculator.computeMostEfficientChange(" + target + "))"); + if (target < 0) { + lines.add(" .withMessage(\"Negative totals are not allowed.\");"); + } else { + lines.add(" .withMessage(\"The total " + target + + " cannot be represented in the given currency.\");"); + } + } else if (c.expected().isArray()) { + java.util.List expCoins = new java.util.ArrayList<>(); + for (JsonNode coin : c.expected()) { + expCoins.add(String.valueOf(coin.asInt())); + } + if (expCoins.isEmpty()) { + lines.add("assertThat(changeCalculator.computeMostEfficientChange(" + target + "))"); + lines.add(" .isEmpty();"); + } else { + lines.add("assertThat(changeCalculator.computeMostEfficientChange(" + target + "))"); + lines.add(" .containsExactly(" + String.join(", ", expCoins) + ");"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderCircularBufferCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + int capacity = c.input().path("capacity").asInt(); + JsonNode ops = c.input().path("operations"); + java.util.List lines = new java.util.ArrayList<>(); + lines.add("CircularBuffer buffer = new CircularBuffer<>(" + capacity + ");"); + + if (ops.isArray()) { + for (JsonNode op : ops) { + String operation = op.path("operation").asText(); + boolean shouldSucceed = op.path("should_succeed").asBoolean(true); + lines.add(""); + switch (operation) { + case "write" -> { + int item = op.path("item").asInt(); + if (shouldSucceed) { + lines.add("buffer.write(" + item + ");"); + } else { + lines.add("assertThatExceptionOfType(BufferIOException.class)"); + lines.add(" .isThrownBy(() -> buffer.write(" + item + "))"); + lines.add(" .withMessage(\"Tried to write to full buffer\");"); + } + } + case "read" -> { + if (shouldSucceed) { + int expected = op.path("expected").asInt(); + lines.add("assertThat(buffer.read()).isEqualTo(" + expected + ");"); + } else { + lines.add("assertThatExceptionOfType(BufferIOException.class)"); + lines.add(" .isThrownBy(buffer::read)"); + lines.add(" .withMessage(\"Tried to read from empty buffer\");"); + } + } + case "overwrite" -> { + int item = op.path("item").asInt(); + lines.add("buffer.overwrite(" + item + ");"); + } + case "clear" -> { + lines.add("buffer.clear();"); + } + } + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderComplexNumberCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String prop = c.property(); + JsonNode input = c.input(); + JsonNode expected = c.expected(); + java.util.List lines = new java.util.ArrayList<>(); + + java.util.function.Function numStr = n -> { + if (n == null) return "0.0"; + if (n.isTextual()) { + String t = n.asText(); + return switch (t) { + case "pi" -> "Math.PI"; + case "pi/4" -> "Math.PI / 4"; + case "ln(2)" -> "Math.log(2.0)"; + case "ln(2)/2" -> "Math.log(2.0) / 2"; + case "e" -> "Math.E"; + default -> t; + }; + } + double d = n.asDouble(); + return (d == (long) d) ? String.format(java.util.Locale.ROOT, "%.1f", d) : String.valueOf(d); + }; + + switch (prop) { + case "real" -> { + JsonNode z = input.path("z"); + String r = numStr.apply(z.get(0)); + String i = numStr.apply(z.get(1)); + String exp = numStr.apply(expected); + lines.add("double expected = " + exp + ";"); + lines.add("double actual = new ComplexNumber(" + r + ", " + i + ").getReal();"); + lines.add("assertDoublesEqual(expected, actual, \"real\");"); + } + case "imaginary" -> { + JsonNode z = input.path("z"); + String r = numStr.apply(z.get(0)); + String i = numStr.apply(z.get(1)); + String exp = numStr.apply(expected); + lines.add("double expected = " + exp + ";"); + lines.add("double actual = new ComplexNumber(" + r + ", " + i + ").getImaginary();"); + lines.add("assertDoublesEqual(expected, actual, \"imaginary\");"); + } + case "abs" -> { + JsonNode z = input.path("z"); + String r = numStr.apply(z.get(0)); + String i = numStr.apply(z.get(1)); + String exp = numStr.apply(expected); + lines.add("double expected = " + exp + ";"); + lines.add("double actual = new ComplexNumber(" + r + ", " + i + ").abs();"); + lines.add("assertDoublesEqual(expected, actual, \"real\");"); + } + case "conjugate" -> { + JsonNode z = input.path("z"); + String r = numStr.apply(z.get(0)); + String i = numStr.apply(z.get(1)); + String expR = numStr.apply(expected.get(0)); + String expI = numStr.apply(expected.get(1)); + lines.add("ComplexNumber expected = new ComplexNumber(" + expR + ", " + expI + ");"); + lines.add("ComplexNumber actual = new ComplexNumber(" + r + ", " + i + ").conjugate();"); + lines.add("assertComplexNumbersEqual(expected, actual);"); + } + case "exp" -> { + JsonNode z = input.path("z"); + String r = numStr.apply(z.get(0)); + String i = numStr.apply(z.get(1)); + String expR = numStr.apply(expected.get(0)); + String expI = numStr.apply(expected.get(1)); + lines.add("ComplexNumber expected = new ComplexNumber(" + expR + ", " + expI + ");"); + lines.add("ComplexNumber actual = new ComplexNumber(" + r + ", " + i + ").exponentialOf();"); + lines.add("assertComplexNumbersEqual(expected, actual);"); + } + case "add", "sub", "mul", "div" -> { + JsonNode z1 = input.path("z1"); + JsonNode z2 = input.path("z2"); + String r1 = numStr.apply(z1.get(0)); + String i1 = numStr.apply(z1.get(1)); + String r2 = numStr.apply(z2.get(0)); + String i2 = numStr.apply(z2.get(1)); + String expR = numStr.apply(expected.get(0)); + String expI = numStr.apply(expected.get(1)); + String method = switch (prop) { + case "add" -> "add"; + case "sub" -> "subtract"; + case "mul" -> "multiply"; + case "div" -> "divide"; + default -> prop; + }; + lines.add("ComplexNumber expected = new ComplexNumber(" + expR + ", " + expI + ");"); + lines.add("ComplexNumber actual = new ComplexNumber(" + r1 + ", " + i1 + ")" + + "." + method + "(new ComplexNumber(" + r2 + ", " + i2 + "));"); + lines.add("assertComplexNumbersEqual(expected, actual);"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderConnectCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode boardNode = c.input().path("board"); + java.util.List rows = new java.util.ArrayList<>(); + if (boardNode.isArray()) { + for (JsonNode row : boardNode) { + rows.add("\"" + JavaTypeFormatter.escapeJavaString(row.asText()) + "\""); + } + } + String expWinner = switch (c.expected().asText()) { + case "X" -> "Winner.PLAYER_X"; + case "O" -> "Winner.PLAYER_O"; + default -> "Winner.NONE"; + }; + java.util.List lines = new java.util.ArrayList<>(); + lines.add("String[] board = new String[]{"); + for (int i = 0; i < rows.size(); i++) { + lines.add(" " + rows.get(i) + (i < rows.size() - 1 ? "," : "")); + } + lines.add("};"); + lines.add("assertThat(new Connect(board).computeWinner()).isEqualTo(" + expWinner + ");"); + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderListOpsCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String prop = c.property(); + java.util.List lines = new java.util.ArrayList<>(); + + java.util.function.Function formatCharTree = new java.util.function.Function<>() { + @Override + public String apply(JsonNode node) { + if (node == null || node.isNull()) return "null"; + if (!node.isArray()) { + return "'" + node.asText() + "'"; + } + if (node.isEmpty()) { + return "List.of()"; + } + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode child : node) { + items.add(apply(child)); + } + return "List.of(" + String.join(", ", items) + ")"; + } + }; + + switch (prop) { + case "append" -> { + JsonNode list1 = c.input().path("list1"); + JsonNode list2 = c.input().path("list2"); + String l1 = JavaTypeFormatter.format(list1); + String l2 = JavaTypeFormatter.format(list2); + JsonNode exp = c.expected(); + if (exp.isEmpty()) { + lines.add("assertThat(ListOps.append(" + l1 + ", " + l2 + ")).isEmpty();"); + } else { + lines.add("assertThat(ListOps.append(" + l1 + ", " + l2 + "))"); + lines.add(" .isEqualTo(" + JavaTypeFormatter.format(exp) + ");"); + } + } + case "concat" -> { + JsonNode nested = c.input().has("lists") ? c.input().path("lists") : c.input().path("nested"); + if (nested.isEmpty()) { + lines.add("assertThat(ListOps.concat(List.of())).isEmpty();"); + } else if (nested.get(0).isArray() && !nested.get(0).isEmpty() && nested.get(0).get(0).isArray()) { + lines.add("List>> listOfNestedLists = List.of("); + for (int outerIdx = 0; outerIdx < nested.size(); outerIdx++) { + JsonNode outer = nested.get(outerIdx); + java.util.List subItems = new java.util.ArrayList<>(); + for (JsonNode inner : outer) { + subItems.add(formatCharTree.apply(inner)); + } + if (subItems.isEmpty()) { + lines.add(" List.of()" + (outerIdx < nested.size() - 1 ? "," : "")); + } else { + lines.add(" List.of("); + for (int innerIdx = 0; innerIdx < subItems.size(); innerIdx++) { + lines.add(" " + subItems.get(innerIdx) + (innerIdx < subItems.size() - 1 ? "," : "")); + } + lines.add(" )" + (outerIdx < nested.size() - 1 ? "," : "")); + } + } + lines.add(");"); + java.util.List expItems = new java.util.ArrayList<>(); + for (JsonNode expItem : c.expected()) { + expItems.add(formatCharTree.apply(expItem)); + } + lines.add("assertThat(ListOps.concat(listOfNestedLists))"); + lines.add(" .isEqualTo(List.of("); + for (int i = 0; i < expItems.size(); i++) { + lines.add(" " + expItems.get(i) + (i < expItems.size() - 1 ? "," : "")); + } + lines.add(" ));"); + } else { + java.util.List inItems = new java.util.ArrayList<>(); + for (JsonNode child : nested) { + inItems.add(formatCharTree.apply(child)); + } + java.util.List expChars = new java.util.ArrayList<>(); + for (JsonNode child : c.expected()) { + expChars.add("'" + child.asText() + "'"); + } + lines.add("List> listOfLists = List.of("); + for (int i = 0; i < inItems.size(); i++) { + lines.add(" " + inItems.get(i) + (i < inItems.size() - 1 ? "," : "")); + } + lines.add(");"); + lines.add("assertThat(ListOps.concat(listOfLists)).containsExactly(" + String.join(", ", expChars) + ");"); + } + } + case "filter" -> { + JsonNode list = c.input().path("list"); + if (list.isEmpty()) { + lines.add("assertThat(ListOps.filter(List.of(), integer -> integer % 2 == 1))"); + lines.add(" .isEmpty();"); + } else { + java.util.List inVals = new java.util.ArrayList<>(); + for (JsonNode v : list) inVals.add(String.valueOf(v.asInt())); + java.util.List expVals = new java.util.ArrayList<>(); + for (JsonNode v : c.expected()) expVals.add(String.valueOf(v.asInt())); + lines.add("assertThat(ListOps.filter(List.of(" + String.join(", ", inVals) + "), integer -> integer % 2 == 1))"); + lines.add(" .containsExactly(" + String.join(", ", expVals) + ");"); + } + } + case "length" -> { + JsonNode list = c.input().path("list"); + if (list.isEmpty()) { + lines.add("assertThat(ListOps.size(List.of())).isEqualTo(0);"); + } else { + lines.add("assertThat(ListOps.size(List.of(\"one\", \"two\", \"three\", \"four\"))).isEqualTo(4);"); + } + } + case "map" -> { + JsonNode list = c.input().path("list"); + if (list.isEmpty()) { + lines.add("assertThat(ListOps.map(List.of(), integer -> integer + 1)).isEmpty();"); + } else { + java.util.List inVals = new java.util.ArrayList<>(); + for (JsonNode v : list) inVals.add(String.valueOf(v.asInt())); + java.util.List expVals = new java.util.ArrayList<>(); + for (JsonNode v : c.expected()) expVals.add(String.valueOf(v.asInt())); + lines.add("assertThat(ListOps.map(List.of(" + String.join(", ", inVals) + "), integer -> integer + 1))"); + lines.add(" .containsExactly(" + String.join(", ", expVals) + ");"); + } + } + case "reverse" -> { + JsonNode list = c.input().path("list"); + if (list.isEmpty()) { + lines.add("assertThat(ListOps.reverse(List.of())).isEmpty();"); + } else if (list.get(0).isArray()) { + java.util.List inItems = new java.util.ArrayList<>(); + for (JsonNode child : list) inItems.add(formatCharTree.apply(child)); + java.util.List expItems = new java.util.ArrayList<>(); + for (JsonNode child : c.expected()) expItems.add(formatCharTree.apply(child)); + lines.add("List> listOfLists = List.of("); + for (int i = 0; i < inItems.size(); i++) { + lines.add(" " + inItems.get(i) + (i < inItems.size() - 1 ? "," : "")); + } + lines.add(");"); + lines.add("assertThat(ListOps.reverse(listOfLists)).containsExactly("); + for (int i = 0; i < expItems.size(); i++) { + lines.add(" " + expItems.get(i) + (i < expItems.size() - 1 ? "," : "")); + } + lines.add(");"); + } else { + java.util.List inChars = new java.util.ArrayList<>(); + for (JsonNode child : list) inChars.add("'" + child.asText() + "'"); + java.util.List expChars = new java.util.ArrayList<>(); + for (JsonNode child : c.expected()) expChars.add("'" + child.asText() + "'"); + lines.add("assertThat(ListOps.reverse(List.of(" + String.join(", ", inChars) + ")))"); + lines.add(" .containsExactly(" + String.join(", ", expChars) + ");"); + } + } + case "foldl" -> { + JsonNode list = c.input().path("list"); + String fn = c.input().path("function").asText(); + double init = c.input().path("initial").asDouble(); + double exp = c.expected().asDouble(); + if (list.isEmpty()) { + lines.add("assertThat(ListOps.foldLeft(List.of(), " + init + ", (acc, el) -> el * acc))"); + lines.add(" .isEqualTo(" + exp + ");"); + } else if (fn.contains("+")) { + java.util.List inVals = new java.util.ArrayList<>(); + for (JsonNode v : list) inVals.add(String.valueOf(v.asInt())); + lines.add("assertThat(ListOps.foldLeft(List.of(" + String.join(", ", inVals) + "), " + (int) init + ", Integer::sum))"); + lines.add(" .isEqualTo(" + (int) exp + ");"); + } else { + java.util.List inVals = new java.util.ArrayList<>(); + for (JsonNode v : list) inVals.add(String.format(java.util.Locale.ROOT, "%.1f", v.asDouble())); + lines.add("assertThat(ListOps.foldLeft(List.of(" + String.join(", ", inVals) + "), " + String.format(java.util.Locale.ROOT, "%.1f", init) + ", (acc, el) -> el / acc))"); + lines.add(" .isEqualTo(" + exp + ");"); + } + } + case "foldr" -> { + JsonNode list = c.input().path("list"); + String fn = c.input().path("function").asText(); + double init = c.input().path("initial").asDouble(); + double exp = c.expected().asDouble(); + if (list.isEmpty()) { + lines.add("assertThat(ListOps.foldRight(List.of(), " + init + ", (el, acc) -> el * acc))"); + lines.add(" .isEqualTo(" + exp + ");"); + } else if (fn.contains("+")) { + java.util.List inVals = new java.util.ArrayList<>(); + for (JsonNode v : list) inVals.add(String.valueOf(v.asInt())); + lines.add("assertThat(ListOps.foldRight(List.of(" + String.join(", ", inVals) + "), " + (int) init + ", Integer::sum))"); + lines.add(" .isEqualTo(" + (int) exp + ");"); + } else { + java.util.List inVals = new java.util.ArrayList<>(); + for (JsonNode v : list) inVals.add(String.format(java.util.Locale.ROOT, "%.1f", v.asDouble())); + lines.add("assertThat(ListOps.foldRight(List.of(" + String.join(", ", inVals) + "), " + String.format(java.util.Locale.ROOT, "%.1f", init) + ", (el, acc) -> el / acc))"); + lines.add(" .isEqualTo(" + exp + ");"); + } + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderOcrCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode rows = c.input().path("rows"); + java.util.List rowLines = new java.util.ArrayList<>(); + if (rows.isArray()) { + for (JsonNode r : rows) { + rowLines.add("\"" + JavaTypeFormatter.escapeJavaString(r.asText()) + "\""); + } + } + java.util.List lines = new java.util.ArrayList<>(); + String singleLineRows = "List.of(" + String.join(", ", rowLines) + ")"; + String rowsExpr; + if (singleLineRows.length() > 50) { + rowsExpr = "List.of(\n" + + " " + String.join(",\n ", rowLines) + + ")"; + } else { + rowsExpr = singleLineRows; + } + if (c.expected().isObject() && c.expected().has("error")) { + int numRows = rows.size(); + String msg = (numRows % 4 != 0) + ? "Number of input rows must be a positive multiple of 4" + : "Number of input columns must be a positive multiple of 3"; + lines.add("assertThatExceptionOfType(IllegalArgumentException.class)"); + lines.add(" .isThrownBy(() -> new OpticalCharacterReader().parse(" + rowsExpr + "))"); + lines.add(" .withMessage(\"" + msg + "\");"); + } else { + lines.add("assertThat(new OpticalCharacterReader().parse(" + rowsExpr + "))"); + lines.add(" .isEqualTo(\"" + JavaTypeFormatter.escapeJavaString(c.expected().asText()) + "\");"); + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderPalindromeProductsCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + int min = c.input().path("min").asInt(); + int max = c.input().path("max").asInt(); + String prop = c.property(); + java.util.List lines = new java.util.ArrayList<>(); + + if (c.expected().isObject() && c.expected().has("error")) { + lines.add("assertThatExceptionOfType(IllegalArgumentException.class)"); + lines.add(" .isThrownBy(() -> palindromeCalculator.getPalindromeProductsWithFactors(" + + min + ", " + max + "))"); + lines.add(" .withMessage(\"invalid input: min must be <= max\");"); + } else { + lines.add("SortedMap>> palindromes ="); + lines.add(" palindromeCalculator.getPalindromeProductsWithFactors(" + min + ", " + max + ");"); + lines.add(""); + JsonNode expVal = c.expected().path("value"); + if (expVal == null || expVal.isNull() || !expVal.isNumber()) { + lines.add("assertThat(palindromes.isEmpty()).isTrue();"); + } else { + long val = expVal.asLong(); + JsonNode factors = c.expected().path("factors"); + java.util.List pairs = new java.util.ArrayList<>(); + if (factors.isArray()) { + for (JsonNode pair : factors) { + pairs.add("List.of(" + pair.get(0).asInt() + ", " + pair.get(1).asInt() + ")"); + } + } + lines.add("List> expected = List.of("); + for (int i = 0; i < pairs.size(); i++) { + lines.add(" " + pairs.get(i) + (i < pairs.size() - 1 ? "," : "")); + } + lines.add(");"); + lines.add("long expectedValue = " + val + "L;"); + String keyMethod = prop.equals("smallest") ? "palindromes.firstKey()" : "palindromes.lastKey()"; + lines.add("checkPalindromeWithFactorsMatchesExpected(expected, expectedValue, palindromes, " + + keyMethod + ");"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderPovCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String prop = c.property(); + JsonNode treeNode = c.input().path("tree"); + java.util.List lines = new java.util.ArrayList<>(); + + java.util.function.BiFunction formatPovTree = new java.util.function.BiFunction<>() { + @Override + public String apply(JsonNode node, Integer depth) { + if (node == null || node.isNull()) return "null"; + String label = "\"" + JavaTypeFormatter.escapeJavaString(node.path("label").asText()) + "\""; + JsonNode children = node.path("children"); + if (children != null && children.isArray() && !children.isEmpty()) { + java.util.List inlineChildren = new java.util.ArrayList<>(); + for (JsonNode ch : children) { + inlineChildren.add(apply(ch, 0)); + } + String inline = "Tree.of(" + label + ", List.of(" + String.join(", ", inlineChildren) + "))"; + if (inline.length() <= 40) { + return inline; + } + String indent = " ".repeat(depth + 2); + java.util.List chList = new java.util.ArrayList<>(); + for (JsonNode ch : children) { + chList.add(indent + apply(ch, depth + 1)); + } + return "Tree.of(" + label + ",\n" + + indent + "List.of(\n" + + String.join(",\n", chList) + "))"; + } + return "Tree.of(" + label + ")"; + } + }; + + lines.add("Tree tree = " + formatPovTree.apply(treeNode, 0) + ";"); + + boolean isError = (c.expected().isObject() && c.expected().has("error")) || c.expected().isNull(); + if (prop.equals("fromPov")) { + String from = "\"" + JavaTypeFormatter.escapeJavaString(c.input().path("from").asText()) + "\""; + if (isError) { + lines.add("assertThatExceptionOfType(UnsupportedOperationException.class)"); + lines.add(" .isThrownBy(() -> tree.fromPov(" + from + "))"); + lines.add(" .withMessage(\"Tree could not be reoriented\");"); + } else { + lines.add("Tree expected = " + formatPovTree.apply(c.expected(), 0) + ";"); + lines.add("assertThat(tree.fromPov(" + from + ")).isEqualTo(expected);"); + } + } else if (prop.equals("pathTo")) { + String from = "\"" + JavaTypeFormatter.escapeJavaString(c.input().path("from").asText()) + "\""; + String to = "\"" + JavaTypeFormatter.escapeJavaString(c.input().path("to").asText()) + "\""; + if (isError) { + lines.add("assertThatExceptionOfType(UnsupportedOperationException.class)"); + lines.add(" .isThrownBy(() -> tree.pathTo(" + from + ", " + to + "))"); + lines.add(" .withMessage(\"No path found\");"); + } else { + java.util.List pathItems = new java.util.ArrayList<>(); + if (c.expected().isArray()) { + for (JsonNode p : c.expected()) { + pathItems.add("\"" + JavaTypeFormatter.escapeJavaString(p.asText()) + "\""); + } + } + lines.add("List expected = List.of(" + String.join(", ", pathItems) + ");"); + lines.add("assertThat(tree.pathTo(" + from + ", " + to + ")).isEqualTo(expected);"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderRationalCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String prop = c.property(); + JsonNode input = c.input(); + JsonNode exp = c.expected(); + java.util.List lines = new java.util.ArrayList<>(); + + switch (prop) { + case "add", "sub", "mul", "div" -> { + JsonNode r1 = input.path("r1"); + JsonNode r2 = input.path("r2"); + String opMethod = switch (prop) { + case "add" -> "add"; + case "sub" -> "subtract"; + case "mul" -> "multiply"; + case "div" -> "divide"; + default -> prop; + }; + lines.add("Rational expected = new Rational(" + exp.get(0).asInt() + ", " + + exp.get(1).asInt() + ");"); + lines.add("Rational actual = new Rational(" + r1.get(0).asInt() + ", " + r1.get(1).asInt() + ")"); + lines.add(" ." + opMethod + "(new Rational(" + r2.get(0).asInt() + ", " + + r2.get(1).asInt() + "));"); + lines.add("assertThat(actual).isEqualTo(expected);"); + } + case "abs" -> { + JsonNode r = input.path("r"); + lines.add("Rational expected = new Rational(" + exp.get(0).asInt() + ", " + + exp.get(1).asInt() + ");"); + lines.add("Rational actual = new Rational(" + r.get(0).asInt() + ", " + + r.get(1).asInt() + ").abs();"); + lines.add("assertThat(actual).isEqualTo(expected);"); + } + case "exprational" -> { + JsonNode r = input.path("r"); + int n = input.path("n").asInt(); + lines.add("Rational expected = new Rational(" + exp.get(0).asInt() + ", " + + exp.get(1).asInt() + ");"); + lines.add("Rational actual = new Rational(" + r.get(0).asInt() + ", " + + r.get(1).asInt() + ").pow(" + n + ");"); + lines.add("assertThat(actual).isEqualTo(expected);"); + } + case "expreal" -> { + JsonNode r = input.path("r"); + double x = input.path("x").asDouble(); + String xStr = (x == (long) x) ? String.format(java.util.Locale.ROOT, "%.1f", x) + : String.valueOf(x); + double expD = exp.asDouble(); + String expStr; + if (Math.abs(expD - 1.0 / 3) < 1e-6) { + expStr = "1.0 / 3"; + } else if (expD == (long) expD) { + expStr = String.format(java.util.Locale.ROOT, "%.1f", expD); + } else { + expStr = String.valueOf(expD); + } + lines.add("double expected = " + expStr + ";"); + lines.add("double actual = new Rational(" + r.get(0).asInt() + ", " + + r.get(1).asInt() + ").exp(" + xStr + ");"); + lines.add("assertDoublesEqual(expected, actual);"); + } + case "reduce" -> { + JsonNode r = input.path("r"); + lines.add("Rational expected = new Rational(" + exp.get(0).asInt() + ", " + + exp.get(1).asInt() + ");"); + lines.add("Rational actual = new Rational(" + r.get(0).asInt() + ", " + + r.get(1).asInt() + ");"); + lines.add("assertThat(actual).isEqualTo(expected);"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderRectanglesCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode linesNode = c.input().has("strings") ? c.input().path("strings") : c.input().path("lines"); + java.util.List rows = new java.util.ArrayList<>(); + if (linesNode.isArray()) { + for (JsonNode row : linesNode) { + rows.add("\"" + JavaTypeFormatter.escapeJavaString(row.asText()) + "\""); + } + } + java.util.List lines = new java.util.ArrayList<>(); + if (rows.isEmpty()) { + lines.add("assertThat(new RectangleCounter().countRectangles(new String[]{}))"); + lines.add(" .isEqualTo(" + c.expected().asInt() + ");"); + } else { + lines.add("String[] grid = new String[]{"); + for (int i = 0; i < rows.size(); i++) { + lines.add(" " + rows.get(i) + (i < rows.size() - 1 ? "," : "")); + } + lines.add("};"); + lines.add("assertThat(new RectangleCounter().countRectangles(grid))"); + lines.add(" .isEqualTo(" + c.expected().asInt() + ");"); + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderSimpleCipherCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode input = c.input(); + JsonNode expected = c.expected(); + String prop = c.property(); + + java.util.List lines = new java.util.ArrayList<>(); + boolean isRandom = !input.has("key"); + + if (isRandom) { + if (expected.isObject() && expected.has("match")) { + lines.add("assertThat(randomKeyCipher.getKey()).matches(\"" + + JavaTypeFormatter.escapeJavaString(expected.get("match").asText()) + "\");"); + } else if ("encode".equals(prop)) { + String plain = input.path("plaintext").asText(); + lines.add("String plainText = \"" + JavaTypeFormatter.escapeJavaString(plain) + "\";"); + lines.add("String cipherText = randomKeyCipher.getKey().substring(0, " + plain.length() + ");"); + lines.add("assertThat(randomKeyCipher.encode(plainText)).isEqualTo(cipherText);"); + } else if ("decode".equals(prop)) { + if ("cipher.encode".equals(input.path("ciphertext").asText())) { + String plain = input.path("plaintext").asText(); + lines.add("String plainText = \"" + JavaTypeFormatter.escapeJavaString(plain) + "\";"); + lines.add("assertThat(randomKeyCipher.decode(randomKeyCipher.encode(plainText)))"); + lines.add(" .isEqualTo(plainText);"); + } else { + String exp = expected.asText(); + lines.add("String cipherText = \"" + JavaTypeFormatter.escapeJavaString(exp) + "\";"); + lines.add("assertThat(randomKeyCipher.decode(randomKeyCipher.getKey().substring(0, " + exp.length() + ")))"); + lines.add(" .isEqualTo(cipherText);"); + } + } + } else { + String key = input.path("key").asText(); + boolean useDefaultKey = "abcdefghij".equals(key); + String cipherExpr = useDefaultKey ? "substitutionCipher" : ("new Cipher(\"" + JavaTypeFormatter.escapeJavaString(key) + "\")"); + + if ("cipher.encode".equals(input.path("ciphertext").asText())) { + String plain = input.path("plaintext").asText(); + lines.add("String plainText = \"" + JavaTypeFormatter.escapeJavaString(plain) + "\";"); + lines.add("assertThat(" + cipherExpr + ".decode(" + cipherExpr + ".encode(plainText)))"); + lines.add(" .isEqualTo(plainText);"); + } else if ("encode".equals(prop)) { + String plain = input.path("plaintext").asText(); + lines.add("String plainText = \"" + JavaTypeFormatter.escapeJavaString(plain) + "\";"); + lines.add("assertThat(" + cipherExpr + ".encode(plainText)).isEqualTo(\"" + + JavaTypeFormatter.escapeJavaString(expected.asText()) + "\");"); + } else if ("decode".equals(prop)) { + String cipherText = input.path("ciphertext").asText(); + lines.add("String plainText = \"" + JavaTypeFormatter.escapeJavaString(expected.asText()) + "\";"); + lines.add("assertThat(" + cipherExpr + ".decode(\"" + JavaTypeFormatter.escapeJavaString(cipherText) + "\"))"); + lines.add(" .isEqualTo(plainText);"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderForthCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + java.util.List lines = new java.util.ArrayList<>(); + + if ("evaluateBoth".equals(c.property())) { + JsonNode firstInstrs = c.input().path("instructionsFirst"); + JsonNode secondInstrs = c.input().path("instructionsSecond"); + java.util.List firstList = new java.util.ArrayList<>(); + java.util.List secondList = new java.util.ArrayList<>(); + if (firstInstrs.isArray()) { + for (JsonNode in : firstInstrs) { + firstList.add("\"" + JavaTypeFormatter.escapeJavaString(in.asText()) + "\""); + } + } + if (secondInstrs.isArray()) { + for (JsonNode in : secondInstrs) { + secondList.add("\"" + JavaTypeFormatter.escapeJavaString(in.asText()) + "\""); + } + } + java.util.List expFirst = new java.util.ArrayList<>(); + java.util.List expSecond = new java.util.ArrayList<>(); + if (c.expected().isArray() && c.expected().size() >= 2) { + for (JsonNode in : c.expected().get(0)) { + expFirst.add(String.valueOf(in.asInt())); + } + for (JsonNode in : c.expected().get(1)) { + expSecond.add(String.valueOf(in.asInt())); + } + } + lines.add("ForthEvaluator firstInstance = new ForthEvaluator();"); + lines.add("ForthEvaluator secondInstance = new ForthEvaluator();"); + lines.add(""); + lines.add("assertThat(firstInstance.evaluateProgram(List.of(" + String.join(", ", firstList) + ")))"); + lines.add(" .containsExactly(" + String.join(", ", expFirst) + ");"); + lines.add("assertThat(secondInstance.evaluateProgram(List.of(" + String.join(", ", secondList) + ")))"); + lines.add(" .containsExactly(" + String.join(", ", expSecond) + ");"); + return String.join("\n ", lines); + } + + JsonNode instrs = c.input().path("instructions"); + java.util.List instrList = new java.util.ArrayList<>(); + if (instrs.isArray()) { + for (JsonNode in : instrs) { + instrList.add("\"" + JavaTypeFormatter.escapeJavaString(in.asText()) + "\""); + } + } + String instrExpr = "List.of(" + String.join(", ", instrList) + ")"; + + if (c.expected().isObject() && c.expected().has("error")) { + String err = c.expected().path("error").asText(); + String msg; + if (err.contains("zero") || instrList.stream().anyMatch(s -> s.contains("/ 0"))) { + msg = "Division by 0 is not allowed"; + } else if (err.contains("illegal") || instrList.stream().anyMatch(s -> s.matches("\".*:\\s*-?\\d+.*\""))) { + msg = "Cannot redefine numbers"; + } else if (instrList.stream().anyMatch(s -> s.contains("dup"))) { + msg = "Duplicating requires that the stack contain at least 1 value"; + } else if (instrList.stream().anyMatch(s -> s.contains("drop"))) { + msg = "Dropping requires that the stack contain at least 1 value"; + } else if (instrList.stream().anyMatch(s -> s.contains("swap"))) { + msg = "Swapping requires that the stack contain at least 2 values"; + } else if (instrList.stream().anyMatch(s -> s.contains("over"))) { + msg = "Overing requires that the stack contain at least 2 values"; + } else if (instrList.stream().anyMatch(s -> s.contains("+"))) { + msg = "Addition requires that the stack contain at least 2 values"; + } else if (instrList.stream().anyMatch(s -> s.contains("-"))) { + msg = "Subtraction requires that the stack contain at least 2 values"; + } else if (instrList.stream().anyMatch(s -> s.contains("*"))) { + msg = "Multiplication requires that the stack contain at least 2 values"; + } else if (instrList.stream().anyMatch(s -> s.contains("/"))) { + msg = "Division requires that the stack contain at least 2 values"; + } else { + msg = "No definition available for operator \\\"foo\\\""; + } + lines.add("assertThatExceptionOfType(IllegalArgumentException.class)"); + lines.add(" .isThrownBy(() -> forthEvaluator.evaluateProgram(" + instrExpr + "))"); + lines.add(" .withMessage(\"" + msg + "\");"); + } else { + java.util.List expInts = new java.util.ArrayList<>(); + if (c.expected().isArray()) { + for (JsonNode in : c.expected()) { + expInts.add(String.valueOf(in.asInt())); + } + } + lines.add("assertThat(forthEvaluator.evaluateProgram(" + instrExpr + "))"); + lines.add(" .containsExactly(" + String.join(", ", expInts) + ");"); + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderPythagoreanCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + int n = c.input().path("n").asInt(); + JsonNode maxFactorNode = c.input().path("maxFactor"); + java.util.List lines = new java.util.ArrayList<>(); + + lines.add("List actual = PythagoreanTriplet"); + lines.add(" .makeTripletsList()"); + lines.add(" .thatSumTo(" + n + ")"); + if (maxFactorNode.isNumber()) { + lines.add(" .withFactorsLessThanOrEqualTo(" + maxFactorNode.asInt() + ")"); + } + lines.add(" .build();"); + + JsonNode expTriplets = c.expected(); + java.util.List triplets = new java.util.ArrayList<>(); + if (expTriplets.isArray()) { + for (JsonNode tr : expTriplets) { + triplets.add("new PythagoreanTriplet(" + tr.get(0).asInt() + ", " + + tr.get(1).asInt() + ", " + tr.get(2).asInt() + ")"); + } + } + if (triplets.isEmpty()) { + lines.add("List expected = List.of();"); + } else if (triplets.size() == 1) { + lines.add("List expected = List.of(" + triplets.get(0) + ");"); + } else { + lines.add("List expected = List.of("); + for (int i = 0; i < triplets.size(); i++) { + lines.add(" " + triplets.get(i) + (i < triplets.size() - 1 ? "," : "")); + } + lines.add(");"); + } + lines.add("assertThat(actual).isEqualTo(expected);"); + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderCustomSetCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + String prop = c.property(); + JsonNode input = c.input(); + JsonNode exp = c.expected(); + java.util.List lines = new java.util.ArrayList<>(); + + java.util.function.Function formatSet = node -> { + if (node == null || !node.isArray() || node.isEmpty()) { + return "new CustomSet<>(List.of())"; + } + java.util.List items = new java.util.ArrayList<>(); + for (JsonNode el : node) { + items.add(String.valueOf(el.asInt())); + } + return "new CustomSet<>(List.of(" + String.join(", ", items) + "))"; + }; + + switch (prop) { + case "empty" -> { + lines.add("CustomSet customSet = " + formatSet.apply(input.path("set")) + ";"); + lines.add("assertThat(customSet.isEmpty())." + (exp.asBoolean() ? "isTrue" : "isFalse") + "();"); + } + case "contains" -> { + lines.add("CustomSet customSet = " + formatSet.apply(input.path("set")) + ";"); + int element = input.path("element").asInt(); + lines.add("assertThat(customSet.contains(" + element + "))." + + (exp.asBoolean() ? "isTrue" : "isFalse") + "();"); + } + case "subset" -> { + lines.add("CustomSet customSet1 = " + formatSet.apply(input.path("set1")) + ";"); + lines.add("CustomSet customSet2 = " + formatSet.apply(input.path("set2")) + ";"); + lines.add("assertThat(customSet2.isSubset(customSet1))." + + (exp.asBoolean() ? "isTrue" : "isFalse") + "();"); + } + case "disjoint" -> { + lines.add("CustomSet customSet1 = " + formatSet.apply(input.path("set1")) + ";"); + lines.add("CustomSet customSet2 = " + formatSet.apply(input.path("set2")) + ";"); + lines.add("assertThat(customSet1.isDisjoint(customSet2))." + + (exp.asBoolean() ? "isTrue" : "isFalse") + "();"); + } + case "equal" -> { + lines.add("CustomSet customSet1 = " + formatSet.apply(input.path("set1")) + ";"); + lines.add("CustomSet customSet2 = " + formatSet.apply(input.path("set2")) + ";"); + lines.add("assertThat(customSet1.equals(customSet2))." + + (exp.asBoolean() ? "isTrue" : "isFalse") + "();"); + } + case "add" -> { + lines.add("CustomSet customSet = " + formatSet.apply(input.path("set")) + ";"); + int element = input.path("element").asInt(); + lines.add("customSet.add(" + element + ");"); + lines.add("CustomSet expected = " + formatSet.apply(exp) + ";"); + lines.add("assertThat(customSet.equals(expected)).isTrue();"); + } + case "intersection" -> { + lines.add("CustomSet customSet1 = " + formatSet.apply(input.path("set1")) + ";"); + lines.add("CustomSet customSet2 = " + formatSet.apply(input.path("set2")) + ";"); + lines.add("CustomSet actual = customSet1.getIntersection(customSet2);"); + lines.add("CustomSet expected = " + formatSet.apply(exp) + ";"); + lines.add("assertThat(actual.equals(expected)).isTrue();"); + } + case "difference" -> { + lines.add("CustomSet customSet1 = " + formatSet.apply(input.path("set1")) + ";"); + lines.add("CustomSet customSet2 = " + formatSet.apply(input.path("set2")) + ";"); + lines.add("CustomSet actual = customSet1.getDifference(customSet2);"); + lines.add("CustomSet expected = " + formatSet.apply(exp) + ";"); + lines.add("assertThat(actual.equals(expected)).isTrue();"); + } + case "union" -> { + lines.add("CustomSet customSet1 = " + formatSet.apply(input.path("set1")) + ";"); + lines.add("CustomSet customSet2 = " + formatSet.apply(input.path("set2")) + ";"); + lines.add("CustomSet actual = customSet1.getUnion(customSet2);"); + lines.add("CustomSet expected = " + formatSet.apply(exp) + ";"); + lines.add("assertThat(actual.equals(expected)).isTrue();"); + } + } + return String.join("\n ", lines); + }); + + handlebars.registerHelper("renderSatelliteCase", (context, options) -> { + CanonicalCase c = toCanonicalCase(context); + if (c == null) return ""; + JsonNode pre = c.input().path("preorder"); + JsonNode in = c.input().path("inorder"); + java.util.List preChars = new java.util.ArrayList<>(); + if (pre.isArray()) { + for (JsonNode ch : pre) { + preChars.add("'" + ch.asText() + "'"); + } + } + java.util.List inChars = new java.util.ArrayList<>(); + if (in.isArray()) { + for (JsonNode ch : in) { + inChars.add("'" + ch.asText() + "'"); + } + } + java.util.List lines = new java.util.ArrayList<>(); + lines.add("List preorder = List.of(" + String.join(", ", preChars) + ");"); + lines.add("List inorder = List.of(" + String.join(", ", inChars) + ");"); + lines.add(""); + + if (c.expected().isObject() && c.expected().has("error")) { + String error = c.expected().path("error").asText(); + lines.add("assertThatExceptionOfType(IllegalArgumentException.class)"); + lines.add(" .isThrownBy(() -> satellite.treeFromTraversals(preorder, inorder))"); + lines.add(" .withMessage(\"" + JavaTypeFormatter.escapeJavaString(error) + "\");"); + } else { + java.util.List postChars = new java.util.ArrayList<>(); + java.util.function.Consumer computePostorder = new java.util.function.Consumer<>() { + @Override + public void accept(JsonNode node) { + if (node == null || node.isNull() || node.isEmpty()) return; + accept(node.path("l")); + accept(node.path("r")); + postChars.add("'" + node.path("v").asText() + "'"); + } + }; + computePostorder.accept(c.expected()); + lines.add("Tree tree = satellite.treeFromTraversals(preorder, inorder);"); + lines.add(""); + lines.add("assertThat(tree.preorder()).containsExactlyElementsOf(preorder);"); + lines.add("assertThat(tree.inorder()).containsExactlyElementsOf(inorder);"); + if (postChars.isEmpty()) { + lines.add("assertThat(tree.postorder()).isEmpty();"); + } else { + lines.add("assertThat(tree.postorder()).containsExactly(" + String.join(", ", postChars) + ");"); + } + } + return String.join("\n ", lines); + }); + } + + private static exercism.testgenerator.model.CanonicalCase toCanonicalCase(Object context) { + if (context instanceof exercism.testgenerator.model.CanonicalCase c) return c; + if (context instanceof exercism.testgenerator.model.RenderedTestCase r) return r.rawCase(); + if (context instanceof JsonNode n) { + return new exercism.testgenerator.model.CanonicalCase( + n.path("uuid").asText(""), + n.path("description").asText(""), + n.path("property").asText(""), + n.path("input"), + n.path("expected"), + java.util.List.of(), + java.util.List.of() + ); + } + return null; + } + + private static String breakStringIntoChunks(String text, int indentSpaces) { + if (text.length() <= 80) { + return "\"" + JavaTypeFormatter.escapeJavaString(text) + "\""; + } + String indent = " ".repeat(indentSpaces); + StringBuilder sb = new StringBuilder(); + int start = 0; + boolean first = true; + while (start < text.length()) { + int end = Math.min(start + 70, text.length()); + if (end < text.length()) { + int lastSpace = text.lastIndexOf(' ', end); + if (lastSpace > start + 30) { + end = lastSpace + 1; + } + } + String chunk = text.substring(start, end); + if (!first) { + sb.append("\n").append(indent).append("+ "); + } + sb.append("\"").append(JavaTypeFormatter.escapeJavaString(chunk)).append("\""); + first = false; + start = end; + } + return sb.toString(); + } + + private static String formatPointSet(JsonNode pointsNode) { + if (pointsNode == null || !pointsNode.isArray() || pointsNode.isEmpty()) { + return "Set.of()"; + } + java.util.List pts = new java.util.ArrayList<>(); + for (JsonNode pt : pointsNode) { + pts.add("new Point(" + pt.get(0).asInt() + ", " + pt.get(1).asInt() + ")"); + } + return "Set.of(" + String.join(", ", pts) + ")"; + } + + private static String formatSgfNode(JsonNode node, int indent) { + if (node == null || node.isNull()) return "null"; + JsonNode props = node.path("properties"); + JsonNode children = node.path("children"); + + boolean hasProps = props.isObject() && !props.isEmpty(); + boolean hasChildren = children.isArray() && !children.isEmpty(); + + if (!hasProps && !hasChildren) { + return "new SgfNode()"; + } + + String propsExpr = formatSgfProperties(props); + if (!hasChildren) { + return "new SgfNode(" + propsExpr + ")"; + } + + java.util.List childExprs = new java.util.ArrayList<>(); + for (JsonNode child : children) { + childExprs.add(formatSgfNode(child, indent + 8)); + } + if (propsExpr.length() + String.join(", ", childExprs).length() > 50) { + String childrenList = "List.of(\n " + + String.join(",\n ", childExprs) + + "\n )"; + return "new SgfNode(\n " + propsExpr + ",\n " + childrenList + "\n )"; + } + String childrenExpr = "List.of(" + String.join(", ", childExprs) + ")"; + return "new SgfNode(" + propsExpr + ", " + childrenExpr + ")"; + } + + private static String formatSgfProperties(JsonNode props) { + if (props == null || !props.isObject() || props.isEmpty()) { + return "Map.of()"; + } + java.util.List entries = new java.util.ArrayList<>(); + props.fields().forEachRemaining(entry -> { + String key = "\"" + JavaTypeFormatter.escapeJavaString(entry.getKey()) + "\""; + java.util.List vals = new java.util.ArrayList<>(); + if (entry.getValue().isArray()) { + for (JsonNode v : entry.getValue()) { + vals.add("\"" + JavaTypeFormatter.escapeJavaString(v.asText()) + "\""); + } + } + entries.add(key + ", List.of(" + String.join(", ", vals) + ")"); + }); + if (entries.size() > 1) { + return "Map.of(\n " + String.join(",\n ", entries) + "\n )"; + } + return "Map.of(" + String.join(", ", entries) + ")"; + } + + private static void generateTreeAssertions(JsonNode node, String accessPath, java.util.List lines) { + int id = node.has("id") ? node.path("id").asInt() : node.path("recordId").asInt(); + JsonNode children = node.path("children"); + java.util.List childIds = new java.util.ArrayList<>(); + if (children.isArray() && !children.isEmpty()) { + for (JsonNode ch : children) { + int chId = ch.has("id") ? ch.path("id").asInt() : ch.path("recordId").asInt(); + childIds.add(String.valueOf(chId)); + } + } + if (childIds.isEmpty()) { + lines.add("assertNode(" + accessPath + ", " + id + ");"); + } else { + lines.add("assertNode(" + accessPath + ", " + id + ", " + String.join(", ", childIds) + ");"); + for (int i = 0; i < children.size(); i++) { + generateTreeAssertions(children.get(i), accessPath + ".getChildren().get(" + i + ")", lines); + } + } + } + + private static class DotNode { + final String name; + final java.util.Map attrs; + + DotNode(String name, java.util.Map attrs) { + this.name = name; + this.attrs = attrs; + } + } + + private static class DotEdge { + final String start; + final String end; + final java.util.Map attrs; + + DotEdge(String start, String end, java.util.Map attrs) { + this.start = start; + this.end = end; + this.attrs = attrs; + } + } + + private static void parseDotAttrs(String attrStr, java.util.Map target) { + java.util.regex.Pattern p = java.util.regex.Pattern.compile("([a-zA-Z0-9_]+)=(?:\"([^\"]*)\"|([^,\\s\\]]+))"); + java.util.regex.Matcher m = p.matcher(attrStr); + while (m.find()) { + String key = m.group(1); + String val = m.group(2) != null ? m.group(2) : m.group(3); + target.put(key, val); + } + } + + private static String formatDotMapOf(java.util.Map map) { + java.util.List entries = new java.util.ArrayList<>(); + for (var e : map.entrySet()) { + entries.add("\"" + e.getKey() + "\", \"" + JavaTypeFormatter.escapeJavaString(e.getValue()) + "\""); + } + return "Map.of(" + String.join(", ", entries) + ")"; + } + + private static String translateComputeFunction(String fn) { + String expr = fn.trim(); + if (expr.startsWith("if ") && expr.contains(" then ") && expr.contains(" else ")) { + int thenIdx = expr.indexOf(" then "); + int elseIdx = expr.indexOf(" else "); + String cond = expr.substring(3, thenIdx).trim(); + String thenPart = expr.substring(thenIdx + 6, elseIdx).trim(); + String elsePart = expr.substring(elseIdx + 6).trim(); + expr = cond + " ? " + thenPart + " : " + elsePart; + } + expr = expr.replaceAll("inputs\\[(\\d+)\\]", "list.get($1)"); + return "list -> " + expr; + } + + private static String jsonNodeToOrgJson(JsonNode node, int indent) { + String sp = " ".repeat(indent); + if (node.isObject()) { + if (node.isEmpty()) return "new JSONObject()"; + StringBuilder sb = new StringBuilder("new JSONObject()"); + var it = node.fields(); + while (it.hasNext()) { + var entry = it.next(); + String key = entry.getKey().equals("owed_by") ? "owedBy" : entry.getKey(); + sb.append("\n").append(sp).append(" .put(\"").append(key).append("\", "); + sb.append(jsonNodeToOrgJson(entry.getValue(), indent + 8)).append(")"); + } + return sb.toString(); + } else if (node.isArray()) { + if (node.isEmpty()) return "new JSONArray()"; + StringBuilder sb = new StringBuilder("new JSONArray()"); + for (JsonNode item : node) { + sb.append("\n").append(sp).append(" .put("); + sb.append(jsonNodeToOrgJson(item, indent + 8)).append(")"); + } + return sb.toString(); + } else if (node.isTextual()) { + return "\"" + JavaTypeFormatter.escapeJavaString(node.asText()) + "\""; + } else if (node.isDouble() || (node.isNumber() && (node.asText().contains(".") || indent > 0))) { + return String.format(java.util.Locale.US, "%.1f", node.asDouble()); + } else if (node.isIntegralNumber()) { + return node.asText(); + } else if (node.isBoolean()) { + return node.asBoolean() ? "true" : "false"; + } + return "null"; + } + + private static String buildZipperNavPath(JsonNode ops) { + if (ops == null || !ops.isArray()) return ""; + StringBuilder sb = new StringBuilder(); + for (JsonNode op : ops) { + sb.append(".").append(op.path("operation").asText()); + } + return sb.toString(); + } + + private static String formatZipperPrintTree(JsonNode node) { + if (node == null || node.isNull()) { + return "null"; + } + int val = node.path("value").asInt(); + JsonNode left = node.path("left"); + JsonNode right = node.path("right"); + boolean leftNull = left == null || left.isNull(); + boolean rightNull = right == null || right.isNull(); + + if (leftNull && rightNull) { + return "value: " + val + ", left: null, right: null"; + } else if (leftNull) { + return "value: " + val + ", left: null, right: { " + formatZipperPrintTree(right) + " }"; + } else if (rightNull) { + return "value: " + val + ", left: { " + formatZipperPrintTree(left) + " }, right: null"; + } else { + return "value: " + val + ", left: { " + formatZipperPrintTree(left) + " }, right: { " + formatZipperPrintTree(right) + " }"; + } + } + + private static String breakZipperString(String s) { + if (s == null) return "\"\""; + String res = "\"" + JavaTypeFormatter.escapeJavaString(s) + "\""; + if (res.length() <= 80) return res; + return res + .replace(", left: ", ", \" +\n \"left: ") + .replace(", right: ", ", \" +\n \"right: "); + } + + public String render(RenderedExercise exercise, Path exerciseDirectory) throws IOException { + Path customTemplatePath = exerciseDirectory.resolve(".meta").resolve("template.hbs"); + Template template; + + if (Files.exists(customTemplatePath)) { + String templateSource = Files.readString(customTemplatePath, StandardCharsets.UTF_8); + template = handlebars.compileInline(templateSource); + } else { + // Load default template from classpath + try (InputStream in = getClass().getResourceAsStream("/templates/default.hbs")) { + if (in == null) { + throw new IOException("Default template '/templates/default.hbs' not found on classpath"); + } + String defaultSource = new String(in.readAllBytes(), StandardCharsets.UTF_8); + template = handlebars.compileInline(defaultSource); + } + } + + Context context = Context.newBuilder(exercise) + .resolver( + JsonNodeValueResolver.INSTANCE, + MethodValueResolver.INSTANCE, + FieldValueResolver.INSTANCE, + JavaBeanValueResolver.INSTANCE, + MapValueResolver.INSTANCE + ) + .build(); + + String rawRendered = template.apply(context); + return cleanJavaFormatting(rawRendered); + } + + public static String cleanJavaFormatting(String javaCode) { + if (javaCode == null) return null; + String text = javaCode.replace("\r\n", "\n").replace("\r", "\n"); + String[] lines = text.split("\n", -1); + + for (int i = 0; i < lines.length; i++) { + lines[i] = lines[i].stripTrailing(); + } + + java.util.List result = new java.util.ArrayList<>(); + boolean prevWasAnnotation = false; + + for (int i = 0; i < lines.length; i++) { + String line = lines[i]; + String trimmed = line.trim(); + + if (trimmed.isEmpty()) { + if (prevWasAnnotation) { + int nextIdx = i + 1; + while (nextIdx < lines.length && lines[nextIdx].trim().isEmpty()) { + nextIdx++; + } + if (nextIdx < lines.length) { + String nextTrimmed = lines[nextIdx].trim(); + if (nextTrimmed.startsWith("@") || nextTrimmed.startsWith("public ") + || nextTrimmed.startsWith("void ") || nextTrimmed.startsWith("private ") + || nextTrimmed.startsWith("protected ") || nextTrimmed.startsWith("default ")) { + continue; + } + } + } + + if (!result.isEmpty() && result.get(result.size() - 1).isEmpty()) { + continue; + } + result.add(line); + prevWasAnnotation = false; + } else { + result.add(line); + prevWasAnnotation = trimmed.startsWith("@"); + } + } + + while (!result.isEmpty() && result.get(result.size() - 1).isEmpty()) { + result.remove(result.size() - 1); + } + return String.join("\n", result) + "\n"; + } +} diff --git a/test-generator/src/main/java/exercism/testgenerator/service/TestsTomlService.java b/test-generator/src/main/java/exercism/testgenerator/service/TestsTomlService.java new file mode 100644 index 000000000..c4da87886 --- /dev/null +++ b/test-generator/src/main/java/exercism/testgenerator/service/TestsTomlService.java @@ -0,0 +1,47 @@ +package exercism.testgenerator.service; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.dataformat.toml.TomlMapper; +import exercism.testgenerator.model.TestCaseConfig; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Collections; +import java.util.HashMap; +import java.util.Map; + +public class TestsTomlService { + + private final TomlMapper tomlMapper; + + public TestsTomlService() { + this.tomlMapper = new TomlMapper(); + } + + public Map parseTestsToml(Path tomlPath) throws IOException { + if (!Files.exists(tomlPath)) { + return Collections.emptyMap(); + } + return parseTestsToml(Files.readString(tomlPath)); + } + + public Map parseTestsToml(String tomlContent) throws IOException { + if (tomlContent == null || tomlContent.isBlank()) { + return Collections.emptyMap(); + } + return tomlMapper.readValue(tomlContent, new TypeReference>() {}); + } + + public boolean isCaseIncluded(Map configs, String uuid) { + if (configs == null || configs.isEmpty()) { + return true; + } + if (!configs.containsKey(uuid)) { + // If tests.toml exists and has entries, omitted UUIDs are unsynced/unimplemented + return false; + } + TestCaseConfig config = configs.get(uuid); + return config == null || config.isIncluded(); + } +} diff --git a/test-generator/src/main/resources/templates/default.hbs b/test-generator/src/main/resources/templates/default.hbs new file mode 100644 index 000000000..530d1439f --- /dev/null +++ b/test-generator/src/main/resources/templates/default.hbs @@ -0,0 +1,37 @@ +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +{{#if hasCollections}} + +{{#if hasList}} +import java.util.List; +{{/if}} +{{#if hasMap}} +import java.util.Map; +{{/if}} +{{#if hasSet}} +import java.util.Set; +{{/if}} +{{/if}} + +import static org.assertj.core.api.Assertions.assertThat; +{{#if hasExceptions}} +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; +{{/if}} +{{#if hasFloatingPoint}} +import static org.assertj.core.api.Assertions.offset; +{{/if}} + +public class {{testClassName}} { +{{#each testCases}} + + {{#if disabled~}} + @Disabled("Remove to run test") + {{/if~}} + @Test + {{{displayNameAnnotation}}} + public void {{methodName}}() { + {{{assertionCode}}} + } +{{/each}} +} diff --git a/test-generator/src/test/java/exercism/testgenerator/CaseFlattenerTest.java b/test-generator/src/test/java/exercism/testgenerator/CaseFlattenerTest.java new file mode 100644 index 000000000..e641aebaa --- /dev/null +++ b/test-generator/src/test/java/exercism/testgenerator/CaseFlattenerTest.java @@ -0,0 +1,55 @@ +package exercism.testgenerator; + +import com.fasterxml.jackson.databind.ObjectMapper; +import exercism.testgenerator.model.CanonicalCase; +import exercism.testgenerator.model.CanonicalData; +import exercism.testgenerator.service.CaseFlattener; +import java.util.List; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class CaseFlattenerTest { + + private final ObjectMapper mapper = new ObjectMapper(); + private final CaseFlattener flattener = new CaseFlattener(mapper); + + @Test + void flattensNestedCanonicalCases() throws Exception { + String json = """ + { + "exercise": "example", + "cases": [ + { + "uuid": "case-1", + "description": "top level test", + "property": "solve", + "input": {"x": 1}, + "expected": 2 + }, + { + "description": "grouped tests", + "cases": [ + { + "uuid": "case-2", + "description": "nested test", + "property": "solve", + "input": {"x": 2}, + "expected": 4 + } + ] + } + ] + } + """; + + CanonicalData data = mapper.readValue(json, CanonicalData.class); + List cases = flattener.flatten(data.cases()); + + assertThat(cases).hasSize(2); + assertThat(cases.get(0).uuid()).isEqualTo("case-1"); + assertThat(cases.get(0).description()).isEqualTo("top level test"); + assertThat(cases.get(1).uuid()).isEqualTo("case-2"); + assertThat(cases.get(1).description()).isEqualTo("grouped tests -> nested test"); + } +} diff --git a/test-generator/src/test/java/exercism/testgenerator/JavaNamingHelperTest.java b/test-generator/src/test/java/exercism/testgenerator/JavaNamingHelperTest.java new file mode 100644 index 000000000..aed44e33f --- /dev/null +++ b/test-generator/src/test/java/exercism/testgenerator/JavaNamingHelperTest.java @@ -0,0 +1,51 @@ +package exercism.testgenerator; + +import exercism.testgenerator.service.JavaNamingHelper; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class JavaNamingHelperTest { + + @Test + void convertsSimpleDescriptionToCamelCase() { + assertThat(JavaNamingHelper.toMethodName("basic")) + .isEqualTo("basic"); + assertThat(JavaNamingHelper.toMethodName("lowercase words")) + .isEqualTo("lowercaseWords"); + assertThat(JavaNamingHelper.toMethodName("all caps word")) + .isEqualTo("allCapsWord"); + } + + @Test + void handlesPunctuationAndSymbols() { + assertThat(JavaNamingHelper.toMethodName("punctuation without whitespace")) + .isEqualTo("punctuationWithoutWhitespace"); + assertThat(JavaNamingHelper.toMethodName("something - with dashes and spaces!")) + .isEqualTo("somethingWithDashesAndSpaces"); + } + + @Test + void handlesStartingWithDigits() { + assertThat(JavaNamingHelper.toMethodName("123 test")) + .isEqualTo("test123Test"); + } + + @Test + void prefixesJavaKeywords() { + assertThat(JavaNamingHelper.toMethodName("default")) + .isEqualTo("testDefault"); + assertThat(JavaNamingHelper.toMethodName("class")) + .isEqualTo("testClass"); + } + + @Test + void convertsSlugToPascalCase() { + assertThat(JavaNamingHelper.toPascalCase("acronym")) + .isEqualTo("Acronym"); + assertThat(JavaNamingHelper.toPascalCase("two-fer")) + .isEqualTo("TwoFer"); + assertThat(JavaNamingHelper.toPascalCase("difference-of-squares")) + .isEqualTo("DifferenceOfSquares"); + } +} diff --git a/test-generator/src/test/java/exercism/testgenerator/JavaTypeFormatterTest.java b/test-generator/src/test/java/exercism/testgenerator/JavaTypeFormatterTest.java new file mode 100644 index 000000000..850ce8cdb --- /dev/null +++ b/test-generator/src/test/java/exercism/testgenerator/JavaTypeFormatterTest.java @@ -0,0 +1,35 @@ +package exercism.testgenerator; + +import com.fasterxml.jackson.databind.ObjectMapper; +import exercism.testgenerator.service.JavaTypeFormatter; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class JavaTypeFormatterTest { + + private final ObjectMapper mapper = new ObjectMapper(); + + @Test + void formatsPrimitives() throws Exception { + assertThat(JavaTypeFormatter.format(mapper.readTree("null"))).isEqualTo("null"); + assertThat(JavaTypeFormatter.format(mapper.readTree("true"))).isEqualTo("true"); + assertThat(JavaTypeFormatter.format(mapper.readTree("false"))).isEqualTo("false"); + assertThat(JavaTypeFormatter.format(mapper.readTree("42"))).isEqualTo("42"); + assertThat(JavaTypeFormatter.format(mapper.readTree("9999999999"))).isEqualTo("9999999999L"); + } + + @Test + void formatsEscapedStrings() throws Exception { + assertThat(JavaTypeFormatter.format(mapper.readTree("\"hello\""))).isEqualTo("\"hello\""); + assertThat(JavaTypeFormatter.format(mapper.readTree("\"hello \\\"world\\\"\""))).isEqualTo("\"hello \\\"world\\\"\""); + assertThat(JavaTypeFormatter.format(mapper.readTree("\"line1\\nline2\""))).isEqualTo("\"line1\\nline2\""); + } + + @Test + void formatsArrays() throws Exception { + assertThat(JavaTypeFormatter.format(mapper.readTree("[]"))).isEqualTo("List.of()"); + assertThat(JavaTypeFormatter.format(mapper.readTree("[\"a\", \"b\"]"))).isEqualTo("List.of(\"a\", \"b\")"); + assertThat(JavaTypeFormatter.format(mapper.readTree("[1, 2, 3]"))).isEqualTo("List.of(1, 2, 3)"); + } +} diff --git a/test-generator/src/test/java/exercism/testgenerator/TemplateRendererTest.java b/test-generator/src/test/java/exercism/testgenerator/TemplateRendererTest.java new file mode 100644 index 000000000..cf651b381 --- /dev/null +++ b/test-generator/src/test/java/exercism/testgenerator/TemplateRendererTest.java @@ -0,0 +1,59 @@ +package exercism.testgenerator; + +import exercism.testgenerator.service.TemplateRenderer; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class TemplateRendererTest { + + @Test + @DisplayName("cleans up blank lines between annotations and trailing whitespace") + void testCleanJavaFormattingRemovesBlankLinesBetweenAnnotations() { + String input = """ + public class ExampleTest { + + + @Test + @DisplayName("first test") + public void testOne() { + assertThat(true).isTrue(); + } + + + @Disabled("Remove to run test") + + @Test + @DisplayName("second test") + public void testTwo() { + assertThat(true).isTrue(); + } + + } + """; + + String cleaned = TemplateRenderer.cleanJavaFormatting(input); + + String expected = """ + public class ExampleTest { + + @Test + @DisplayName("first test") + public void testOne() { + assertThat(true).isTrue(); + } + + @Disabled("Remove to run test") + @Test + @DisplayName("second test") + public void testTwo() { + assertThat(true).isTrue(); + } + + } + """; + + assertThat(cleaned).isEqualTo(expected); + } +} diff --git a/test-generator/src/test/java/exercism/testgenerator/TestsTomlServiceTest.java b/test-generator/src/test/java/exercism/testgenerator/TestsTomlServiceTest.java new file mode 100644 index 000000000..ac4e55222 --- /dev/null +++ b/test-generator/src/test/java/exercism/testgenerator/TestsTomlServiceTest.java @@ -0,0 +1,35 @@ +package exercism.testgenerator; + +import exercism.testgenerator.model.TestCaseConfig; +import exercism.testgenerator.service.TestsTomlService; +import java.util.Collections; +import java.util.Map; +import org.junit.jupiter.api.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +class TestsTomlServiceTest { + + private final TestsTomlService service = new TestsTomlService(); + + @Test + void parsesTestsTomlWithIncludesAndExcludes() throws Exception { + String toml = """ + [1e22cceb-c5e4-4562-9afe-aef07ad1eaf4] + description = "basic" + + [b3cca662-f50a-489e-ae10-ab8290a09bdc] + description = "detects two anagrams" + include = false + comment = "not supported" + """; + + Map result = service.parseTestsToml(toml); + + assertThat(result).hasSize(2); + assertThat(service.isCaseIncluded(result, "1e22cceb-c5e4-4562-9afe-aef07ad1eaf4")).isTrue(); + assertThat(service.isCaseIncluded(result, "b3cca662-f50a-489e-ae10-ab8290a09bdc")).isFalse(); + assertThat(service.isCaseIncluded(result, "unknown-uuid")).isFalse(); // omitted from tests.toml implies excluded + assertThat(service.isCaseIncluded(Collections.emptyMap(), "unknown-uuid")).isTrue(); // empty/no tests.toml implies included + } +}