"""task-bench's PHP planter: which files Infection mutates, how its log's diffs become mutants and what PHPUnit's output tells Haiku. PICK's diffs and FAILING are what Infection 0.35.12 and PHPUnit 12.5.45 wrote for a small project on PHP 8.5.13, and each logged mutant holds the keys the planter reads. The other diffs and outputs are made up in the same form.""" import json import pathlib import sys import tempfile import unittest sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1])) from task_bench.php_bugs import changed, killed_mutants, task_text from failure import Failure from task_bench.planted_mutant import Mutant, mutated from mutate_changes.tool_process import Ran PICK = """ $items */ public static function sum(array $items, int $floor): int { $sum = 0; foreach ($items as $item) { if ($item >= $floor) { $sum += $item; } } return $sum; } public static function label(int $count): string { return $count === 1 ? 'one item' : $count . ' items'; } } """ LINES = PICK.split("\n") OPERATOR_DIFF = "@@ @@\n \t{\n \t\t$sum = 0;\n \t\tforeach ($items as $item) {\n-\t\t\tif ($item >= $floor) {\n+\t\t\tif ($item > $floor) {\n \t\t\t\t$sum += $item;\n \t\t\t}\n \t\t}" # Infection prints the lines of a statement it rewrote with its own indent, and leaves the ones between them as they were. FOREACH_DIFF = ( "@@ @@\n \tpublic static function sum(array $items, int $floor): int\n \t{\n \t\t$sum = 0;\n-\t\tforeach ($items as $item) {\n-\t\t\tif ($item >= $floor) {\n" "+\t\tforeach ([] as $item) {\n+ if ($item >= $floor) {\n \t\t\t\t$sum += $item;\n \t\t\t}\n-\t\t}\n+ }\n \t\treturn $sum;\n \t}" ) TERNARY_DIFF = ( "@@ @@\n\n \tpublic static function label(int $count): string\n \t{\n-\t\treturn $count === 1\n-\t\t\t? 'one item'\n-\t\t\t: $count . ' items';\n" "+\t\treturn $count === 1 ? $count . ' items' : 'one item';\n \t}\n }" ) # An empty line of the file stands in the diff without the space that opens an unchanged line. VISIBILITY_DIFF = ( "@@ @@\n \t\treturn $sum;\n \t}\n\n-\tpublic static function label(int $count): string\n+\tprotected static function label(int $count): string\n" " \t{\n \t\treturn $count === 1\n \t\t\t? 'one item'" ) OPERATOR_NOW = (b"\t\t\tif ($item > $floor) {",) def logged(mutator: str, line: int, diff: str, path: str = "/w/src/Pick.php", source: str = PICK) -> dict: return {"mutator": {"mutatorName": mutator, "originalSourceCode": source, "originalFilePath": path, "originalStartLine": line}, "diff": diff} # Three failed tests. FAILING = """PHPUnit 12.5.45 by Sebastian Bergmann and contributors. Runtime: PHP 8.5.13 Configuration: /w/phpunit.xml FFF 3 / 3 (100%) Time: 00:00.002, Memory: 18.00 MB There were 3 failures: 1) Probe\\Tests\\PickTest::testAddsTheItemsAtOrAboveTheFloor Failed asserting that 3 is identical to 5. /w/tests/PickTest.php:12 2) Probe\\Tests\\PickTest::testNamesOne one is singular Failed asserting that two strings are identical. --- Expected +++ Actual @@ @@ -'one item' +'' /w/tests/PickTest.php:17 3) Probe\\Tests\\PickTest::testNamesMany Failed asserting that two arrays are equal. --- Expected +++ Actual @@ @@ Array ( - 'text' => '3 items' + 'text' => '3' ) /w/tests/PickTest.php:22 FAILURES! Tests: 3, Assertions: 3, Failures: 3. """ PASSING = "PHPUnit 12.5.45 by Sebastian Bergmann and contributors.\n\n... 3 / 3 (100%)\n\nOK (3 tests, 3 assertions)\n" def failing(test: str, *lines: str) -> str: return "\n".join(["F 1 / 1 (100%)", "", "There was 1 failure:", "", f"1) {test}", *lines, "", "FAILURES!", "Tests: 1, Assertions: 1, Failures: 1.", ""]) class ChangedTest(unittest.TestCase): def test_is_the_line_an_operator_mutant_changes(self): self.assertEqual(changed(OPERATOR_DIFF, LINES, 12), (12, (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW)) def test_is_every_line_from_the_first_changed_one_to_the_last(self): was = tuple(line.encode() for line in LINES[10:15]) now = (b"\t\tforeach ([] as $item) {", b" if ($item >= $floor) {", b"\t\t\t\t$sum += $item;", b"\t\t\t}", b" }") self.assertEqual(changed(FOREACH_DIFF, LINES, 11), (11, was, now)) def test_a_mutant_may_have_fewer_lines_than_it_replaces(self): was = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';") self.assertEqual(changed(TERNARY_DIFF, LINES, 21), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",))) def test_reads_an_empty_line_of_the_diff_as_an_unchanged_empty_line(self): self.assertEqual(changed(VISIBILITY_DIFF, LINES, 19), (19, (b"\tpublic static function label(int $count): string",), (b"\tprotected static function label(int $count): string",))) def test_finds_the_lines_around_the_mutants_start_line_where_the_file_holds_them_twice(self): twice = ["\t\t$a = 1;", "\t\treturn $a >= 2;", "\t}", "", "\t\t$a = 1;", "\t\treturn $a >= 2;", "\t}"] diff = "@@ @@\n \t\t$a = 1;\n-\t\treturn $a >= 2;\n+\t\treturn $a > 2;\n \t}" self.assertEqual(changed(diff, twice, 2), (2, (b"\t\treturn $a >= 2;",), (b"\t\treturn $a > 2;",))) self.assertEqual(changed(diff, twice, 6), (6, (b"\t\treturn $a >= 2;",), (b"\t\treturn $a > 2;",))) def test_is_none_where_the_diffs_lines_do_not_stand_around_the_start_line(self): self.assertIsNone(changed(OPERATOR_DIFF, LINES, 20)) self.assertIsNone(changed(OPERATOR_DIFF.replace("$sum = 0", "$sum = 1"), LINES, 12)) self.assertIsNone(changed(OPERATOR_DIFF, LINES, 0)) def test_is_none_where_the_diff_holds_no_change_or_no_hunk(self): self.assertIsNone(changed("@@ @@\n \t{\n \t\t$sum = 0;", LINES, 10)) self.assertIsNone(changed("", LINES, 10)) def test_what_it_returns_plants_as_the_mutant(self): for diff, start in ((OPERATOR_DIFF, 12), (FOREACH_DIFF, 11), (TERNARY_DIFF, 21), (VISIBILITY_DIFF, 19)): with self.subTest(start=start): line, was, now = changed(diff, LINES, start) planted = mutated(PICK.encode(), Mutant("src/Pick.php", line, "a name", was, now)) self.assertEqual(planted.split(b"\n")[line - 1], now[0]) self.assertEqual(len(planted.split(b"\n")), len(LINES) - len(was) + len(now)) class KilledMutantsTest(unittest.TestCase): def setUp(self): folder = tempfile.TemporaryDirectory() self.addCleanup(folder.cleanup) self.top = pathlib.Path(folder.name) self.ran: list[tuple[list[str], str]] = [] def infection(self, log: dict | str | None, code: int = 0): """A run that writes Infection's log where its --logger-json names, or none where log is None.""" def run(argv: list[str], cwd: str) -> Ran: self.ran.append((argv, cwd)) if log is not None: path = next(argument.partition("=")[2] for argument in argv if argument.startswith("--logger-json=")) pathlib.Path(cwd, path).write_text(log if isinstance(log, str) else json.dumps(log), encoding="utf-8") return Ran(code, "the tool's last words\n") return run def test_runs_infection_over_the_files_at_the_top_with_a_json_log_in_a_scratch_folder(self): killed_mutants(str(self.top), ["src/Pick.php", "src/Last.php"], self.infection({"killed": []}), 3) (argv, cwd), = self.ran self.assertEqual(cwd, str(self.top)) self.assertEqual(argv[:4], ["vendor/bin/infection", "--filter=src/Pick.php,src/Last.php", "--threads=3", "--no-progress"]) self.assertRegex(argv[4], r"^--logger-json=\.mutate-changes-[^/]+/log\.json$") self.assertEqual(len(argv), 5) def test_is_each_killed_mutant_as_the_lines_it_changes(self): log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF), logged("Ternary", 21, TERNARY_DIFF)], "escaped": [logged("PublicVisibility", 19, VISIBILITY_DIFF)]} found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1) ternary = (b"\t\treturn $count === 1", b"\t\t\t? 'one item'", b"\t\t\t: $count . ' items';") self.assertEqual(found, [ Mutant("src/Pick.php", 12, "src/Pick.php:12 GreaterThanOrEqualTo", (b"\t\t\tif ($item >= $floor) {",), OPERATOR_NOW), Mutant("src/Pick.php", 21, "src/Pick.php:21 Ternary", ternary, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)), ]) def test_names_a_file_by_its_path_from_the_top_wherever_infection_saw_the_tree(self): log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF, path) for path in ("/w/src/Pick.php", "src/Pick.php", "/w/lib/src/Pick.php", "/w/src/Other.php", "/w/src/NotPick.php")]} found = killed_mutants(str(self.top), ["src/Pick.php", "lib/src/Pick.php", "Pick.php"], self.infection(log), 1) self.assertEqual([mutant.path for mutant in found], ["src/Pick.php", "src/Pick.php", "lib/src/Pick.php"]) def test_leaves_out_a_mutant_whose_diff_does_not_fit_its_source(self): log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR_DIFF, source="