276 lines
14 KiB
Python
276 lines
14 KiB
Python
"""task-bench's PHP planter: which files Infection mutates, how its log's mutants become lines and what PHPUnit's output tells Haiku.
|
|
|
|
The four mutants of PICK and FAILING are what Infection 0.35.12 and PHPUnit 12.5.45 wrote for a small project on PHP 8.5.13. Each
|
|
logged mutant is cut down to the keys the planter reads. The other mutants 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[2]))
|
|
|
|
from task_bench.bugs.php_bugs import changed, killed_mutants, task_text
|
|
from failure import Failure
|
|
from task_bench.bugs.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")
|
|
|
|
|
|
def with_lines(first: int, count: int, *now: str) -> str:
|
|
"""PICK with `count` lines from line `first` on replaced by `now`: the mutated source Infection logged for such a mutant."""
|
|
return "\n".join([*LINES[:first - 1], *now, *LINES[first - 1 + count:]])
|
|
|
|
|
|
OPERATOR = with_lines(12, 1, "\t\t\tif ($item > $floor) {")
|
|
# Infection prints the lines of a statement it rewrote with its own indent, and leaves the ones between them as they were.
|
|
FOREACH = with_lines(11, 5, "\t\tforeach ([] as $item) {", " if ($item >= $floor) {", "\t\t\t\t$sum += $item;", "\t\t\t}", " }")
|
|
TERNARY = with_lines(21, 3, "\t\treturn $count === 1 ? $count . ' items' : 'one item';")
|
|
VISIBILITY = with_lines(19, 1, "\tprotected static function label(int $count): string")
|
|
OPERATOR_NOW = (b"\t\t\tif ($item > $floor) {",)
|
|
|
|
|
|
def logged(mutator: str, line: int, mutated_source: str, path: str = "/w/src/Pick.php", source: str = PICK) -> dict:
|
|
return {"mutator": {"mutatorName": mutator, "originalSourceCode": source, "mutatedSourceCode": mutated_source, "originalFilePath": path, "originalStartLine": line}}
|
|
|
|
|
|
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(PICK, OPERATOR), (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(PICK, FOREACH), (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(PICK, TERNARY), (21, was, (b"\t\treturn $count === 1 ? $count . ' items' : 'one item';",)))
|
|
|
|
def test_a_mutant_may_only_remove_a_line_or_only_add_one(self):
|
|
self.assertEqual(changed("a\nb\nc", "a\nc"), (2, (b"b",), ()))
|
|
self.assertEqual(changed("a\nc", "a\nb\nc"), (2, (), (b"b",)))
|
|
|
|
def test_a_line_counts_as_unchanged_before_the_change_or_after_it_never_both(self):
|
|
self.assertEqual(changed("a\nb\nb", "a\nb"), (3, (b"b",), ()))
|
|
self.assertEqual(changed("b\nb\nc", "b\nc"), (2, (b"b",), ()))
|
|
|
|
def test_reaches_the_first_line_and_the_last(self):
|
|
self.assertEqual(changed("a\nb", "c\nb"), (1, (b"a",), (b"c",)))
|
|
self.assertEqual(changed("a\nb", "a\nc"), (2, (b"b",), (b"c",)))
|
|
|
|
def test_is_none_where_the_mutant_changes_no_line(self):
|
|
self.assertIsNone(changed(PICK, PICK))
|
|
|
|
def test_what_it_returns_plants_as_the_mutant(self):
|
|
for source in (OPERATOR, FOREACH, TERNARY, VISIBILITY):
|
|
line, was, now = changed(PICK, source)
|
|
self.assertEqual(mutated(PICK.encode(), Mutant("src/Pick.php", line, "a name", was, now)), source.encode())
|
|
|
|
|
|
class KilledMutantsTest(unittest.TestCase):
|
|
def setUp(self):
|
|
folder = tempfile.TemporaryDirectory()
|
|
self.addCleanup(folder.cleanup)
|
|
self.top = pathlib.Path(folder.name)
|
|
(self.top / "src").mkdir()
|
|
(self.top / "src/Pick.php").write_text(PICK, encoding="utf-8")
|
|
self.ran: list[tuple[list[str], 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, and another log beside it."""
|
|
def run(argv: list[str], cwd: str) -> Ran:
|
|
self.ran.append((argv, cwd, pathlib.Path(cwd, "src/Pick.php").read_text(encoding="utf-8")))
|
|
pathlib.Path(cwd, "infection.html").write_text("every mutant", encoding="utf-8")
|
|
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_in_a_copy_of_the_tree_with_a_json_log_and_no_score_to_reach(self):
|
|
killed_mutants(str(self.top), ["src/Pick.php", "src/Last.php"], self.infection({"killed": []}), 3)
|
|
(argv, cwd, source), = self.ran
|
|
self.assertRegex(cwd, rf"^{self.top}/\.mutate-changes-[^/]+/copy$")
|
|
self.assertEqual(source, PICK)
|
|
self.assertEqual(argv, ["vendor/bin/infection", "--filter=src/Pick.php,src/Last.php", "--threads=3", "--no-progress", "--min-msi=0", "--min-covered-msi=0", "--logger-json=infection-log.json"])
|
|
|
|
def test_is_each_killed_mutant_as_the_lines_it_changes(self):
|
|
log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR), logged("Ternary", 21, TERNARY)], "escaped": [logged("PublicVisibility", 19, VISIBILITY)]}
|
|
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_mutant_by_the_line_infection_logs_for_it(self):
|
|
found = killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": [logged("Foreach_", 11, FOREACH), logged("Ternary", 20, TERNARY)]}), 1)
|
|
self.assertEqual([(mutant.line, mutant.name) for mutant in found], [(11, "src/Pick.php:11 Foreach_"), (21, "src/Pick.php:20 Ternary")])
|
|
|
|
def test_names_a_file_by_its_path_from_the_top_wherever_infection_saw_the_tree(self):
|
|
log = {"killed": [logged("GreaterThanOrEqualTo", 12, OPERATOR, 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_that_changes_no_line(self):
|
|
log = {"killed": [logged("GreaterThanOrEqualTo", 12, PICK)]}
|
|
self.assertEqual(killed_mutants(str(self.top), ["src/Pick.php"], self.infection(log), 1), [])
|
|
|
|
def test_leaves_the_tree_as_it_was_whatever_infection_wrote(self):
|
|
for code in (0, 1):
|
|
killed_mutants(str(self.top), ["src/Pick.php"], self.infection({"killed": []}, code), 1)
|
|
self.assertEqual(sorted(str(path.relative_to(self.top)) for path in self.top.rglob("*")), ["src", "src/Pick.php"])
|
|
|
|
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):
|
|
unreadable = (None, "not json", "{}", '{"killed": [{}]}', '{"killed": [7]}', json.dumps({"killed": [{"mutator": {**logged("Ternary", 21, TERNARY)["mutator"], "mutatedSourceCode": 7}}]}))
|
|
for log in unreadable:
|
|
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, infection-log.json in ", found.reason)
|
|
|
|
def test_fails_where_the_tree_cannot_be_copied(self):
|
|
found = killed_mutants(str(self.top / "missing"), ["src/Pick.php"], self.infection({"killed": []}), 1)
|
|
self.assertIsInstance(found, Failure)
|
|
self.assertEqual(self.ran, [])
|
|
|
|
|
|
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_reads_a_listed_test_that_names_no_class(self):
|
|
self.assertEqual(task_text(failing("testNamesOne", "got 3, want 5")), "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_reads_no_test_of_another_list_as_a_failed_one(self):
|
|
named = failing("Probe\\Tests\\PickTest::testSum", "PickTest failed", "", "/w/tests/PickTest.php:9").partition("FAILURES!")[0]
|
|
for heading in ("There was 1 risky test:", "There were 2 risky tests:", "1 test triggered 1 deprecation:", "2 tests triggered 3 PHPUnit warnings:"):
|
|
with self.subTest(heading=heading):
|
|
output = "\n".join([named, "--", "", heading, "", "1) Probe\\Tests\\LastTest::testLabels", "This test did not perform any assertions", "", "/w/tests/LastTest.php:20", "", "FAILURES!"])
|
|
self.assertIsNone(task_text(output))
|
|
|
|
def test_reads_the_failures_listed_after_another_list(self):
|
|
output = "\n".join(["There was 1 risky test:", "", "1) LastTest::testLabels", "This test did not perform any assertions", "", "--", "", "There was 1 failure:", "", "1) PickTest::testSum", "Failed asserting that 3 is identical to 5.", "", "/w/tests/PickTest.php:9", "", "FAILURES!"])
|
|
self.assertEqual(task_text(output), "Failed asserting that 3 is identical to 5.")
|
|
|
|
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()
|