diff --git a/exercises/practice/list-ops/ListOpsTest.php b/exercises/practice/list-ops/ListOpsTest.php index c29e7ceb9..a899e71bf 100644 --- a/exercises/practice/list-ops/ListOpsTest.php +++ b/exercises/practice/list-ops/ListOpsTest.php @@ -12,6 +12,7 @@ public static function setUpBeforeClass(): void require_once 'ListOps.php'; } + /** * uuid 485b9452-bf94-40f7-a3db-c3cf4850066a */ @@ -19,7 +20,12 @@ public static function setUpBeforeClass(): void public function testAppendEmptyLists() { $listOps = new ListOps(); - $this->assertEquals([], $listOps->append([], [])); + $list1 = []; + $list2 = []; + + $result = $listOps->append($list1, $list2); + + $this->assertEquals([], $result); } /** @@ -29,7 +35,12 @@ public function testAppendEmptyLists() public function testAppendNonEmptyListToEmptyList() { $listOps = new ListOps(); - $this->assertEquals([1, 2, 3, 4], $listOps->append([1, 2, 3, 4], [])); + $list1 = []; + $list2 = [1, 2, 3, 4]; + + $result = $listOps->append($list1, $list2); + + $this->assertEquals([1, 2, 3, 4], $result); } /** @@ -39,7 +50,12 @@ public function testAppendNonEmptyListToEmptyList() public function testAppendEmptyListToNonEmptyList() { $listOps = new ListOps(); - $this->assertEquals([1, 2, 3, 4], $listOps->append([], [1, 2, 3, 4])); + $list1 = [1, 2, 3, 4]; + $list2 = []; + + $result = $listOps->append($list1, $list2); + + $this->assertEquals([1, 2, 3, 4], $result); } /** @@ -49,7 +65,12 @@ public function testAppendEmptyListToNonEmptyList() public function testAppendNonEmptyLists() { $listOps = new ListOps(); - $this->assertEquals([1, 2, 2, 3, 4, 5], $listOps->append([1, 2], [2, 3, 4, 5])); + $list1 = [1, 2]; + $list2 = [2, 3, 4, 5]; + + $result = $listOps->append($list1, $list2); + + $this->assertEquals([1, 2, 2, 3, 4, 5], $result); } /** @@ -59,7 +80,11 @@ public function testAppendNonEmptyLists() public function testConcatEmptyLists() { $listOps = new ListOps(); - $this->assertEquals([], $listOps->concat([], [])); + $lists = []; + + $result = $listOps->concat($lists); + + $this->assertEquals([], $result); } /** @@ -69,7 +94,11 @@ public function testConcatEmptyLists() public function testConcatLists() { $listOps = new ListOps(); - $this->assertEquals([1, 2, 3, 4, 5, 6], $listOps->concat([1, 2], [3], [], [4, 5, 6])); + $lists = [[1, 2], [3], [], [4, 5, 6]]; + + $result = $listOps->concat($lists); + + $this->assertEquals([1, 2, 3, 4, 5, 6], $result); } /** @@ -79,7 +108,11 @@ public function testConcatLists() public function testConcatNestedLists() { $listOps = new ListOps(); - $this->assertEquals([[1], [2], [3], [], [4, 5, 6]], $listOps->concat([[1], [2]], [[3]], [[]], [[4, 5, 6]])); + $lists = [[[1], [2]], [[3]], [[]], [[4, 5, 6]]]; + + $result = $listOps->concat($lists); + + $this->assertEquals([[1], [2], [3], [], [4, 5, 6]], $result); } /** @@ -89,10 +122,12 @@ public function testConcatNestedLists() public function testFilterEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - [], - $listOps->filter(static fn ($el) => $el % 2 === 1, []) - ); + $list = []; + $function = static fn ($el) => $el % 2 === 1; + + $result = $listOps->filter($list, $function); + + $this->assertEquals([], $result); } /** @@ -102,10 +137,12 @@ public function testFilterEmptyList() public function testFilterNonEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - [1, 3, 5], - $listOps->filter(static fn ($el) => $el % 2 === 1, [1, 2, 3, 5]) - ); + $list = [1, 2, 3, 5]; + $function = static fn ($el) => $el % 2 === 1; + + $result = $listOps->filter($list, $function); + + $this->assertEquals([1, 3, 5], $result); } /** @@ -115,7 +152,11 @@ public function testFilterNonEmptyList() public function testLengthEmptyList() { $listOps = new ListOps(); - $this->assertEquals(0, $listOps->length([])); + $list = []; + + $result = $listOps->length($list); + + $this->assertEquals(0, $result); } /** @@ -125,7 +166,11 @@ public function testLengthEmptyList() public function testLengthNonEmptyList() { $listOps = new ListOps(); - $this->assertEquals(4, $listOps->length([1, 2, 3, 4])); + $list = [1, 2, 3, 4]; + + $result = $listOps->length($list); + + $this->assertEquals(4, $result); } /** @@ -135,10 +180,12 @@ public function testLengthNonEmptyList() public function testMapEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - [], - $listOps->map(static fn ($el) => $el + 1, []) - ); + $list = []; + $function = static fn ($el) => $el + 1; + + $result = $listOps->map($list, $function); + + $this->assertEquals([], $result); } /** @@ -148,10 +195,12 @@ public function testMapEmptyList() public function testMapNonEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - [2, 4, 6, 8], - $listOps->map(static fn ($el) => $el + 1, [1, 3, 5, 7]) - ); + $list = [1, 3, 5, 7]; + $function = static fn ($el) => $el + 1; + + $result = $listOps->map($list, $function); + + $this->assertEquals([2, 4, 6, 8], $result); } /** @@ -161,10 +210,13 @@ public function testMapNonEmptyList() public function testFoldlEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - 2, - $listOps->foldl(static fn ($acc, $el) => $el * $acc, [], 2) - ); + $list = []; + $initial = 2; + $function = static fn ($acc, $el) => $el * $acc; + + $result = $listOps->foldl($list, $initial, $function); + + $this->assertEquals(2, $result); } /** @@ -174,10 +226,13 @@ public function testFoldlEmptyList() public function testFoldlDirectionIndependentNonEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - 15, - $listOps->foldl(static fn ($acc, $el) => $acc + $el, [1, 2, 3, 4], 5) - ); + $list = [1, 2, 3, 4]; + $initial = 5; + $function = static fn ($acc, $el) => $el + $acc; + + $result = $listOps->foldl($list, $initial, $function); + + $this->assertEquals(15, $result); } /** @@ -187,10 +242,13 @@ public function testFoldlDirectionIndependentNonEmptyList() public function testFoldlDirectionDependentNonEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - 64, - $listOps->foldl(static fn ($acc, $el) => $el / $acc, [1, 2, 3, 4], 24) - ); + $list = [1, 2, 3, 4]; + $initial = 24; + $function = static fn ($acc, $el) => $el / $acc; + + $result = $listOps->foldl($list, $initial, $function); + + $this->assertEquals(64, $result); } /** @@ -200,10 +258,13 @@ public function testFoldlDirectionDependentNonEmptyList() public function testFoldrEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - 2, - $listOps->foldr(static fn ($acc, $el) => $el * $acc, [], 2) - ); + $list = []; + $initial = 2; + $function = static fn ($acc, $el) => $el * $acc; + + $result = $listOps->foldr($list, $initial, $function); + + $this->assertEquals(2, $result); } /** @@ -213,10 +274,13 @@ public function testFoldrEmptyList() public function testFoldrDirectionIndependentNonEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - 15, - $listOps->foldr(static fn ($acc, $el) => $acc + $el, [1, 2, 3, 4], 5) - ); + $list = [1, 2, 3, 4]; + $initial = 5; + $function = static fn ($acc, $el) => $el + $acc; + + $result = $listOps->foldr($list, $initial, $function); + + $this->assertEquals(15, $result); } /** @@ -226,10 +290,13 @@ public function testFoldrDirectionIndependentNonEmptyList() public function testFoldrDirectionDependentNonEmptyList() { $listOps = new ListOps(); - $this->assertEquals( - 9, - $listOps->foldr(static fn ($acc, $el) => $el / $acc, [1, 2, 3, 4], 24) - ); + $list = [1, 2, 3, 4]; + $initial = 24; + $function = static fn ($acc, $el) => $el / $acc; + + $result = $listOps->foldr($list, $initial, $function); + + $this->assertEquals(9, $result); } /** @@ -269,6 +336,10 @@ public function testReverseNonEmptyOddLengthList() public function testReverseNonEmptyListIsNotFlattened() { $listOps = new ListOps(); - $this->assertEquals([[4, 5, 6], [], [3], [1, 2]], $listOps->reverse([[1, 2], [3], [], [4, 5, 6]])); + $list = [[1, 2], [3], [], [4, 5, 6]]; + + $result = $listOps->reverse($list); + + $this->assertEquals([[4, 5, 6], [], [3], [1, 2]], $result); } } diff --git a/exercises/practice/list-ops/ListOpsTest.php.twig b/exercises/practice/list-ops/ListOpsTest.php.twig new file mode 100644 index 000000000..056bf27df --- /dev/null +++ b/exercises/practice/list-ops/ListOpsTest.php.twig @@ -0,0 +1,65 @@ + x modulo 2 == 1': 'static fn ($el) => $el % 2 === 1', + '(x) -> x + 1': 'static fn ($el) => $el + 1', + '(acc, el) -> el * acc': 'static fn ($acc, $el) => $el * $acc', + '(acc, el) -> el + acc': 'static fn ($acc, $el) => $el + $acc', + '(acc, el) -> el / acc': 'static fn ($acc, $el) => $el / $acc', +} +-%} + +/* + * By adding type hints and enabling strict type checking, code can become + * easier to read, self-documenting and reduce the number of potential bugs. + * By default, type declarations are non-strict, which means they will attempt + * to change the original type to match the type specified by the + * type-declaration. + * + * In other words, if you pass a string to a function requiring a float, + * it will attempt to convert the string value to a float. + * + * To enable strict mode, a single declare directive must be placed at the top + * of the file. + * This means that the strictness of typing is configured on a per-file basis. + * This directive not only affects the type declarations of parameters, but also + * a function's return type. + * + * For more info review the Concept on strict type checking in the PHP track + * . + * + * To disable strict typing, comment out the directive below. + */ + +declare(strict_types=1); + +use PHPUnit\Framework\ExpectationFailedException; + +class ListOpsTest extends PHPUnit\Framework\TestCase +{ + public static function setUpBeforeClass(): void + { + require_once 'ListOps.php'; + } + + + {% for case0 in cases -%} + {% for case in case0.cases -%} + /** + * @testdox {{ case0.description }} -> {{ case.description }} + */ + public function {{ testfn(case0.description ~ ' with ' ~ case.description) }}() + { + $listOps = new ListOps(); + {% for property, value in case.input -%} + ${{ property }} = {{ property == 'function' ? callbacks[value] : export(value) }}; + {% endfor %} + + $result = $listOps->{{ case.property }}({{ case.input | keys | map(p => '$' ~ p) | join(', ')}}); + + $this->assertEquals({{ export(case.expected) }}, $result); + } + + {% endfor -%} + {% endfor -%} +} diff --git a/test-generator/.gitignore b/test-generator/.gitignore new file mode 100644 index 000000000..1940dfd2f --- /dev/null +++ b/test-generator/.gitignore @@ -0,0 +1,3 @@ +.phpunit.cache/ +.phpcs-cache +vendor/ diff --git a/test-generator/README.md b/test-generator/README.md new file mode 100644 index 000000000..dd1b0a357 --- /dev/null +++ b/test-generator/README.md @@ -0,0 +1,26 @@ +TODO: +- [ ] Readme + - [ ] Requirements (php 8.3) + - [ ] Usage `php test-generator/main.php exercises/practice/list-ops/ /home/codespace/.cache/exercism/configlet/problem-specifications/exercises/list-ops/canonical-data.json -vv` + - [ ] https://twig.symfony.com/ + - [ ] custom functions `export` / `testf` +- [ ] CI (generator) + - [ ] `phpstan` + - [ ] `phpcs` + - [ ] `phpunit` +- [ ] CI (exercises): iterate over each exercise and run the generator in check mode +- [ ] Write tests +- [ ] Path to convert existing exercises to the test-generator +- [ ] `@TODO` +- [ ] Upgrade https://github.com/brick/varexporter +- [ ] TOML Library for php (does not seem to exist any maitained library) +- [ ] Default templates: + - [ ] Test function header (automatic docblock, automatic name) +- [ ] Going further + - [ ] Skip re-implements + - [x] Read .meta/tests.toml to skip `include=false` cases by uuid + - [ ] Ensure correctness between toml and effectively generated files + - [ ] Default templates to include (strict_types header, require_once based on config, testfn header [testdox, uuid, task_id]) + - [ ] devcontainer for easy contribution in github codespace directly + - [ ] Automatically fetch configlet and exercise informations + - [x] Disable twig automatic isset diff --git a/test-generator/composer.json b/test-generator/composer.json new file mode 100644 index 000000000..b6a4ecb5d --- /dev/null +++ b/test-generator/composer.json @@ -0,0 +1,41 @@ +{ + "name": "exercism/test-generator", + "type": "project", + "require": { + "brick/varexporter": "^0.4.0", + "league/flysystem": "^3.26", + "league/flysystem-memory": "^3.25", + "psr/log": "^3.0", + "symfony/console": "^6.0", + "twig/twig": "^3.8" + }, + "require-dev": { + "doctrine/coding-standard": "^12.0", + "phpstan/phpstan": "^1.10", + "phpunit/phpunit": "^10.0", + "squizlabs/php_codesniffer": "^3.9" + }, + "license": "MIT", + "autoload": { + "psr-4": { + "App\\": "src/" + } + }, + "autoload-dev": { + "psr-4": { + "App\\Tests\\": "tests" + } + }, + "scripts": { + "phpstan": "phpstan analyse src tests --configuration phpstan.neon --memory-limit=2G", + "test": "phpunit", + "lint": "phpcs", + "lint:fix": "phpcbf" + }, + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + }, + "sort-packages": true + } +} diff --git a/test-generator/main.php b/test-generator/main.php new file mode 100644 index 000000000..a9a519e68 --- /dev/null +++ b/test-generator/main.php @@ -0,0 +1,8 @@ +run(); diff --git a/test-generator/phpcs.xml.dist b/test-generator/phpcs.xml.dist new file mode 100644 index 000000000..8a22e1cb3 --- /dev/null +++ b/test-generator/phpcs.xml.dist @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + src/ + tests/ + \ No newline at end of file diff --git a/test-generator/phpstan.neon b/test-generator/phpstan.neon new file mode 100644 index 000000000..22254bcd0 --- /dev/null +++ b/test-generator/phpstan.neon @@ -0,0 +1,2 @@ +parameters: + level: max diff --git a/test-generator/phpunit.xml.dist b/test-generator/phpunit.xml.dist new file mode 100644 index 000000000..1444de8ba --- /dev/null +++ b/test-generator/phpunit.xml.dist @@ -0,0 +1,24 @@ + + + + + ./tests + + + + + src/ + + + + + + + + + + \ No newline at end of file diff --git a/test-generator/src/Application.php b/test-generator/src/Application.php new file mode 100644 index 000000000..0fc9049e0 --- /dev/null +++ b/test-generator/src/Application.php @@ -0,0 +1,150 @@ +setVersion('1.0.0'); + // @TODO + $this->addArgument('exercise-path', InputArgument::REQUIRED, 'Path of the exercise.'); + $this->addArgument('canonical-data', InputArgument::REQUIRED, 'Path of the canonical data for the exercise. (Use `bin/configlet -verbosity info --offline`)'); + $this->addOption('check', null, InputOption::VALUE_NONE, 'Checks whether the existing files are the same as generated one.'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + $exercisePath = $input->getArgument('exercise-path'); + $canonicalPath = $input->getArgument('canonical-data'); + $exerciseCheck = $input->getOption('check'); + assert(is_string($exercisePath), 'exercise-path must be a string'); + assert(is_string($canonicalPath), 'canonical-data must be a string'); + assert(is_bool($exerciseCheck), 'check must be a bool'); + + $logger = new ConsoleLogger($output); + $logger->info('Exercise path: ' . $exercisePath); + $logger->info('canonical-data path: ' . $canonicalPath); + + $canonicalDataJson = file_get_contents($canonicalPath); + if ($canonicalDataJson === false) { + throw new RuntimeException('Faield to fetch canonical-data.json, check you `canonical-data` argument.'); + } + + $canonicalData = json_decode($canonicalDataJson, true, flags: JSON_THROW_ON_ERROR); + assert(is_array($canonicalData), 'json_decode(..., true) should return an array'); + $exerciseAdapter = new LocalFilesystemAdapter($exercisePath); + $exerciseFilesystem = new Filesystem($exerciseAdapter); + + $success = $this->generate($exerciseFilesystem, $exerciseCheck, $canonicalData, $logger); + + return $success ? self::SUCCESS : self::FAILURE; + } + + /** @param array $canonicalData */ + public function generate(Filesystem $exerciseDir, bool $check, array $canonicalData, LoggerInterface $logger): bool + { + // 1. Read config.json + $configJson = $exerciseDir->read('/.meta/config.json'); + $config = json_decode($configJson, true, flags: JSON_THROW_ON_ERROR); + assert(is_array($config), 'json_decode(..., true) should return an array'); + + if (! isset($config['files']['test']) || ! is_array($config['files']['test'])) { + throw new RuntimeException('.meta/config.json: missing or invalid `files.test` key'); + } + + $testsPaths = $config['files']['test']; + $logger->info('.meta/config.json: tests files: ' . implode(', ', $testsPaths)); + + if (empty($testsPaths)) { + $logger->warning('.meta/config.json: `files.test` key is empty'); + } + + // 2. Read test.toml + $testsToml = $exerciseDir->read('/.meta/tests.toml'); + $tests = TomlParser::parse($testsToml); + + // 3. Remove `include = false` tests + $excludedTests = array_filter($tests, static fn (array $props) => isset($props['include']) && $props['include'] === false); + $this->removeExcludedTests($excludedTests, $canonicalData['cases']); + + // 4. foreach tests files, check if there is a twig file + $twigLoader = new ArrayLoader(); + $twigEnvironment = new Environment($twigLoader, ['strict_variables' => true, 'autoescape' => false]); + $twigEnvironment->addFunction(new TwigFunction('export', static fn (mixed $value) => VarExporter::export($value, VarExporter::INLINE_ARRAY))); + $twigEnvironment->addFunction(new TwigFunction('testfn', static fn (string $label) => 'test' . str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9]/', ' ', $label))))); + foreach ($testsPaths as $testPath) { + // 5. generate the file + $twigFilename = $testPath . '.twig'; + // @TODO warning or error if it does not exist + $testTemplate = $exerciseDir->read($twigFilename); + $rendered = $twigEnvironment->createTemplate($testTemplate, $twigFilename)->render($canonicalData); + + if ($check) { + // 6. Compare it if check mode + if ($exerciseDir->read($testPath) !== $rendered) { + // return false; + throw new Exception('Differences between generated and existing file'); + } + } else { + $exerciseDir->write($testPath, $rendered); + } + } + + return true; + } + + private function removeExcludedTests(array $tests, array &$cases): void + { + foreach ($cases as $key => &$case) { + if (array_key_exists('cases', $case)) { + $this->removeExcludedTests($tests, $case['cases']); + } else { + assert(array_key_exists('uuid', $case)); + if (array_key_exists($case['uuid'], $tests)) { + unset($cases[$key]); + } + } + } + } +} diff --git a/test-generator/src/TomlParser.php b/test-generator/src/TomlParser.php new file mode 100644 index 000000000..1d88fc550 --- /dev/null +++ b/test-generator/src/TomlParser.php @@ -0,0 +1,79 @@ +write('.meta/config.json', '{"files":{"test":["test.php"]}}'); + $exerciseFs->write('.meta/tests.toml', ''); + $exerciseFs->write('test.php.twig', ' [1, 2], 'l' => 'this-Is_a test fn', 'cases' => []]; + + $application = new Application(); + $success = $application->generate($exerciseFs, false, $canonicalData, new NullLogger()); + + $this->assertTrue($success); + $this->assertSame('read('/test.php')); + } +}