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

226 lines
11 KiB
Python

"""task-bench's Python planter: which mutants of mutmut's it keeps, as the lines each changes, and what pytest's output tells Haiku."""
import pathlib
import sys
import tempfile
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from failure import Failure
from task_bench.python_bugs import killed_mutants, task_text
from task_bench.planted_mutant import Mutant, mutated
from mutate_changes.tool_process import Ran
CALC = "def double(n):\n\treturn n * 2\n\n\ndef triple(n):\n\treturn (\n\t\tn * 3\n\t)\n"
# mutmut 3's copy of calc.py: the original of each function, then its mutants.
COPY = """def x_double__mutmut_orig(n):
return n * 2
def x_double__mutmut_1(n):
return n / 2
def x_double__mutmut_2(n):
return n * 3
def x_triple__mutmut_orig(n):
return (
n * 3
)
def x_triple__mutmut_1(n):
return (
n / 3
)
def x_triple__mutmut_2(n):
return [
n * 3
]
"""
RESULTS = " calc.x_double__mutmut_1: killed\n calc.x_double__mutmut_2: survived\n calc.x_triple__mutmut_1: no tests\n calc.x_triple__mutmut_2: caught by type check\n"
# pytest 9.2.0's report of three failed tests, the last on an error the code raised.
PYTEST_FAILURES = """============================= test session starts ==============================
collected 5 items
test_calc.py ..FFF [100%]
=================================== FAILURES ===================================
_____________________________ TotalTest.test_adds ______________________________
self = <test_calc.TotalTest testMethod=test_adds>
def test_adds(self):
> self.assertEqual(total(1, 2), 3)
E AssertionError: -1 != 3
test_calc.py:14: AssertionError
________________________________ test_total[1] _________________________________
a = 1
@pytest.mark.parametrize("a", [1, 2])
def test_total(a):
> assert total(a, 2) == a + 2
E assert -1 == (1 + 2)
E + where -1 = total(1, 2)
test_calc.py:19: AssertionError
__________________________________ test_pick ___________________________________
def test_pick():
> assert pick([1, 2, 3]) == 3
^^^^^^^^^^^^^^^
test_calc.py:23:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
rows = [1, 2, 3]
def pick(rows):
> return rows[3]
^^^^^^^
E IndexError: list index out of range
calc.py:2: IndexError
=========================== short test summary info ============================
FAILED test_calc.py::TotalTest::test_adds - AssertionError: -1 != 3
FAILED test_calc.py::test_total[1] - assert -1 == (1 + 2)
FAILED test_calc.py::test_pick - IndexError: list index out of range
========================= 3 failed, 2 passed in 0.03s ==========================
"""
def failures(*sections: str) -> str:
"""pytest's report of failed tests, each section a test's heading and what follows it, as --tb=short prints them."""
return "=================================== FAILURES ===================================\n" + "".join(sections) + "=========================== short test summary info ============================\nE no error\n"
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
for path, text in (("bin/setup.cfg", "[tool:pytest]\n"), ("bin/pkg/calc.py", CALC), ("bin/pkg/test_calc.py", "import pkg.calc\n"), ("bin/pkg/empty.py", "LIMIT = 3\n"), ("README.md", "# Calc\n")):
(self.top / path).parent.mkdir(parents=True, exist_ok=True)
(self.top / path).write_text(text)
self.ran: list[tuple[list[str], str, list[str]]] = []
# Where the fake mutmut writes its copy of calc.py, from the folder it runs in.
self.copy = "pkg/calc.py"
def mutmut(self, results: str = RESULTS, code: int = 0, said: str = ""):
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd, sorted(str(path.relative_to(cwd)) for path in pathlib.Path(cwd).rglob("*") if path.is_file())))
if argv[:2] == ["mutmut", "results"]:
return Ran(0, results)
pathlib.Path(cwd, "mutants", self.copy).parent.mkdir(parents=True)
pathlib.Path(cwd, "mutants", self.copy).write_text(COPY)
return Ran(code, said)
return run
def test_keeps_each_mutant_the_tests_kill_as_the_lines_it_changes_named_by_its_place_and_mutmuts_name(self):
found = killed_mutants(str(self.top), ["bin/pkg/calc.py"], self.mutmut(RESULTS.replace("calc.x_", "pkg.calc.x_")), 3)
self.assertEqual(found, [
Mutant("bin/pkg/calc.py", 2, "bin/pkg/calc.py:2 x_double__mutmut_1", (b"\treturn n * 2",), (b"\treturn n / 2",)),
Mutant("bin/pkg/calc.py", 6, "bin/pkg/calc.py:6 x_triple__mutmut_2", (b"\treturn (", b"\t\tn * 3", b"\t)"), (b"\treturn [", b"\t\tn * 3", b"\t]")),
])
def test_mutmut_mutates_every_function_of_the_files_in_a_copy_of_the_folder_that_holds_their_settings(self):
killed_mutants(str(self.top), ["bin/pkg/calc.py"], self.mutmut(), 3)
argv, cwd, files = self.ran[0]
self.assertEqual(argv, ["mutmut", "run", "--max-children", "3", "pkg.calc.x_double*", "pkg.calc.x_triple*"])
self.assertEqual((pathlib.Path(cwd).parent.parent, files), (self.top, ["pkg/calc.py", "pkg/empty.py", "pkg/test_calc.py", "setup.cfg"]))
self.assertEqual(self.ran[1][0], ["mutmut", "results", "--all", "true"])
self.assertEqual(sorted(path.name for path in self.top.iterdir()), ["README.md", "bin"])
def test_mutmuts_copy_keeps_a_link_to_a_folder_as_a_link(self):
(self.top / "bin/shared").mkdir()
(self.top / "bin/pkg/fixtures").symlink_to("../shared")
links: list[str] = []
mutmut = self.mutmut()
def run(argv: list[str], cwd: str) -> Ran:
links.extend(str(path.relative_to(cwd)) for path in pathlib.Path(cwd).rglob("*") if path.is_symlink())
return mutmut(argv, cwd)
killed_mutants(str(self.top), ["bin/pkg/calc.py"], run, 3)
self.assertEqual(links[:1], ["pkg/fixtures"])
def test_a_file_without_a_function_has_no_mutant_and_mutmut_does_not_run(self):
self.assertEqual(killed_mutants(str(self.top), ["bin/pkg/empty.py"], self.mutmut(), 3), [])
self.assertEqual(self.ran, [])
def test_a_mutmut_that_fails_or_crashes_is_a_failure_that_says_how(self):
crash = 'Traceback (most recent call last):\n File "/uv/site-packages/mutmut/__main__.py", line 1050, in _run\n worker = pop(pid)\nKeyError: 12\n'
for said, reason in (("mutmut said so", "mutmut said so"), (crash, "mutmut in bin crashed with KeyError: 12, in mutmut/__main__.py line 1050")):
with self.subTest(said=said):
found = killed_mutants(str(self.top), ["bin/pkg/calc.py"], self.mutmut(code=1, said=said), 3)
self.assertIsInstance(found, Failure)
self.assertIn(reason, found.reason)
def test_a_file_that_is_gone_is_a_failure_that_names_the_tree(self):
found = killed_mutants(str(self.top), ["bin/pkg/gone.py"], self.mutmut(), 3)
self.assertIsInstance(found, Failure)
self.assertIn(f"could not read the files to mutate in {self.top}", found.reason)
def test_mutates_a_function_on_the_files_first_line_and_one_on_its_last(self):
(self.top / "bin/pkg/ends.py").write_text("def first(n): return n + 1\n\n\ndef last(n): return n * 2")
killed_mutants(str(self.top), ["bin/pkg/ends.py"], self.mutmut(), 3)
self.assertEqual(self.ran[0][0][4:], ["pkg.ends.x_first*", "pkg.ends.x_last*"])
def test_a_crlf_file_gives_the_same_mutants_without_the_cr_and_they_apply_to_it(self):
(self.top / "bin/pkg/calc.py").write_bytes(CALC.replace("\n", "\r\n").encode())
found = killed_mutants(str(self.top), ["bin/pkg/calc.py"], self.mutmut(RESULTS.replace("calc.x_", "pkg.calc.x_")), 3)
self.assertEqual([(mutant.line, mutant.was, mutant.now) for mutant in found], [(2, (b"\treturn n * 2",), (b"\treturn n / 2",)), (6, (b"\treturn (", b"\t\tn * 3", b"\t)"), (b"\treturn [", b"\t\tn * 3", b"\t]"))])
changed = mutated((self.top / "bin/pkg/calc.py").read_bytes(), found[0])
self.assertIsNotNone(changed)
self.assertIn(b"\treturn n / 2\r\n", changed or b"")
def test_keeps_the_mutants_of_every_folder_mutmut_runs_in(self):
for path, text in (("tools/setup.cfg", "[tool:pytest]\n"), ("tools/pkg/calc.py", CALC)):
(self.top / path).parent.mkdir(parents=True, exist_ok=True)
(self.top / path).write_text(text)
found = killed_mutants(str(self.top), ["tools/pkg/calc.py", "bin/pkg/calc.py"], self.mutmut(RESULTS.replace("calc.x_", "pkg.calc.x_")), 3)
self.assertEqual([mutant.name for mutant in found], ["bin/pkg/calc.py:2 x_double__mutmut_1", "bin/pkg/calc.py:6 x_triple__mutmut_2", "tools/pkg/calc.py:2 x_double__mutmut_1", "tools/pkg/calc.py:6 x_triple__mutmut_2"])
def test_a_file_in_the_folder_mutmut_runs_in_at_the_top_keeps_its_path(self):
(self.top / "setup.cfg").write_text("[tool:pytest]\n")
(self.top / "calc.py").write_text(CALC)
self.copy = "calc.py"
found = killed_mutants(str(self.top), ["calc.py"], self.mutmut(), 3)
self.assertEqual(found[0], Mutant("calc.py", 2, "calc.py:2 x_double__mutmut_1", (b"\treturn n * 2",), (b"\treturn n / 2",)))
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_error_without_the_code_around_it(self):
self.assertEqual(task_text(PYTEST_FAILURES), "AssertionError: -1 != 3")
def test_keeps_each_line_of_the_error(self):
self.assertEqual(task_text(failures("___ test_total[1] ___\ntest_calc.py:19: in test_total\n assert total(a, 2) == a + 2\nE assert -1 == (1 + 2)\nE + where -1 = total(1, 2)\nE\n")), "assert -1 == (1 + 2)\n+ where -1 = total(1, 2)")
def test_takes_an_error_the_code_raised_from_below_the_last_frame(self):
section = "___ test_pick ___\ntest_calc.py:23: \n_ _ _ _ _ _ _ _\n\n def pick(rows):\n> \treturn rows[3]\nE IndexError: list index out of range\n\ncalc.py:2: IndexError\n"
self.assertEqual(task_text(failures(section)), "IndexError: list index out of range")
def test_leaves_out_each_line_that_names_the_test_its_class_or_a_test_file(self):
section = "_ PickTest.test_empty[case 1] _\nE AssertionError: 3 != 4\nE test_empty: off by one\nE in PickTest\nE see test_calc.py:12\nE see calc_test.py\nE see conftest.py\nE see calc.py\n"
self.assertEqual(task_text(failures(section)), "AssertionError: 3 != 4\nsee calc.py")
def test_is_none_where_the_first_error_only_names_the_test(self):
self.assertIsNone(task_text(failures("___ test_pick ___\nE test_pick failed\n", "___ test_last ___\nE got 5\n")))
def test_takes_the_first_failed_test_that_has_an_error(self):
self.assertEqual(task_text(failures("___ test_pick ___\nno error here\n", "___ test_next ___\nE got 3\n", "___ test_last ___\nE got 5\n")), "got 3")
def test_a_line_the_failed_test_printed_is_no_error(self):
section = "___ test_pick ___\nE got 3\n----------------------------- Captured stdout call -----------------------------\nE printed, not raised\n"
self.assertEqual(task_text(failures(section, "___ test_last ___\nE got 5\n")), "got 3")
self.assertIsNone(task_text(failures("___ test_pick ___\n--- Captured stderr call ---\nE printed, not raised\n")))
def test_is_none_where_pytest_reports_no_failed_test_with_an_error(self):
for output in ("", "===== 5 passed in 0.03s =====\n", "E stray\n", "==== ERRORS ====\n___ ERROR collecting test_calc.py ___\nE SyntaxError: invalid syntax\n", failures(), failures("___ test_pick ___\n"), "E before\n" + failures("E under no test\n")):
with self.subTest(output=output):
self.assertIsNone(task_text(output))
def test_an_error_runs_to_the_end_of_the_output(self):
self.assertEqual(task_text("==== FAILURES ====\n___ test_pick ___\nE got 3"), "got 3")
if __name__ == "__main__":
unittest.main()