Files
claude-config/bin/task_bench/test_php_bugs.py
T

260 lines
13 KiB
Python

"""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 = """<?php
namespace Probe;
final class Pick
{
/** @param list<int> $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="<?php\n")]}
self.assertEqual(killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1), [])
def test_removes_the_scratch_folder(self):
for code in (0, 1):
killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": []}, code), 1)
self.assertEqual(list(self.top.iterdir()), [])
def test_fails_where_infection_exits_nonzero(self):
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": []}, code=1), 1)
self.assertEqual(found, Failure("Infection exited 1:\nthe tool's last words"))
def test_passes_on_a_run_that_could_not_start(self):
failure = Failure("vendor/bin/infection could not start: No such file or directory")
self.assertIs(killed_mutants(str(self.top), ["src/Pick.php"], lambda argv, cwd: failure, 1), failure)
def test_fails_where_infection_wrote_no_log_or_one_it_cannot_read(self):
for log in (None, "not json", "{}", '{"killed": [{"diff": ""}]}', '{"killed": [7]}'):
with self.subTest(log=log):
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1)
self.assertIsInstance(found, Failure)
self.assertIn("could not read Infection's log in ", found.reason)
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_message_without_the_tests_name_or_file(self):
self.assertEqual(task_text(FAILING), "Failed asserting that 3 is identical to 5.")
def test_is_every_line_of_a_message_up_to_the_file_and_line_that_failed(self):
second = FAILING[FAILING.index("2) "):]
expected = "one is singular\nFailed asserting that two strings are identical.\n--- Expected\n+++ Actual\n@@ @@\n-'one item'\n+''"
self.assertEqual(task_text("There was 1 failure:\n\n" + second), expected)
def test_is_none_on_a_passing_run_or_output_that_lists_no_failure(self):
self.assertIsNone(task_text(PASSING))
self.assertIsNone(task_text("PHP Parse error: syntax error, unexpected token \"}\" in /w/src/Pick.php on line 12\n"))
self.assertIsNone(task_text("1) a line that only looks like a listed test\nits message\n"))
self.assertIsNone(task_text(""))
def test_reads_an_error_as_it_reads_a_failure(self):
output = "E\n\nThere was 1 error:\n\n1) Probe\\Tests\\PickTest::testNamesOne\nTypeError: label(): Argument #1 ($count) must be of type int, string given\n\n/w/src/Pick.php:19\n/w/tests/PickTest.php:17\n\nERRORS!\n"
self.assertEqual(task_text(output), "TypeError: label(): Argument #1 ($count) must be of type int, string given")
def test_leaves_out_each_line_that_names_the_test_its_class_or_its_file(self):
lines = ("testNamesOne went wrong", "PickTest saw it", "see tests/LabelTest.php", "got 3, want 5", "", "/w/tests/PickTest.php:17")
self.assertEqual(task_text(failing("Probe\\Tests\\PickTest::testNamesOne", *lines)), "got 3, want 5")
self.assertEqual(task_text(failing("Probe\\Tests\\PickTest::testNamesOne with data set #0 (1, 'one')", *lines)), "got 3, want 5")
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text(failing("Probe\\Tests\\PickTest::testNamesOne", "testNamesOne failed", "", "/w/tests/PickTest.php:17")))
def test_takes_the_first_failed_test_that_has_a_message(self):
output = "There were 2 failures:\n\n1) PickTest::testAdds\ntestAdds\n\n/w/tests/PickTest.php:12\n\n2) PickTest::testLabels\nno label\n\n/w/tests/PickTest.php:17\n\nFAILURES!\n"
self.assertEqual(task_text(output), "no label")
def test_a_message_without_a_file_and_line_ends_at_the_next_test_or_the_summary(self):
self.assertEqual(task_text("There were 2 failures:\n\n1) PickTest::testAdds\ngot 3\n\n2) PickTest::testLabels\nno label\n"), "got 3")
self.assertEqual(task_text(failing("PickTest::testAdds", "got 3")), "got 3")
self.assertEqual(task_text("There was 1 error:\n\n1) PickTest::testAdds\ngot 3\n\n--\n\nThere was 1 failure:\n\n1) PickTest::testLabels\nno label\n"), "got 3")
if __name__ == "__main__":
unittest.main()