Plant bugs for task-bench in Python from the mutants mutmut kills
CI / tests (pull_request) Failing after 3m46s

This commit is contained in:
2026-11-23 21:31:00 +01:00
parent cb6aedd603
commit c6cdd2f850
15 changed files with 968 additions and 401 deletions
+2 -2
View File
@@ -228,7 +228,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `settings_filter.py` is git's clean filter for `settings.json`: it drops `"model"` and sorts the keys. `.gitattributes` sets the filter `settings` on `settings.json`, and Install's `git config` line makes this script that filter.
- `statusline.py` renders Claude Code's status line; `settings.json` → `statusLine` runs it.
- `subagent-rung [--plan] <model> <L>` prints the Agent tool's model and effort for a subagent's task, picked by its L from the project's model on the project's routing ladder, and with `--plan` never below the project's rung; `subagent-rung --help` states the rule.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, at the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `task-bench --image <image> --test <shell text> [<options>]` plants bugs that the tests catch, in the Go and Python files that hold the places the comprehension seats found hardest, has Haiku fix each at the base and at the head, and prints how often the fix passes and what it took. It needs docker and a token from `claude setup-token`; `task-bench --help` says how it plants, runs and checks. It leaves a digest of why runs failed. With `--tasks features` it has Haiku build each feature in the folder the config names as `bench-tasks` instead, from its spec, and checks the build with acceptance tests Haiku never sees. With `--tasks data-sources` it has Haiku add each data source there: a folder that also holds `generate-register`, the seeded script whose made-up register Haiku imports. With `--record-figures`, a bench that finishes appends its figures over every task to the comprehension history. A scoring run starts the bench that way where the project's README documents its `task-bench` command. `task-bench gather` starts a claude on the project's rung, which files a plan item for each place the digest shows to be hard; then gather removes the bench's folder, digest and streams.
- `todo-item` reads and changes a project's plan, whatever holds it: `list` prints the items in the plan's order and `show <ID>` one item's row and detail; `add …` files an item under the next free ID, `edit <ID> …` sets an item's cells or detail, and `move <ID> --release <version>` sets an item's release; `finish <ID>` removes a finished item and adds the bullet passed with `--changelog` to `CHANGELOG.md`, except for a plan kept in Jira. Each change ranks a markdown plan. `todo-item --help` states the flags.
- `touch-predictions record <ID>...` appends what a chunk's items were predicted to touch, under `Touches:` in their details, beside the files and parts its branch touched, to the record the config names as `touch-predictions`; `touch-predictions --help` shows the spelling and how a part is named. `chunk-preflight` reads the same predictions to name the items that may start chunks at once.
- `wait-for <file> [<pattern>] [--timeout <seconds>]` waits until a file a background job writes holds a line matching the pattern, and prints it.
@@ -278,7 +278,7 @@ Install puts only `loop-claude` on `PATH`; call the others by their path, such a
- `review_rules/` holds the larv-review rules that several tools apply: its passes, its review folder, its round commit titles and the comprehension history's format.
- `routing_figures/` measures loop-claude's archive, and each of its projects' default branches, for loop-claude's routing calls.
- `rung_replay/` holds what `judge_replay` and `review_replay` share: the parallel replay runner, the argument reader, the candidate rungs and the exits, and `judge_replay`'s rung search. It reads `agent_cycle`'s retry count and `chunk_driver`'s models file, and finds that file through `loop_state`'s paths. Its `archive.py` keeps each replay's runs and its report in a `replays/` folder of loop-claude's archive.
- `task_bench/` holds `task-bench`, which plants bugs in a Go project, or takes the project's bench features or data sources, and has Haiku fix, build or add them in containers.
- `task_bench/` holds `task-bench`, which plants bugs in a project's Go and Python files, or takes the project's bench features or data sources, and has Haiku fix, build or add them in containers.
- `test_env.py` serves the tests.
- `text_files/` reads a Markdown file's `##` sections, quotes a passage and joins names into a list, reads the text piped into a command, stamps times in UTC, replaces a file in one step, private where it is new, and gzips a file beside its plain name, by which it reads it afterwards.
- `transcript_archive/` stores loop-claude's transcripts. Its `project_key.py` names each project's archive folder, loop-claude session and models-file entry.
+19 -6
View File
@@ -62,10 +62,18 @@ def statuses(results: str) -> dict[str, str]:
return {name: status for name, _, status in (line.strip().partition(": ") for line in results.splitlines()) if "__mutmut_" in name and status}
def mutated_line(source: str, copy: str, key: str, number: int) -> tuple[int, str] | None:
"""The source line a mutant changes, with that line as the mutant has it; None where the mutants/ copy lacks the mutant, or holds an original unlike the source.
class Change(NamedTuple):
"""The source lines a mutant changes: the number of the first, those lines as the source has them, and what the mutant has in their place."""
A mutant keeps the original's lines, so the first line where they differ sits at the same offset from the source function's def."""
line: int
was: tuple[str, ...]
now: tuple[str, ...]
def mutated_lines(source: str, copy: str, key: str, number: int) -> Change | None:
"""The source lines a mutant changes; None where the mutants/ copy lacks the mutant, or holds an original unlike the source.
A mutant is a changed copy of the original, so the lines before the first that differs, and those after the last, sit at the same offsets from the source function's def."""
module, copied = parsed(source), parsed(copy)
if module is None or copied is None:
return None
@@ -77,8 +85,13 @@ def mutated_line(source: str, copy: str, key: str, number: int) -> tuple[int, st
kept, changed = (as_named(copied.lines, node, function.name) for node in (original, mutant))
if kept != expected:
return None
offset = next((index for index, (was, now) in enumerate(zip(kept, changed)) if was != now), None)
return None if offset is None else (function.lineno + offset, changed[offset].strip())
first = next((index for index, (was, now) in enumerate(zip(kept, changed)) if was != now), None)
if first is None:
return None
after = 0
while after < min(len(kept), len(changed)) - first and kept[-1 - after] == changed[-1 - after]:
after += 1
return Change(function.lineno + first, tuple(kept[first:len(kept) - after]), tuple(changed[first:len(changed) - after]))
class Parsed(NamedTuple):
@@ -87,7 +100,7 @@ class Parsed(NamedTuple):
lines: tuple[str, ...]
# mutated_line reads the same source and mutants/ copy for each of a file's mutants, and a copy holds every mutant, so parsing it
# mutated_lines reads the same source and mutants/ copy for each of a file's mutants, and a copy holds every mutant, so parsing it
# anew for each one made the report take minutes.
@functools.lru_cache(maxsize=4)
def parsed(text: str) -> Parsed | None:
+95 -32
View File
@@ -1,4 +1,4 @@
"""Mutate the changed lines of a branch's Python files with mutmut 3, in a scratch copy of the folder each file's tests run from.
"""Mutate the changed lines of a branch's Python files with mutmut 3, or every line of the files given, in a scratch copy of the folder each file's tests run from.
mutmut reads its settings from the folder it runs in, writes beside them, and names each module by its path from there. So each file is
mutated from the folder its tests import it from: the nearest folder above it, up to the checkout's top, that holds a setup.cfg or a
@@ -9,9 +9,10 @@ import pathlib
import posixpath
import shutil
import tomllib
import typing
from mutate_changes.changed_lines import by_folder, label
from mutate_changes.mutmut_mutants import crash_in_mutmut, function_keys, mutant_globs, mutated_line, named, statuses
from mutate_changes.mutmut_mutants import crash_in_mutmut, function_keys, Change, mutant_globs, mutated_lines, named, statuses
from mutate_changes.tool_process import failed, Ran, remove, Run, scratch_folder
from failure import Failure
from git_cli.git_repo import Git
@@ -43,36 +44,82 @@ class Folder:
return label(self.path)
@dataclasses.dataclass(frozen=True)
class Ended:
"""How mutmut's run in a folder ended. found is empty where the folder has no mutant, as none says why, or where mutmut crashed, as crash says how."""
folder: Folder
found: dict[str, str] = dataclasses.field(default_factory=dict) # each mutant's status by mutmut's name of it
copies: dict[str, str] = dataclasses.field(default_factory=dict) # mutmut's mutants/ copy of each of the folder's files it wrote one for
none: str = ""
crash: str = ""
notes: str = "" # what the run left out, for the report
class Located(typing.NamedTuple):
"""A mutant in a function or method that a folder's lines fall in. change is None where the lines it changes cannot be found."""
file: str # from the folder
name: str
status: str
change: Change | None
class Killed(typing.NamedTuple):
"""A mutant the tests kill, by mutmut's name of it, with its file's path from the top and the lines it changes."""
path: str
name: str
change: Change
def run_mutmut(top: str, changed: dict[str, frozenset[int]], run: Run, git: Git, jobs: int) -> list[str] | Failure:
"""For each folder mutmut runs in, a line on what it mutated and left out, then a line per mutant on a changed line that its tests don't kill.
changed maps each file, by its path from top, to its changed lines."""
report: list[str] = []
for path, files in sorted(imported_by_file_name(top, by_folder(top, changed, CONFIGS), CONFIGS).items()):
lines = mutate_folder(top, path, files, run, git, jobs)
if isinstance(lines, Failure):
return lines
report.extend(lines)
listed = git("ls-files", "-z", "--cached", "--others", "--exclude-standard", cwd=os.path.join(top, path))
if isinstance(listed, Failure):
return listed
ended = mutate_folder(top, path, files, listed.split("\0"), run, jobs)
if isinstance(ended, Failure):
return ended
report.extend(reported(ended))
return report
def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], run: Run, git: Git, jobs: int) -> list[str] | Failure:
def killed_by_mutmut(top: str, paths: list[str], run: Run, jobs: int) -> list[Killed] | Failure:
"""Each mutant in the files at paths, from top, that the tests kill, in the order of mutmut's names within each folder it runs in.
top holds the project's files and no others, as an unpacked `git archive` does: mutmut's copy of a folder takes every file under it."""
try:
lines = {path: frozenset(range(1, len(pathlib.Path(top, path).read_bytes().splitlines()) + 1)) for path in paths}
except OSError as failure:
return Failure(f"could not read the files to mutate in {top}: {failure}")
killed: list[Killed] = []
for path, files in sorted(imported_by_file_name(top, by_folder(top, lines, CONFIGS), CONFIGS).items()):
root = os.path.join(top, path)
listed = [os.path.relpath(os.path.join(folder, name), root) for folder, _, names in os.walk(root) for name in names]
ended = mutate_folder(top, path, files, listed, run, jobs)
if isinstance(ended, Failure) or ended.crash:
return ended if isinstance(ended, Failure) else Failure(f"mutmut in {ended.folder.label} crashed with {ended.crash}")
killed += [Killed(posixpath.normpath(posixpath.join(path, mutant.file)), mutant.name, mutant.change) for mutant in located(ended) if mutant.status in CAUGHT and mutant.change]
return killed
def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], listed: list[str], run: Run, jobs: int) -> Ended | Failure:
"""Runs mutmut over the functions and methods the lines of files fall in, in a scratch copy of the folder at path that holds the files listed."""
root = os.path.join(top, path)
folder = read_folder(root, path, files)
if isinstance(folder, Failure):
return folder
globs = [glob for file in sorted(files) for glob in mutant_globs(file, folder.keys[file])]
if not globs:
return [f"mutmut in {folder.label}: no changed line falls in a function or method, the only code mutmut mutates."]
listed = git("ls-files", "-z", "--cached", "--others", "--exclude-standard", cwd=root)
if isinstance(listed, Failure):
return listed
return Ended(folder, none="no changed line falls in a function or method, the only code mutmut mutates.")
scratch = scratch_folder(top)
if isinstance(scratch, Failure):
return scratch
try:
copy = os.path.join(scratch, "copy")
copied = copy_files(root, listed.split("\0"), copy)
copied = copy_files(root, listed, copy)
return mutate_copy(copy, copied, folder, ["mutmut", "run", "--max-children", str(jobs), *globs], run)
except OSError as failure:
return Failure(f"could not set mutmut up in {scratch}, a copy of {root}: {failure}")
@@ -123,26 +170,37 @@ def copy_files(root: str, paths: list[str], copy: str) -> list[str]:
return sorted(copied)
def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], run: Run) -> list[str] | Failure:
def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], run: Run) -> Ended | Failure:
ran = run_until_stats_pass(copy, copied, folder, argv, run)
if isinstance(ran, Failure):
return ran
(output, code), left = ran
crash = crash_in_mutmut(output)
if code and crash:
return [f"mutmut in {folder.label} crashed with {crash}: mutate its changed lines by hand."]
return Ended(folder, crash=crash)
if not os.path.isdir(os.path.join(copy, "mutants")):
return Failure(f"mutmut in {folder.label} wrote no mutants/ in {copy}; --prefix must run it in $PWD")
if NO_MUTANT in output:
return [f"mutmut in {folder.label}: none of the functions the changed lines fall in has a mutant."]
return Ended(folder, none="none of the functions the changed lines fall in has a mutant.")
results = run(["mutmut", "results", "--all", "true"], copy)
if isinstance(results, Failure) or results.code:
return results if isinstance(results, Failure) else failed(f"mutmut results in {folder.label}", results)
shown, counted = not_killed(folder, statuses(results.output), copy)
copies = {file: mutated.read_text(encoding="utf-8", errors="replace") for file in folder.files if (mutated := pathlib.Path(copy, "mutants", file)).is_file()}
unreached = " No test reaches them." if NO_TEST in output else ""
left_files = sorted({option.partition("=")[2].partition("::")[0] for option in left})
left_note = f" Left out the tests that fail without a mutant, in {', '.join(left_files)}." if left else ""
return [f"mutmut in {folder.label}: {counted} mutants on changed lines, {len(shown)} not killed.{unreached}{left_note}", *shown]
return Ended(folder, statuses(results.output), copies, notes=unreached + left_note)
def reported(ended: Ended) -> list[str]:
"""A line on what mutmut mutated in the folder and left out, then a line per mutant on a changed line that its tests don't kill."""
label = ended.folder.label
if ended.crash:
return [f"mutmut in {label} crashed with {ended.crash}: mutate its changed lines by hand."]
if ended.none:
return [f"mutmut in {label}: {ended.none}"]
shown, counted = not_killed(ended)
return [f"mutmut in {label}: {counted} mutants on changed lines, {len(shown)} not killed.{ended.notes}", *shown]
def run_until_stats_pass(copy: str, copied: list[str], folder: Folder, argv: list[str], run: Run) -> tuple[tuple[str, int], list[str]] | Failure:
@@ -168,25 +226,30 @@ def configured_run(copy: str, copied: list[str], folder: Folder, options: list[s
return run(argv, copy)
def not_killed(folder: Folder, found: dict[str, str], copy: str) -> tuple[list[str], int]:
"""A line per mutant on a changed line that its tests don't kill, in order of path and line, and how many mutants the changed lines hold."""
copies: dict[str, str] = {}
shown: list[tuple[str, int, str]] = []
counted = 0
# Sorted by name, a file's mutants come one after another, so mutated_line parses its copy once.
for name, status in sorted(found.items()):
def located(ended: Ended) -> typing.Iterator[Located]:
"""Each mutant of the run that is in a function or method the folder's lines fall in, in the order of mutmut's names."""
folder = ended.folder
# Sorted by name, a file's mutants come one after another, so mutated_lines parses its copy once.
for name, status in sorted(ended.found.items()):
hit = named(name, list(folder.files))
if hit is None or hit[1] not in folder.keys[hit[0]]:
continue
file, key, number = hit
if file not in copies:
mutated = pathlib.Path(copy, "mutants", file)
copies[file] = mutated.read_text(encoding="utf-8", errors="replace") if mutated.is_file() else ""
where = mutated_line(folder.sources[file], copies[file], key, number)
if where and where[0] not in folder.files[file]:
yield Located(file, name, status, mutated_lines(folder.sources[file], ended.copies.get(file, ""), key, number))
def not_killed(ended: Ended) -> tuple[list[str], int]:
"""A line per mutant on a changed line that its tests don't kill, in order of path and line, and how many mutants the changed lines hold."""
folder = ended.folder
shown: list[tuple[str, int, str]] = []
counted = 0
for mutant in located(ended):
change = mutant.change
if change and change.line not in folder.files[mutant.file]:
continue
counted += 1
if status not in CAUGHT:
line, text = where or (0, f"{name}, on a line mutate-changes cannot find")
shown.append((posixpath.normpath(posixpath.join(folder.path, file)), line, f"{status}: {text}"))
if mutant.status not in CAUGHT:
# The first line the mutant has in place of the source's; where it only removes lines, it has none.
line, text = (change.line, "".join(change.now[:1]).strip() or "lines removed") if change else (0, f"{mutant.name}, on a line mutate-changes cannot find")
shown.append((posixpath.normpath(posixpath.join(folder.path, mutant.file)), line, f"{mutant.status}: {text}"))
return [f"{file}:{line}: {text}" if line else f"{file}: {text}" for file, line, text in sorted(shown)], counted
+23 -12
View File
@@ -15,7 +15,7 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from mutate_changes.changed_lines import added_lines, by_folder, not_mutated, runs, tool_for
from mutate_changes.mutmut_tool import copy_files
from mutate_changes.mutmut_mutants import crash_in_mutmut, function_keys, mutant_globs, mutated_line, named, statuses
from mutate_changes.mutmut_mutants import crash_in_mutmut, function_keys, mutant_globs, mutated_lines, named, statuses
from failure import Failure
from mutate_changes.bare_imports import imported_by_file_name
from test_env import isolated_env
@@ -230,26 +230,37 @@ class MutmutMutants(unittest.TestCase):
results = " pkg.x_f__mutmut_1: survived\n pkg.x_f__mutmut_2: no tests\n\n pkg.x_f__mutmut_3: killed\n pkg.x_f__mutmut_4:\n mutants: 4\n"
self.assertEqual(statuses(results), {"pkg.x_f__mutmut_1": "survived", "pkg.x_f__mutmut_2": "no tests", "pkg.x_f__mutmut_3": "killed"})
def test_a_mutated_line_is_the_first_line_the_mutant_changes_at_its_place_in_the_source(self):
self.assertEqual(mutated_line(SOURCE, COPY, "x_double", 1), (2, "return n / 2"))
self.assertEqual(mutated_line(SOURCE, COPY, "xǁPtǁmoved", 1), (6, "def moved(self, by=2):"))
self.assertEqual(mutated_line(SOURCE, COPY, "xǁPtǁmoved", 2), (7, "return self.x - by"))
def test_the_mutated_lines_are_those_the_mutant_changes_at_their_place_in_the_source(self):
self.assertEqual(mutated_lines(SOURCE, COPY, "x_double", 1), (2, ("\treturn n * 2",), ("\treturn n / 2",)))
self.assertEqual(mutated_lines(SOURCE, COPY, "xǁPtǁmoved", 1), (6, ("\tdef moved(self, by=1):",), ("\tdef moved(self, by=2):",)))
self.assertEqual(mutated_lines(SOURCE, COPY, "xǁPtǁmoved", 2), (7, ("\t\treturn self.x + by",), ("\t\treturn self.x - by",)))
def test_the_mutated_lines_run_from_the_first_line_that_differs_to_the_last(self):
source = "def total(a, b):\n\tlow = min(\n\t\ta,\n\t\tb,\n\t)\n\treturn low\n"
original = "def x_total__mutmut_orig(a, b):\n\tlow = min(\n\t\ta,\n\t\tb,\n\t)\n\treturn low\n"
for mutant, change in (
("\tlow = max(\n\t\tb,\n\t\ta,\n\t)\n\treturn low\n", (2, ("\tlow = min(", "\t\ta,", "\t\tb,"), ("\tlow = max(", "\t\tb,", "\t\ta,"))),
("\tlow = min(\n\t\ta,\n\t)\n\treturn low\n", (4, ("\t\tb,",), ())),
("\tlow = min(\n\t\ta,\n\t\tb,\n\t\tb,\n\t)\n\treturn low\n", (5, (), ("\t\tb,",))),
):
with self.subTest(mutant=mutant):
self.assertEqual(mutated_lines(source, original + "def x_total__mutmut_1(a, b):\n" + mutant, "x_total", 1), change)
def test_a_mutant_the_copy_lacks_or_a_copy_unlike_the_source_has_no_line(self):
self.assertIsNone(mutated_line(SOURCE, COPY, "x_double", 9))
self.assertIsNone(mutated_line(SOURCE.replace("n * 2", "n * 2 + 1"), COPY, "x_double", 1))
self.assertIsNone(mutated_line(SOURCE, COPY + "def x_double__mutmut_2(n):\n\treturn n * 2\n", "x_double", 2))
self.assertIsNone(mutated_lines(SOURCE, COPY, "x_double", 9))
self.assertIsNone(mutated_lines(SOURCE.replace("n * 2", "n * 2 + 1"), COPY, "x_double", 1))
self.assertIsNone(mutated_lines(SOURCE, COPY + "def x_double__mutmut_2(n):\n\treturn n * 2\n", "x_double", 2))
def test_a_key_the_source_does_not_define_has_no_line(self):
for key in ("x_double", "x_nope", "xǁNopeǁmoved", "xǁPtǁnope"):
with self.subTest(key):
self.assertIsNone(mutated_line("import os\n\n\nclass Pt:\n\tpass\n", COPY, key, 1))
self.assertIsNone(mutated_lines("import os\n\n\nclass Pt:\n\tpass\n", COPY, key, 1))
def test_a_mutated_line_is_found_in_the_function_or_method_its_key_names_among_others(self):
others = "import os\n\n\ndef triple(n):\n\treturn n * 3\n\n\nclass Q:\n\tdef moved(self, by=1):\n\t\treturn 0\n\n\n"
self.assertEqual(mutated_line(others + SOURCE, COPY, "x_double", 1), (14, "return n / 2"))
self.assertEqual(mutated_line(others + SOURCE, COPY, "xǁPtǁmoved", 2), (19, "return self.x - by"))
self.assertIsNone(mutated_line(SOURCE, "def broken(:\n", "x_double", 1))
self.assertEqual(mutated_lines(others + SOURCE, COPY, "x_double", 1), (14, ("\treturn n * 2",), ("\treturn n / 2",)))
self.assertEqual(mutated_lines(others + SOURCE, COPY, "xǁPtǁmoved", 2), (19, ("\t\treturn self.x + by",), ("\t\treturn self.x - by",)))
self.assertIsNone(mutated_lines(SOURCE, "def broken(:\n", "x_double", 1))
class MutmutTool(unittest.TestCase):
+101
View File
@@ -0,0 +1,101 @@
"""The bugs task-bench plants in Go: Gremlins' killed mutants, re-applied from its report, and what go test prints of the test
each fails."""
import os
import pathlib
import re
from failure import Failure
from mutate_changes import in_diff_tools
from mutate_changes.changed_lines import is_test
from mutate_changes.tool_process import Run
from task_bench.planted_mutant import Mutant
# What each of Gremlins v0.6.0's mutators writes in place of a token: `tokenMutations` in its internal/engine/mappings.go, under the
# names its report gives the mutators, from internal/mutator/mutator.go.
MUTATIONS: dict[str, dict[bytes, bytes]] = {
"ARITHMETIC_BASE": {b"+": b"-", b"*": b"/", b"/": b"*", b"%": b"*", b"-": b"+"},
"CONDITIONALS_BOUNDARY": {b">=": b">", b">": b">=", b"<=": b"<", b"<": b"<="},
"CONDITIONALS_NEGATION": {b"==": b"!=", b">=": b"<", b">": b"<=", b"<=": b">", b"<": b">=", b"!=": b"=="},
"INCREMENT_DECREMENT": {b"--": b"++", b"++": b"--"},
"INVERT_ASSIGNMENTS": {b"+=": b"-=", b"*=": b"/=", b"/=": b"*=", b"-=": b"+="},
"INVERT_BITWISE": {b"&": b"|", b"|": b"&", b"^": b"&", b"&^": b"&", b"<<": b">>", b">>": b"<<"},
"INVERT_BWASSIGN": {b"&=": b"|=", b"|=": b"&=", b"^=": b"&=", b"&^=": b"&=", b"<<=": b">>=", b">>=": b"<<="},
"INVERT_LOGICAL": {b"&&": b"||", b"||": b"&&"},
"INVERT_LOOPCTRL": {b"break": b"continue", b"continue": b"break"},
"INVERT_NEGATIVES": {b"-": b"+"},
"REMOVE_SELF_ASSIGNMENTS": dict.fromkeys((b"+=", b"&=", b"&^=", b"*=", b"|=", b"/=", b"%=", b"<<=", b">>=", b"-=", b"^="), b"="),
}
# What a test printed, as go test shows it: ` pick_test.go:42: got 3, want 4`. A failed assertion and a log line look the same.
PRINTED = re.compile(r"^( *)\S*_test\.go:\d+:(.*)$")
# The lines that say whose output follows: `=== RUN TestPick` with -v, and `--- FAIL: TestPick (0.00s)` with and without it.
TEST_MARK = re.compile(r"^( *)(?:=== (?:RUN|CONT|NAME)|--- (?:FAIL|PASS|SKIP):)\s+(\S+)")
FAILED_TEST = re.compile(r"^\s*--- FAIL: (\S+)", re.MULTILINE)
def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure:
"""The mutants in `files` that the tests of the tree at top kill, as Gremlins finds them there. One whose line and column hold
no token its mutator changes is left out.
Gremlins takes no list of files to mutate, only patterns to leave out, so it gets one for each other Go file of the tree."""
others = sorted(path for path in go_files(top) if path not in files)
found = in_diff_tools.gremlins_mutants(top, [argument for path in others for argument in ("--exclude-files", f"^{re.escape(path)}$")], run, jobs)
if isinstance(found, Failure):
return found
killed = [mutant for mutant in found if mutant.status == "KILLED" and mutant.path in files]
try:
lines = {path: pathlib.Path(top, path).read_bytes().split(b"\n") for path in {mutant.path for mutant in killed}}
except OSError as failure:
return Failure(f"could not read the files Gremlins mutated in {top}: {failure}")
return [mutant for reported in killed if (mutant := reapplied(reported, lines[reported.path]))]
def go_files(top: str) -> list[str]:
"""Each Go file under top that Gremlins would mutate, by its path from top."""
paths = (os.path.relpath(os.path.join(folder, name), top) for folder, _, names in os.walk(top) for name in names)
return [path for path in paths if path.endswith(".go") and not is_test(path)]
def reapplied(reported: in_diff_tools.Mutant, lines: list[bytes]) -> Mutant | None:
"""The mutant Gremlins reports by its mutator and the token it changed, at a line and a column in bytes, both from 1, as the
line it changes in a file of those lines. None where the place holds no token the mutator changes."""
if not (1 <= reported.line <= len(lines) and reported.column >= 1):
return None
line = lines[reported.line - 1]
rest = line[reported.column - 1:]
# The longest token first: `>=` holds `>`, and Gremlins names the mutant by the whole token.
token = max((token for token in MUTATIONS.get(reported.mutator, {}) if rest.startswith(token)), key=len, default=None)
if token is None:
return None
now = line[:reported.column - 1] + MUTATIONS[reported.mutator][token] + rest[len(token):]
return Mutant(reported.path, reported.line, f"{reported.path}:{reported.line}:{reported.column} {reported.mutator}", (line,), (now,))
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the failing assertion's message in go test's output, without the test's name, file or
line, so it says what goes wrong and not where. That is the last message of the first failed test that printed one, since a
test logs before it asserts; a test with a failed subtest is left out, since it fails with the subtest. None where no failed test printed a message, as on a panic, a build that broke or a passing run,
or where the message only names the test."""
lines = output.splitlines()
failed = set(FAILED_TEST.findall(output))
# A subtest is named `TestPick/empty_input`; a message may name the whole or the test it belongs to.
tests = {part for name in failed for part in (name, name.partition("/")[0])}
marks: list[tuple[int, str]] = []
last: dict[str, tuple[int, re.Match[str]]] = {}
for index, line in enumerate(lines):
if mark := TEST_MARK.match(line):
marks.append((len(mark[1]), mark[2]))
elif printed := PRINTED.match(line):
# A test's output is indented deeper than its mark, so a line after a subtest's may be its parent's.
test = next((name for indent, name in reversed(marks) if indent < len(printed[1])), None)
if test is not None and test in failed and not any(other.startswith(f"{test}/") for other in failed):
last[test] = index, printed
if not last:
return None
index, found = next(iter(last.values()))
indent = len(found[1])
# A message's later lines are indented deeper than its first.
later = lines[index + 1:]
ends = next((at for at, text in enumerate(later) if len(text) - len(text.lstrip(" ")) <= indent), len(later))
message = [text.strip() for text in (found[2], *later[:ends])]
kept = [text for text in message if text and "_test.go" not in text and not any(name in text for name in tests)]
return "\n".join(kept) or None
+26 -20
View File
@@ -11,11 +11,13 @@ prints. The head is --head, by default HEAD. The base is the merge base of the h
origin's as last fetched, else main or master. Where --base names the head's own commit, the bench runs the head against itself.
No model judges anything: the bench runs programs, and reads Haiku's own stream.
- Plant. It copies the tree at the base and runs Gremlins there, as `gremlins unleash`, over the Go files that hold the places
`larv-review places` prints, the ones the comprehension seats found hardest. It takes the mutants the tests kill in the order
--seed sets, 1 by default, until --bugs of them, 5 by default, have become bugs. A mutant becomes a bug where its line stands
unchanged at the head, and where, planted at each side, a test fails and prints a message that says more than the test's name.
Any other mutant is passed over, so a change to the very line of a bug is not benched. Go is the one language so far.
- Plant. It copies the tree at the base and runs a mutation tool there, over the files that hold the places `larv-review places`
prints, the ones the comprehension seats found hardest: Gremlins over the Go files, as `gremlins unleash`, and mutmut 3 over
the Python files, as `mutmut run`. It takes the mutants the tests kill in the order --seed sets, 1 by default, until --bugs of
them, 5 by default, have become bugs. A mutant becomes a bug where the lines it changes stand unchanged at the head, and where,
planted at each side, a test fails and prints a message that says more than the test's name. Any other mutant is passed over,
so a change to the very lines of a bug is not benched. The message is the one `go test` prints for a Go file, and pytest for
a Python file. Go and Python are the languages so far.
- Run. Haiku fixes each bug --runs times at each side, 5 by default, the sides in turn. A fix starts from a copy of that side's
tree with the bug in it, committed once, so git doesn't show which line the bug is on. In the copy, in a container, `claude -p
--strict-mcp-config --disable-slash-commands --no-session-persistence --model claude-haiku-5-5 --effort low` works with every
@@ -28,13 +30,16 @@ No model judges anything: the bench runs programs, and reads Haiku's own stream.
--image is the project's development image, such as golang:1.27.4. The bench adds Claude Code to it, as its installer installs it,
so the image needs curl and bash; the result names the version. Haiku works in that image. So does --test: sh runs that text at
the copy's top, with no network, so the image must hold what the tests would otherwise download.
--prefix is shell text that runs Gremlins, on the host, as mutate-changes' --prefix does: sh runs `<prefix> "$@"` in the copy of the
base, which $PWD names, with `gremlins unleash ...` as "$@". Without it, the bench runs the `gremlins` on the host's PATH. For
example:
--prefix is shell text that runs the mutation tool, on the host, as mutate-changes' --prefix does: sh runs `<prefix> "$@"` with
the tool's command as "$@", such as `gremlins unleash ...` or `mutmut run ...`. Gremlins runs in the copy of the base, and mutmut
in a copy of the folder there that holds its settings; $PWD names either. Without --prefix, the bench runs the `gremlins` or
the `mutmut` on the host's PATH. For example, for Go and then for Python:
docker run --rm --memory 16g --memory-swap 16g -v "$PWD:$PWD" -w "$PWD" golang:1.27.4 \
sh -c 'shift; exec go run github.com/go-gremlins/gremlins/cmd/gremlins@v0.6.0 "$@"' sh
uvx --python "$(command -v python3)" --with pytest==9.2.0 --from "mutmut>=3,<4"
--tasks features benches features instead of bugs; --tasks bugs is the default. The features are the folders in the folder the
project's config names as `bench-tasks`, in the order of their names. Each holds:
- `spec.md`, all that Haiku is told of the feature;
@@ -46,8 +51,8 @@ works in a copy of the side's tree without the `bench-tasks` folder. A build pas
side's tree with each file that is no test as Haiku left it, and the acceptance tests put over that. The reference patch is
checked the same way, so a test or a `testdata` file it adds doesn't count either. Keep the folder where the project's own test
command doesn't find the acceptance tests, which fail by design: outside the checkout, or in a folder the test runner skips, as Go
skips `testdata`. The table then has a row per feature and side, and `-` for the reads. Gremlins
doesn't run, so --seed, --bugs and --prefix don't go with it.
skips `testdata`. The table then has a row per feature and side, and `-` for the reads. No mutation tool
runs, so --seed, --bugs and --prefix don't go with it.
--tasks data-sources benches adding a data source, for a project that imports what others publish. Each task is a folder in
`bench-tasks` that holds a feature's three parts and `generate-register`, an executable script; --tasks features leaves such
@@ -97,8 +102,8 @@ Each bench empties its own folder first, and removes the folder every earlier be
not, unless a bench or a gather is using it. So gather a bench before the next one starts.
Exit 1, saying why, on an unknown or repeated argument, a missing --image or --test, a --seed, --bugs or --runs that is no whole
number from 1, a --tasks that is none of bugs, features and data-sources, or no token; and where git, docker or Gremlins fails,
the seats' places don't name any Go file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
number from 1, a --tasks that is none of bugs, features and data-sources, or no token; and where git, docker or the mutation tool
fails, the seats' places don't name any Go or Python file, the tests fail at a side without a bug, or no mutant becomes a bug. With --tasks
features or data-sources it exits 1 on a --seed, --bugs or --prefix; where no config names the checkout or its config sets no
`bench-tasks`, or the folder holds no task of that kind, one that lacks a part, or a `generate-register` that is no executable
file, each before docker runs; and where the tests fail at a side without the acceptance tests, or no task counts. Where the
@@ -123,7 +128,8 @@ import typing
import uuid
from task_bench.tasks import Asked, Bench, BUG, check_made, committed, Kind, KINDS, on_disk, Planned, Task, tests_in_copy
from task_bench.plant import bug_at_sides, drawn, killed_mutants, Mutant, place_files, task_text
from task_bench.plant import drawn, killed_mutants, place_files, task_text
from task_bench.planted_mutant import bug_at_sides, Mutant
from claude_code.reply import Claude
from task_bench.bench_folder import clear_left, held
from task_bench.runs import closed, Containers, docker_cli, fix_attempted, MEMORY_MIB, opened, ran_tests, TimedOut, TOKEN, WORK
@@ -151,7 +157,7 @@ COUNTS = {"--bugs": "5", "--runs": "5", "--seed": "1"}
TASKS = "--tasks"
# Opens the report's last line, which names the bench's folder.
KEPT = "The digest, and each run's result and stream, until `task-bench gather` files plan items from them or the next bench starts: "
# The options only a bench of bugs takes: two choose the bugs to plant, and --prefix runs Gremlins.
# The options only a bench of bugs takes: two choose the bugs to plant, and --prefix runs the mutation tool.
OF_BUGS = ("--seed", "--bugs", "--prefix")
@@ -162,7 +168,7 @@ class Fixes(typing.NamedTuple):
def main(argv: list[str], env: typing.Mapping[str, str], read: typing.Callable[[pathlib.Path], str | Failure] = read_places, claude: Claude = run_claude) -> int:
"""Runs task-bench with the arguments argv; git, docker and Gremlins run in the environment env, `read` reads what
"""Runs task-bench with the arguments argv; git, docker and the mutation tool run in the environment env, `read` reads what
`larv-review places` prints for the checkout, and `claude` runs the claude that gathers."""
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
@@ -288,11 +294,11 @@ def features_planner(features: Features, checkout: str, trees: dict[Side, str])
def bugs_planner(given: dict[str, str], env: typing.Mapping[str, str], places: str, base: str) -> typing.Callable[[Bench], Planned | Failure] | Failure:
"""What plans a bench of bugs: of the mutants the tests kill in the Go files of the tree at base that hold a place in places,
those --seed draws first become bugs, until --bugs of them have."""
"""What plans a bench of bugs: of the mutants the tests kill in the Go and Python files of the tree at base that hold a place
in places, those --seed draws first become bugs, until --bugs of them have."""
files = [path for path in place_files(places) if pathlib.Path(base, path).is_file()]
if not files:
return Failure("The places the seats found hard don't name any Go file that the base holds, so there is nowhere to plant a bug.")
return Failure("The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug.")
run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg)
mutants = killed_mutants(base, files, run, CPUS_PER_SLOT)
return mutants if isinstance(mutants, Failure) else functools.partial(planted_tasks, mutants=mutants, seed=int(given["--seed"]), bugs=int(given["--bugs"]))
@@ -438,7 +444,7 @@ def planted(bench: Bench, number: int, mutant: Mutant) -> Task | Failure | None:
if message is None or isinstance(message, Failure):
return message
trees[side], messages[side] = str(tree), message
return Task(number, f"{mutant.path}:{mutant.line}:{mutant.column} {mutant.mutator}", trees, messages, file=mutant.path)
return Task(number, mutant.name, trees, messages, file=mutant.path)
def planted_tree(bench: Bench, side: Side, tree: pathlib.Path, path: str, changed: bytes) -> str | Failure | None:
@@ -456,7 +462,7 @@ def planted_tree(bench: Bench, side: Side, tree: pathlib.Path, path: str, change
return None
if isinstance(ran, Failure):
return ran
message = task_text(ran.output)
message = task_text(path, ran.output)
if message is None:
return None
return committed(bench.git, str(tree)) or message
+42 -129
View File
@@ -1,154 +1,67 @@
"""Pick the bugs task-bench plants: Gremlins' killed mutants in the Go files that hold the places the comprehension seats found hard,
re-applied from its report, each with the failing assertion's message that tells Haiku what goes wrong."""
import os
"""Pick the bugs task-bench plants: the mutants the tests kill in the files that hold the places the comprehension seats found
hard, each with the failing test's message that tells Haiku what goes wrong. Each language has a module that runs its mutation
tool and reads its test runner's output."""
import random
import re
import typing
from failure import Failure
from mutate_changes.in_diff_tools import gremlins_mutants
from mutate_changes.changed_lines import is_test
from mutate_changes.tool_process import Run
from task_bench.figures import Side
from task_bench import go_bugs, python_bugs
from task_bench.planted_mutant import Mutant
# A place as `larv-review places` prints it: `<path>:<line>` in backticks.
PLACE = re.compile(r"`([^`\s:]+):\d+`")
# What each of Gremlins v0.6.0's mutators writes in place of a token: `tokenMutations` in its internal/engine/mappings.go, under the
# names its report gives the mutators, from internal/mutator/mutator.go.
MUTATIONS: dict[str, dict[bytes, bytes]] = {
"ARITHMETIC_BASE": {b"+": b"-", b"*": b"/", b"/": b"*", b"%": b"*", b"-": b"+"},
"CONDITIONALS_BOUNDARY": {b">=": b">", b">": b">=", b"<=": b"<", b"<": b"<="},
"CONDITIONALS_NEGATION": {b"==": b"!=", b">=": b"<", b">": b"<=", b"<=": b">", b"<": b">=", b"!=": b"=="},
"INCREMENT_DECREMENT": {b"--": b"++", b"++": b"--"},
"INVERT_ASSIGNMENTS": {b"+=": b"-=", b"*=": b"/=", b"/=": b"*=", b"-=": b"+="},
"INVERT_BITWISE": {b"&": b"|", b"|": b"&", b"^": b"&", b"&^": b"&", b"<<": b">>", b">>": b"<<"},
"INVERT_BWASSIGN": {b"&=": b"|=", b"|=": b"&=", b"^=": b"&=", b"&^=": b"&=", b"<<=": b">>=", b">>=": b"<<="},
"INVERT_LOGICAL": {b"&&": b"||", b"||": b"&&"},
"INVERT_LOOPCTRL": {b"break": b"continue", b"continue": b"break"},
"INVERT_NEGATIVES": {b"-": b"+"},
"REMOVE_SELF_ASSIGNMENTS": dict.fromkeys((b"+=", b"&=", b"&^=", b"*=", b"|=", b"/=", b"%=", b"<<=", b">>=", b"-=", b"^="), b"="),
}
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)
# What a test printed, as go test shows it: ` pick_test.go:42: got 3, want 4`. A failed assertion and a log line look the same.
PRINTED = re.compile(r"^( *)\S*_test\.go:\d+:(.*)$")
# The lines that say whose output follows: `=== RUN TestPick` with -v, and `--- FAIL: TestPick (0.00s)` with and without it.
TEST_MARK = re.compile(r"^( *)(?:=== (?:RUN|CONT|NAME)|--- (?:FAIL|PASS|SKIP):)\s+(\S+)")
FAILED_TEST = re.compile(r"^\s*--- FAIL: (\S+)", re.MULTILINE)
class Mutant(typing.NamedTuple):
"""A mutant the project's tests killed, as Gremlins reports it: the mutator and the token it changed, by its line and its column in bytes, both from 1."""
class Language(typing.NamedTuple):
"""A language the bench plants bugs in, by its files' suffixes. killed takes a tree's top, the files to mutate there, what
runs the mutation tool and how many tests it may run at once, and returns the mutants the tree's tests kill. told takes the
test command's output over a planted bug, and returns the failing test's message, or None where it printed none."""
path: str
line: int
column: int
mutator: str
name: str
suffixes: tuple[str, ...]
killed: typing.Callable[[str, list[str], Run, int], list[Mutant] | Failure]
told: typing.Callable[[str], str | None]
LANGUAGES = (
Language("Go", (".go",), go_bugs.killed_mutants, go_bugs.task_text),
Language("Python", (".py",), python_bugs.killed_mutants, python_bugs.task_text),
)
def language_of(path: str) -> Language | None:
return next((language for language in LANGUAGES if path.endswith(language.suffixes)), None)
def place_files(places: str) -> list[str]:
"""The Go files that hold a place in what `larv-review places` prints, test files left out, in the order of their paths."""
return sorted({path for path in PLACE.findall(places) if path.endswith(".go") and not is_test(path)})
"""The files that hold a place in what `larv-review places` prints and are in a language of LANGUAGES, test files left out, in
the order of their paths."""
return sorted({path for path in PLACE.findall(places) if language_of(path) and not is_test(path)})
def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure:
"""The mutants in `files` that the tests of the tree at top kill, as Gremlins finds them there.
Gremlins takes no list of files to mutate, only patterns to leave out, so it gets one for each other Go file of the tree."""
others = sorted(path for path in go_files(top) if path not in files)
found = gremlins_mutants(top, [argument for path in others for argument in ("--exclude-files", f"^{re.escape(path)}$")], run, jobs)
if isinstance(found, Failure):
return found
return [Mutant(mutant.path, mutant.line, mutant.column, mutant.mutator) for mutant in found if mutant.status == "KILLED" and mutant.path in files]
def go_files(top: str) -> list[str]:
"""Each Go file under top that Gremlins would mutate, by its path from top."""
paths = (os.path.relpath(os.path.join(folder, name), top) for folder, _, names in os.walk(top) for name in names)
return [path for path in paths if path.endswith(".go") and not is_test(path)]
"""The mutants in `files`, which place_files named, that the tests of the tree at top kill: each language's tool runs over
the files in that language."""
killed: list[Mutant] = []
for language in LANGUAGES:
own = [path for path in files if language_of(path) is language]
found = language.killed(top, own, run, jobs) if own else []
if isinstance(found, Failure):
return found
killed += found
return killed
def drawn(mutants: list[Mutant], seed: int) -> list[Mutant]:
"""The mutants in the order the seed draws them, whatever order Gremlins listed them in."""
"""The mutants in the order the seed draws them, whatever order the tools listed them in."""
return random.Random(seed).sample(sorted(set(mutants)), len(set(mutants)))
def mutated(source: bytes, mutant: Mutant) -> bytes | None:
"""A file's source with the mutant applied, or None where its line and column hold no token its mutator changes."""
lines = source.split(b"\n")
if not 1 <= mutant.line <= len(lines):
return None
line = lines[mutant.line - 1]
rest = line[mutant.column - 1:]
# The longest token first: `>=` holds `>`, and Gremlins names the mutant by the whole token.
token = max((token for token in MUTATIONS.get(mutant.mutator, {}) if rest.startswith(token)), key=len, default=None)
if token is None:
return None
lines[mutant.line - 1] = line[:mutant.column - 1] + MUTATIONS[mutant.mutator][token] + rest[len(token):]
return b"\n".join(lines)
def bug_at_sides(mutant: Mutant, diff: str, sources: dict[Side, bytes | None]) -> dict[Side, bytes] | None:
"""The file of mutant with the bug in it, at the base and at the head. None where the mutant doesn't become a bug at one side
or the other.
sources holds the file at each side, None where the side lacks it; diff is the file's diff from base to head.
The bug is the same change to the same line at both sides, so only the code around it differs between them."""
at_head = line_at_head(diff, mutant.line)
if at_head is None:
return None
bugs: dict[Side, bytes] = {}
placings: tuple[tuple[Side, Mutant], ...] = (("base", mutant), ("head", mutant._replace(line=at_head)))
for side, placed in placings:
changed = None if (source := sources[side]) is None else mutated(source, placed)
if changed is None:
return None
bugs[side] = changed
return bugs
def line_at_head(diff: str, line: int) -> int | None:
"""The number at the head of a file's line `line` at the base, or None where the head changed or removed that line.
diff is `git diff -U0 <base> <head> -- <file>`, so each hunk holds changed lines only."""
moved = 0
for old_start, old_count, new_start, new_count in ((int(a), int(b or 1), int(c), int(d or 1)) for a, b, c, d in HUNK.findall(diff)):
# A hunk that only adds lines names the line it adds them after. One that only removes lines names the line the gap follows.
old_end = old_start + old_count if old_count else old_start + 1
new_end = new_start + new_count if new_count else new_start + 1
if old_count and old_start <= line < old_end:
return None
if line >= old_end:
moved = new_end - old_end
return line + moved
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the failing assertion's message in go test's output, without the test's name, file or
line, so it says what goes wrong and not where. That is the last message of the first failed test that printed one, since a
test logs before it asserts; a test with a failed subtest is left out, since it fails with the subtest. None where no failed test printed a message, as on a panic, a build that broke or a passing run,
or where the message only names the test."""
lines = output.splitlines()
failed = set(FAILED_TEST.findall(output))
# A subtest is named `TestPick/empty_input`; a message may name the whole or the test it belongs to.
tests = {part for name in failed for part in (name, name.partition("/")[0])}
marks: list[tuple[int, str]] = []
last: dict[str, tuple[int, re.Match[str]]] = {}
for index, line in enumerate(lines):
if mark := TEST_MARK.match(line):
marks.append((len(mark[1]), mark[2]))
elif printed := PRINTED.match(line):
# A test's output is indented deeper than its mark, so a line after a subtest's may be its parent's.
test = next((name for indent, name in reversed(marks) if indent < len(printed[1])), None)
if test is not None and test in failed and not any(other.startswith(f"{test}/") for other in failed):
last[test] = index, printed
if not last:
return None
index, found = next(iter(last.values()))
indent = len(found[1])
# A message's later lines are indented deeper than its first.
later = lines[index + 1:]
ends = next((at for at, text in enumerate(later) if len(text) - len(text.lstrip(" ")) <= indent), len(later))
message = [text.strip() for text in (found[2], *later[:ends])]
kept = [text for text in message if text and "_test.go" not in text and not any(name in text for name in tests)]
return "\n".join(kept) or None
def task_text(path: str, output: str) -> str | None:
"""What Haiku is told of a bug planted in the file at path, one place_files named: the failing test's message in output,
what the test command printed, as the file's language reads it. None where the output holds no such message."""
language = language_of(path)
return language.told(output) if language else None
+65
View File
@@ -0,0 +1,65 @@
"""A mutant task-bench plants as a bug, and how it is re-applied at the base and at the head: as the same change to the same lines."""
import re
import typing
from task_bench.figures import Side
HUNK = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@", re.MULTILINE)
class Mutant(typing.NamedTuple):
"""A mutant the project's tests killed, as the lines it changes in the tree its tool ran in: the number of the first, from 1,
those lines as the tree has them, and what the mutant has in their place. name is what the report calls the bug it becomes:
the path and line, then the tool's own name of the mutant."""
path: str
line: int
name: str
was: tuple[bytes, ...]
now: tuple[bytes, ...]
def mutated(source: bytes, mutant: Mutant) -> bytes | None:
"""A file's source with the mutant applied, or None where its line doesn't start the lines the mutant changes."""
lines = source.split(b"\n")
first = mutant.line - 1
if not 0 <= first <= len(lines) or tuple(lines[first:first + len(mutant.was)]) != mutant.was:
return None
lines[first:first + len(mutant.was)] = mutant.now
return b"\n".join(lines)
def bug_at_sides(mutant: Mutant, diff: str, sources: dict[Side, bytes | None]) -> dict[Side, bytes] | None:
"""The file of mutant with the bug in it, at the base and at the head. None where the mutant doesn't become a bug at one side
or the other.
sources holds the file at each side, None where the side lacks it; diff is the file's diff from base to head.
The bug is the same change to the same lines at both sides, so only the code around it differs between them."""
at_head = line_at_head(diff, mutant.line)
if at_head is None:
return None
bugs: dict[Side, bytes] = {}
placings: tuple[tuple[Side, Mutant], ...] = (("base", mutant), ("head", mutant._replace(line=at_head)))
for side, placed in placings:
changed = None if (source := sources[side]) is None else mutated(source, placed)
if changed is None:
return None
bugs[side] = changed
return bugs
def line_at_head(diff: str, line: int) -> int | None:
"""The number at the head of a file's line `line` at the base, or None where the head changed or removed that line.
diff is `git diff -U0 <base> <head> -- <file>`, so each hunk holds changed lines only."""
moved = 0
for old_start, old_count, new_start, new_count in ((int(a), int(b or 1), int(c), int(d or 1)) for a, b, c, d in HUNK.findall(diff)):
# A hunk that only adds lines names the line it adds them after. One that only removes lines names the line the gap follows.
old_end = old_start + old_count if old_count else old_start + 1
new_end = new_start + new_count if new_count else new_start + 1
if old_count and old_start <= line < old_end:
return None
if line >= old_end:
moved = new_end - old_end
return line + moved
+59
View File
@@ -0,0 +1,59 @@
"""The bugs task-bench plants in Python: mutmut's killed mutants, re-applied from the copy of each file it writes, and what pytest
prints of the test each fails."""
import re
from failure import Failure
from mutate_changes.mutmut_tool import killed_by_mutmut
from mutate_changes.tool_process import Run
from task_bench.planted_mutant import Mutant
# pytest's report of the failed tests, in its default form or with --tb=short: under this heading, a section per test.
FAILURES = re.compile(r"^=+ FAILURES =+$", re.MULTILINE)
# A section's heading, such as `_____ test_pick _____` or `_____ PickTest.test_empty _____`. A traceback's `_ _ _ _` between
# two frames is none.
SECTION = re.compile(r"^_+ (?!_)(.+?) _+$")
# The heading of what follows the failed tests, such as `===== short test summary info =====`.
NEXT_PART = re.compile(r"^=+ .+ =+$")
# A line of the error a test failed with: `E assert 3 == 4`, and `E + where 3 = pick([])` below it.
ERROR = re.compile(r"^E(?: (.*)|\s*)$")
# The heading of what a failed test printed, such as `----- Captured stdout call -----`, which may hold a line that looks like an error's.
CAPTURED = re.compile(r"^-+ Captured .+ -+$")
TEST_FILE = re.compile(r"\btest_\w*\.py|\w+_test\.py|\bconftest\.py")
def killed_mutants(top: str, files: list[str], run: Run, jobs: int) -> list[Mutant] | Failure:
"""The mutants in `files` that the tests of the tree at top kill, as mutmut finds them there."""
killed = killed_by_mutmut(top, files, run, jobs)
if isinstance(killed, Failure):
return killed
return [Mutant(path, change.line, f"{path}:{change.line} {name.rpartition('.')[2]}", encoded(change.was), encoded(change.now)) for path, name, change in killed]
def encoded(lines: tuple[str, ...]) -> tuple[bytes, ...]:
return tuple(line.encode() for line in lines)
def task_text(output: str) -> str | None:
"""What Haiku is told of a planted bug: the error of the first failed test that has one in pytest's output, without the test's
name or file, so it says what goes wrong and not which test shows it. None where pytest reports no failed test with an
error, as on a passing run, a file that fails to import or a run with --tb=no, or where the error only names the test."""
failures = FAILURES.split(output, maxsplit=1)
if len(failures) < 2:
return None
test, captured = "", False
error: list[str] = []
for line in failures[1].splitlines():
heading = SECTION.match(line)
if NEXT_PART.match(line) or heading and error:
break
if heading:
test, captured = heading[1], False
elif CAPTURED.match(line):
captured = True
elif test and not captured and (said := ERROR.match(line)):
error.append((said[1] or "").strip())
# A heading names a method after its class, and a parametrized test or a subtest before its `[case]` or ` (case)`.
whole = re.split(r"[\s\[(]", test)[0]
names = {whole, *whole.split(".")} - {""}
kept = [text for text in error if text and not TEST_FILE.search(text) and not any(name in text for name in names)]
return "\n".join(kept) or None
+171
View File
@@ -0,0 +1,171 @@
"""task-bench's Go planter: which files Gremlins mutates, how its mutants are re-applied and what go test's output tells Haiku."""
import json
import tempfile
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.go_bugs import go_files, killed_mutants, reapplied, task_text
from task_bench.planted_mutant import Mutant
from failure import Failure
from mutate_changes import in_diff_tools
from mutate_changes.tool_process import Ran
# go test's report of an assertion that failed in a subtest, then of one whose message runs over two lines.
GO_FAILURE = """ok \texample.com/calc/cli\t0.004s
--- FAIL: TestPick (0.00s)
--- FAIL: TestPick/empty_input (0.00s)
pick_test.go:42: Pick() = 3,
want 4
pick_test.go:50: got 1 row, want 2
FAIL
FAIL\texample.com/calc/render\t0.012s
FAIL
"""
# testify prints the test's file and name inside the message.
TESTIFY_FAILURE = """--- FAIL: TestTotal (0.00s)
total_test.go:12:
\tError Trace:\t/work/total_test.go:12
\tError: \tNot equal:
\t \texpected: 1
\t \tactual : 2
\tTest: \tTestTotal
FAIL
"""
PANIC = """--- FAIL: TestPick (0.00s)
panic: runtime error: index out of range [3] with length 3 [recovered]
FAIL\texample.com/calc/render\t0.012s
"""
class ReappliedTest(unittest.TestCase):
SOURCE = b"package calc\n\nfunc f(a, b int) int {\n\tif a >= b {\n\t\treturn a - b\n\t}\n\tn -= 1\n\treturn a\n}\n"
def planted(self, line: int, column: int, mutator: str, source: bytes = SOURCE) -> str | None:
found = reapplied(in_diff_tools.Mutant("calc.go", line, column, "KILLED", mutator), source.split(b"\n"))
return None if found is None else b"\n".join(found.now).decode()
def test_swaps_the_token_at_the_line_and_column_as_gremlins_mutator_does(self):
self.assertEqual(self.planted(4, 7, "CONDITIONALS_NEGATION"), "\tif a < b {")
self.assertEqual(self.planted(4, 7, "CONDITIONALS_BOUNDARY"), "\tif a > b {")
self.assertEqual(self.planted(5, 12, "ARITHMETIC_BASE"), "\t\treturn a + b")
self.assertEqual(self.planted(7, 4, "INVERT_ASSIGNMENTS"), "\tn += 1")
self.assertEqual(self.planted(7, 4, "REMOVE_SELF_ASSIGNMENTS"), "\tn = 1")
def test_names_the_mutant_by_its_place_and_mutator_and_holds_the_line_it_changes(self):
found = reapplied(in_diff_tools.Mutant("calc.go", 5, 12, "KILLED", "ARITHMETIC_BASE"), self.SOURCE.split(b"\n"))
self.assertEqual(found, Mutant("calc.go", 5, "calc.go:5:12 ARITHMETIC_BASE", (b"\t\treturn a - b",), (b"\t\treturn a + b",)))
def test_counts_the_column_in_bytes_as_go_does(self):
self.assertEqual(self.planted(1, 15, "CONDITIONALS_NEGATION", 'x := "åäö" == y\n'.encode()), 'x := "åäö" != y')
def test_is_none_where_the_place_holds_no_token_of_the_mutator(self):
self.assertIsNone(self.planted(4, 6, "CONDITIONALS_NEGATION"))
self.assertIsNone(self.planted(5, 12, "CONDITIONALS_NEGATION"))
self.assertIsNone(self.planted(40, 1, "ARITHMETIC_BASE"))
self.assertIsNone(self.planted(0, 1, "ARITHMETIC_BASE"))
self.assertIsNone(self.planted(5, 0, "ARITHMETIC_BASE", b"x\n\n\n\n\t\treturn a -"))
self.assertIsNone(self.planted(4, 70, "ARITHMETIC_BASE"))
self.assertIsNone(self.planted(4, 7, "A_MUTATOR_GREMLINS_ADDS_LATER"))
def test_takes_the_longest_token_at_the_column(self):
self.assertEqual(self.planted(1, 3, "CONDITIONALS_BOUNDARY", b"a >= b"), "a > b")
self.assertEqual(self.planted(1, 3, "INVERT_BITWISE", b"a &^ b"), "a & b")
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_message_without_the_tests_name_file_or_line(self):
self.assertEqual(task_text(GO_FAILURE), "Pick() = 3,\nwant 4")
def test_leaves_out_each_line_that_names_the_test_or_its_file(self):
self.assertEqual(task_text(TESTIFY_FAILURE), "Error: \tNot equal:\nexpected: 1\nactual : 2")
def test_is_none_where_no_assertion_failed_as_on_a_panic_or_a_passing_run(self):
self.assertIsNone(task_text(PANIC))
self.assertIsNone(task_text("ok \texample.com/calc\t0.004s\n"))
def test_takes_the_message_of_a_test_that_failed_not_what_a_passing_test_logged(self):
output = "=== RUN TestServer\n server_test.go:12: listening on 127.0.0.1:0\n--- PASS: TestServer (0.00s)\n=== RUN TestPick\n pick_test.go:42: got 3, want 4\n--- FAIL: TestPick (0.00s)\nFAIL\n"
self.assertEqual(task_text(output), "got 3, want 4")
def test_takes_the_last_message_of_the_failed_test_since_a_test_logs_before_it_asserts(self):
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:40: input [1 2 3]\n pick_test.go:42: got 3, want 4\nFAIL\n"), "got 3, want 4")
def test_takes_the_first_failed_test_that_has_a_message(self):
output = "--- FAIL: TestPick (0.00s)\n --- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: got 3\n--- FAIL: TestLast (0.00s)\n pick_test.go:50: got 5\nFAIL\n"
self.assertEqual(task_text(output), "got 3")
def test_a_line_printed_before_any_tests_mark_is_no_tests_message(self):
self.assertEqual(task_text(" setup_test.go:3: starting\n--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\nFAIL\n"), "got 3")
self.assertIsNone(task_text(" setup_test.go:3: starting\n--- FAIL: TestPick (0.00s)\nFAIL\n"))
def test_takes_the_failed_subtests_message_over_what_its_parent_logged_before_it(self):
output = "--- FAIL: TestPick (0.00s)\n pick_test.go:10: three cases\n --- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: got 3\nFAIL\n"
self.assertEqual(task_text(output), "got 3")
def test_is_none_where_only_passing_tests_logged(self):
self.assertIsNone(task_text("=== RUN TestServer\n server_test.go:12: listening\n--- PASS: TestServer (0.00s)\nPASS\n"))
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: TestPick failed\nFAIL\n"))
def test_a_message_ends_at_the_next_line_indented_as_its_first(self):
output = "--- FAIL: TestPick/empty_input (0.00s)\n pick_test.go:42: got 3\n want 4\n--- FAIL: TestLast (0.00s)\n pick_test.go:50: got 5\n"
self.assertEqual(task_text(output), "got 3\nwant 4")
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\n a line the test logged\n"), "got 3")
def test_a_message_runs_to_the_end_of_the_output(self):
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\n want 4"), "got 3\nwant 4")
def test_a_message_may_name_a_part_of_a_subtests_name_that_is_no_test(self):
output = "--- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: empty input: got 3\n in TestPick\n in TestPick/empty\n"
self.assertEqual(task_text(output), "empty input: got 3")
class KilledMutantsTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
for path in ("calc.go", "calc_test.go", "render/pick.go", "render/a+b.go", "render/notes.md", "cli/main.go"):
(self.top / path).parent.mkdir(parents=True, exist_ok=True)
(self.top / path).write_text("package x\n\n\nfunc f() int {\n\treturn a + b\n}\n")
self.ran: list[tuple[list[str], str]] = []
def gremlins(self, report: dict | None, code: int = 0):
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd))
if report is not None:
pathlib.Path(cwd, argv[argv.index("--output") + 1]).write_text(json.dumps(report))
return Ran(code, "gremlins said so")
return run
def test_names_each_go_file_gremlins_would_mutate_by_its_path_from_the_top(self):
self.assertEqual(sorted(go_files(str(self.top))), ["calc.go", "cli/main.go", "render/a+b.go", "render/pick.go"])
def test_has_gremlins_leave_out_every_other_go_file_by_its_whole_path(self):
killed_mutants(str(self.top), ["render/pick.go"], self.gremlins({"files": []}), 3)
argv, cwd = self.ran[0]
self.assertEqual(cwd, str(self.top))
self.assertEqual(argv[:8], ["gremlins", "unleash", "--exclude-files", r"^calc\.go$", "--exclude-files", r"^cli/main\.go$", "--exclude-files", r"^render/a\+b\.go$"])
self.assertEqual((argv[8], argv[10:]), ("--output", ["--workers", "3"]))
def test_keeps_the_killed_mutants_of_the_files_asked_for_whose_place_holds_the_mutators_token_as_the_line_each_changes(self):
report = {"files": [
{"file_name": "render/pick.go", "mutations": [{"line": 5, "column": 11, "status": "KILLED", "type": "ARITHMETIC_BASE"}, {"line": 4, "column": 1, "status": "KILLED", "type": "ARITHMETIC_BASE"}, {"line": 5, "column": 2, "status": "LIVED", "type": "INVERT_LOGICAL"}, {"line": 6, "column": 2, "status": "NOT COVERED", "type": "INVERT_LOGICAL"}]},
{"file_name": "calc.go", "mutations": [{"line": 1, "column": 1, "status": "KILLED", "type": "ARITHMETIC_BASE"}]},
]}
self.assertEqual(killed_mutants(str(self.top), ["render/pick.go"], self.gremlins(report), 3), [Mutant("render/pick.go", 5, "render/pick.go:5:11 ARITHMETIC_BASE", (b"\treturn a + b",), (b"\treturn a - b",))])
def test_a_gremlins_that_fails_is_a_failure_with_what_it_printed(self):
found = killed_mutants(str(self.top), ["render/pick.go"], self.gremlins(None, code=1), 3)
self.assertIsInstance(found, Failure)
self.assertIn("gremlins said so", found.reason)
if __name__ == "__main__":
unittest.main()
+44 -191
View File
@@ -1,15 +1,15 @@
"""task-bench's planter: which files it mutates, which mutants it draws, how it re-applies one and what it tells Haiku."""
import json
"""task-bench's planter: which files it mutates, which language's tool finds the mutants of each, which mutants it draws and whose test output it reads."""
import pathlib
import sys
import tempfile
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.plant import bug_at_sides, drawn, go_files, killed_mutants, line_at_head, Mutant, mutated, place_files, task_text
from task_bench import plant
from task_bench.plant import drawn, killed_mutants, Language, LANGUAGES, place_files, task_text
from task_bench.planted_mutant import Mutant
from failure import Failure
from mutate_changes.tool_process import Ran
PLACES = """## 2026-11-19T22:33:15Z, PR #646 at a357cc7b
@@ -25,219 +25,72 @@ Mid A, hardest first:
- Locality: `internal/render/pick.go:354` `resumed`: a loop
- Locality: `data-import/geo.py:3` `load`: a long chain
"""
# go test's report of an assertion that failed in a subtest, then of one whose message runs over two lines.
GO_FAILURE = """ok \texample.com/calc/cli\t0.004s
--- FAIL: TestPick (0.00s)
--- FAIL: TestPick/empty_input (0.00s)
pick_test.go:42: Pick() = 3,
want 4
pick_test.go:50: got 1 row, want 2
FAIL
FAIL\texample.com/calc/render\t0.012s
FAIL
"""
# testify prints the test's file and name inside the message.
TESTIFY_FAILURE = """--- FAIL: TestTotal (0.00s)
total_test.go:12:
\tError Trace:\t/work/total_test.go:12
\tError: \tNot equal:
\t \texpected: 1
\t \tactual : 2
\tTest: \tTestTotal
FAIL
"""
PANIC = """--- FAIL: TestPick (0.00s)
panic: runtime error: index out of range [3] with length 3 [recovered]
FAIL\texample.com/calc/render\t0.012s
"""
def mutant(path: str, line: int = 1) -> Mutant:
return Mutant(path, line, f"{path}:{line} x", (b"a + b",), (b"a - b",))
class PlaceFilesTest(unittest.TestCase):
def test_names_each_go_file_that_holds_a_place_once_and_no_test_file_or_other_language(self):
self.assertEqual(place_files(PLACES), ["cli/report.go", "internal/render/pick.go"])
def test_names_each_go_and_python_file_that_holds_a_place_once_and_no_test_file_or_other_language(self):
self.assertEqual(place_files(PLACES), ["cli/report.go", "data-import/geo.py", "internal/render/pick.go"])
def test_names_none_where_the_seats_found_no_places(self):
self.assertEqual(place_files("Seats found no places hard."), [])
self.assertEqual(place_files("- `tests/test_geo.py:3` `load`\n- `geo_test.py:3` `load`\n- `notes.pyc:1` `x`\n"), [])
class DrawnTest(unittest.TestCase):
MUTANTS = [Mutant("a.go", line, 3, "ARITHMETIC_BASE") for line in range(1, 40)]
MUTANTS = [mutant("a.go", line) for line in range(1, 40)]
def test_a_seed_draws_the_same_order_whatever_order_gremlins_listed_the_mutants_in(self):
def test_a_seed_draws_the_same_order_whatever_order_the_tool_listed_the_mutants_in(self):
self.assertEqual(drawn(self.MUTANTS, 7), drawn(self.MUTANTS[::-1], 7))
def test_draws_every_mutant_once(self):
self.assertEqual(sorted(drawn(self.MUTANTS, 7)), self.MUTANTS)
self.assertEqual(sorted(drawn(self.MUTANTS + self.MUTANTS[:3], 7)), self.MUTANTS)
def test_another_seed_draws_another_order(self):
self.assertNotEqual(drawn(self.MUTANTS, 7), drawn(self.MUTANTS, 8))
class MutatedTest(unittest.TestCase):
SOURCE = b"package calc\n\nfunc f(a, b int) int {\n\tif a >= b {\n\t\treturn a - b\n\t}\n\tn -= 1\n\treturn a\n}\n"
def planted(self, line: int, column: int, mutator: str, source: bytes = SOURCE) -> str | None:
found = mutated(source, Mutant("calc.go", line, column, mutator))
return None if found is None else found.decode().splitlines()[line - 1]
def test_swaps_the_token_at_the_line_and_column_as_gremlins_mutator_does(self):
self.assertEqual(self.planted(4, 7, "CONDITIONALS_NEGATION"), "\tif a < b {")
self.assertEqual(self.planted(4, 7, "CONDITIONALS_BOUNDARY"), "\tif a > b {")
self.assertEqual(self.planted(5, 12, "ARITHMETIC_BASE"), "\t\treturn a + b")
self.assertEqual(self.planted(7, 4, "INVERT_ASSIGNMENTS"), "\tn += 1")
self.assertEqual(self.planted(7, 4, "REMOVE_SELF_ASSIGNMENTS"), "\tn = 1")
def test_changes_no_other_byte(self):
found = mutated(self.SOURCE, Mutant("calc.go", 5, 12, "ARITHMETIC_BASE"))
self.assertEqual(found, self.SOURCE.replace(b"a - b", b"a + b"))
def test_counts_the_column_in_bytes_as_go_does(self):
self.assertEqual(self.planted(1, 15, "CONDITIONALS_NEGATION", 'x := "åäö" == y\n'.encode()), 'x := "åäö" != y')
def test_is_none_where_the_place_holds_no_token_of_the_mutator(self):
self.assertIsNone(self.planted(4, 6, "CONDITIONALS_NEGATION"))
self.assertIsNone(self.planted(5, 12, "CONDITIONALS_NEGATION"))
self.assertIsNone(self.planted(40, 1, "ARITHMETIC_BASE"))
self.assertIsNone(self.planted(4, 70, "ARITHMETIC_BASE"))
self.assertIsNone(self.planted(4, 7, "A_MUTATOR_GREMLINS_ADDS_LATER"))
class TaskTextTest(unittest.TestCase):
def test_is_the_first_failed_tests_message_without_the_tests_name_file_or_line(self):
self.assertEqual(task_text(GO_FAILURE), "Pick() = 3,\nwant 4")
def test_leaves_out_each_line_that_names_the_test_or_its_file(self):
self.assertEqual(task_text(TESTIFY_FAILURE), "Error: \tNot equal:\nexpected: 1\nactual : 2")
def test_is_none_where_no_assertion_failed_as_on_a_panic_or_a_passing_run(self):
self.assertIsNone(task_text(PANIC))
self.assertIsNone(task_text("ok \texample.com/calc\t0.004s\n"))
def test_takes_the_message_of_a_test_that_failed_not_what_a_passing_test_logged(self):
output = "=== RUN TestServer\n server_test.go:12: listening on 127.0.0.1:0\n--- PASS: TestServer (0.00s)\n=== RUN TestPick\n pick_test.go:42: got 3, want 4\n--- FAIL: TestPick (0.00s)\nFAIL\n"
self.assertEqual(task_text(output), "got 3, want 4")
def test_takes_the_last_message_of_the_failed_test_since_a_test_logs_before_it_asserts(self):
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:40: input [1 2 3]\n pick_test.go:42: got 3, want 4\nFAIL\n"), "got 3, want 4")
def test_takes_the_first_failed_test_that_has_a_message(self):
output = "--- FAIL: TestPick (0.00s)\n --- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: got 3\n--- FAIL: TestLast (0.00s)\n pick_test.go:50: got 5\nFAIL\n"
self.assertEqual(task_text(output), "got 3")
def test_a_line_printed_before_any_tests_mark_is_no_tests_message(self):
self.assertEqual(task_text(" setup_test.go:3: starting\n--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\nFAIL\n"), "got 3")
self.assertIsNone(task_text(" setup_test.go:3: starting\n--- FAIL: TestPick (0.00s)\nFAIL\n"))
def test_takes_the_failed_subtests_message_over_what_its_parent_logged_before_it(self):
output = "--- FAIL: TestPick (0.00s)\n pick_test.go:10: three cases\n --- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: got 3\nFAIL\n"
self.assertEqual(task_text(output), "got 3")
def test_is_none_where_only_passing_tests_logged(self):
self.assertIsNone(task_text("=== RUN TestServer\n server_test.go:12: listening\n--- PASS: TestServer (0.00s)\nPASS\n"))
def test_is_none_where_the_message_does_not_say_anything_beyond_the_test(self):
self.assertIsNone(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: TestPick failed\nFAIL\n"))
class LineAtHeadTest(unittest.TestCase):
# Lines 3 and 4 became one, two lines went in after line 9, and line 20 went.
DIFF = "diff --git a/calc.go b/calc.go\n--- a/calc.go\n+++ b/calc.go\n@@ -3,2 +3 @@\n-a\n-b\n+c\n@@ -9,0 +9,2 @@\n+d\n+e\n@@ -20 +20,0 @@\n-f\n"
def test_a_line_above_every_change_keeps_its_number(self):
self.assertEqual(line_at_head(self.DIFF, 2), 2)
def test_a_line_below_a_change_moves_by_the_lines_it_added_and_removed(self):
self.assertEqual([line_at_head(self.DIFF, line) for line in (5, 9, 10, 19, 21)], [4, 8, 11, 20, 21])
def test_a_line_the_head_changed_or_removed_has_none(self):
self.assertEqual([line_at_head(self.DIFF, line) for line in (3, 4, 20)], [None, None, None])
def test_no_diff_keeps_every_line(self):
self.assertEqual(line_at_head("", 12), 12)
class BugAtSidesTest(unittest.TestCase):
MUTANT = Mutant("calc.go", 3, 11, "ARITHMETIC_BASE")
BASE = b"package calc\n\n\treturn a + b\n"
# The head adds a line above the bug's.
HEAD = b"package calc\n// Add adds.\n\n\treturn a + b\n"
DIFF = "@@ -1,0 +2 @@\n+// Add adds.\n"
def test_the_bug_is_the_same_change_at_each_side_on_the_line_as_that_side_numbers_it(self):
found = bug_at_sides(self.MUTANT, self.DIFF, {"base": self.BASE, "head": self.HEAD})
self.assertEqual(found, {"base": self.BASE.replace(b"+", b"-"), "head": self.HEAD.replace(b"+", b"-")})
def test_a_line_the_head_changed_holds_no_bug(self):
self.assertIsNone(bug_at_sides(self.MUTANT, "@@ -3 +3 @@\n-\treturn a + b\n+\treturn b + a\n", {"base": self.BASE, "head": self.BASE}))
def test_a_side_without_the_file_or_without_the_operator_the_mutant_changes_holds_no_bug(self):
self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": None}))
self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": b"package calc\n\n\treturn sum(a, b)\n"}))
class KilledMutantsTest(unittest.TestCase):
class LanguagesTest(unittest.TestCase):
def setUp(self):
folder = tempfile.TemporaryDirectory()
self.addCleanup(folder.cleanup)
self.top = pathlib.Path(folder.name)
for path in ("calc.go", "calc_test.go", "render/pick.go", "render/a+b.go", "render/notes.md", "cli/main.go"):
(self.top / path).parent.mkdir(parents=True, exist_ok=True)
(self.top / path).write_text("package x\n")
self.ran: list[tuple[list[str], str]] = []
self.asked: list[tuple] = []
self.found: dict[str, list[Mutant] | Failure] = {"Go": [mutant("b.go"), mutant("a.go")], "Python": [mutant("c.py")]}
languages = tuple(Language(name, suffixes, self.killed(name), f"{name} read {{}}".format) for name, suffixes in (("Go", (".go",)), ("Python", (".py", ".pyi"))))
patched = unittest.mock.patch.object(plant, "LANGUAGES", languages)
patched.start()
self.addCleanup(patched.stop)
def gremlins(self, report: dict | None, code: int = 0):
def run(argv: list[str], cwd: str) -> Ran:
self.ran.append((argv, cwd))
if report is not None:
pathlib.Path(cwd, argv[argv.index("--output") + 1]).write_text(json.dumps(report))
return Ran(code, "gremlins said so")
def killed(self, name: str):
def killed(top: str, files: list[str], run, jobs: int) -> list[Mutant] | Failure:
self.asked.append((name, top, files, run, jobs))
return self.found[name]
return run
return killed
def test_names_each_go_file_gremlins_would_mutate_by_its_path_from_the_top(self):
self.assertEqual(sorted(go_files(str(self.top))), ["calc.go", "cli/main.go", "render/a+b.go", "render/pick.go"])
def test_each_languages_tool_finds_the_mutants_of_the_files_in_that_language(self):
self.assertEqual(killed_mutants("/top", ["a.go", "c.py", "b.go", "d.pyi"], "run", 3), [mutant("b.go"), mutant("a.go"), mutant("c.py")])
self.assertEqual(self.asked, [("Go", "/top", ["a.go", "b.go"], "run", 3), ("Python", "/top", ["c.py", "d.pyi"], "run", 3)])
def test_has_gremlins_leave_out_every_other_go_file_by_its_whole_path(self):
killed_mutants(str(self.top), ["render/pick.go"], self.gremlins({"files": []}), 3)
argv, cwd = self.ran[0]
self.assertEqual(cwd, str(self.top))
self.assertEqual(argv[:8], ["gremlins", "unleash", "--exclude-files", r"^calc\.go$", "--exclude-files", r"^cli/main\.go$", "--exclude-files", r"^render/a\+b\.go$"])
self.assertEqual((argv[8], argv[10:]), ("--output", ["--workers", "3"]))
def test_a_language_without_a_file_runs_no_tool(self):
self.assertEqual(killed_mutants("/top", ["c.py"], "run", 3), [mutant("c.py")])
self.assertEqual([name for name, *_ in self.asked], ["Python"])
def test_keeps_the_killed_mutants_of_the_files_asked_for(self):
report = {"files": [
{"file_name": "render/pick.go", "mutations": [{"line": 4, "column": 7, "status": "KILLED", "type": "ARITHMETIC_BASE"}, {"line": 5, "column": 2, "status": "LIVED", "type": "INVERT_LOGICAL"}, {"line": 6, "column": 2, "status": "NOT COVERED", "type": "INVERT_LOGICAL"}]},
{"file_name": "calc.go", "mutations": [{"line": 1, "column": 1, "status": "KILLED", "type": "ARITHMETIC_BASE"}]},
]}
self.assertEqual(killed_mutants(str(self.top), ["render/pick.go"], self.gremlins(report), 3), [Mutant("render/pick.go", 4, 7, "ARITHMETIC_BASE")])
def test_a_tool_that_fails_fails_the_whole(self):
self.found["Go"] = Failure("gremlins broke")
self.assertEqual(killed_mutants("/top", ["a.go", "c.py"], "run", 3), Failure("gremlins broke"))
def test_a_gremlins_that_fails_is_a_failure_with_what_it_printed(self):
found = killed_mutants(str(self.top), ["render/pick.go"], self.gremlins(None, code=1), 3)
self.assertIsInstance(found, Failure)
self.assertIn("gremlins said so", found.reason)
def test_the_language_of_the_bugs_file_reads_the_test_commands_output(self):
self.assertEqual((task_text("pkg/a.go", "output"), task_text("pkg/c.pyi", "output")), ("Go read output", "Python read output"))
self.assertIsNone(task_text("README.md", "output"))
class EdgesTest(unittest.TestCase):
def test_mutates_the_last_line_of_a_file(self):
self.assertEqual(mutated(b"a\nb + c", Mutant("calc.go", 2, 3, "ARITHMETIC_BASE")), b"a\nb - c")
self.assertIsNone(mutated(b"a\nb + c", Mutant("calc.go", 3, 3, "ARITHMETIC_BASE")))
self.assertIsNone(mutated(b"a\nb + c", Mutant("calc.go", 0, 3, "ARITHMETIC_BASE")))
def test_takes_the_longest_token_at_the_column(self):
self.assertEqual(mutated(b"a >= b", Mutant("calc.go", 1, 3, "CONDITIONALS_BOUNDARY")), b"a > b")
self.assertEqual(mutated(b"a &^ b", Mutant("calc.go", 1, 3, "INVERT_BITWISE")), b"a & b")
def test_a_message_ends_at_the_next_line_indented_as_its_first(self):
output = "--- FAIL: TestPick/empty_input (0.00s)\n pick_test.go:42: got 3\n want 4\n--- FAIL: TestLast (0.00s)\n pick_test.go:50: got 5\n"
self.assertEqual(task_text(output), "got 3\nwant 4")
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\n a line the test logged\n"), "got 3")
def test_a_message_runs_to_the_end_of_the_output(self):
self.assertEqual(task_text("--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3\n want 4"), "got 3\nwant 4")
def test_a_message_may_name_a_part_of_a_subtests_name_that_is_no_test(self):
output = "--- FAIL: TestPick/empty (0.00s)\n pick_test.go:42: empty input: got 3\n in TestPick\n in TestPick/empty\n"
self.assertEqual(task_text(output), "empty input: got 3")
class ShippedLanguagesTest(unittest.TestCase):
def test_go_reads_go_tests_output_and_python_pytests(self):
self.assertEqual([(language.name, language.suffixes) for language in LANGUAGES], [("Go", (".go",)), ("Python", (".py",))])
self.assertEqual(task_text("calc.go", "--- FAIL: TestPick (0.00s)\n pick_test.go:42: got 3, want 4\nFAIL\n"), "got 3, want 4")
self.assertEqual(task_text("calc.py", "==== FAILURES ====\n___ test_pick ___\nE assert 3 == 4\n"), "assert 3 == 4")
if __name__ == "__main__":
+76
View File
@@ -0,0 +1,76 @@
"""How task-bench re-applies a mutant: as the same change to the same lines at the base and at the head."""
import pathlib
import sys
import unittest
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench.planted_mutant import bug_at_sides, line_at_head, Mutant, mutated
class MutatedTest(unittest.TestCase):
SOURCE = b"a\n\tb + c\n\td,\n\te\n"
def test_puts_the_mutants_lines_in_place_of_the_ones_it_changes_and_changes_no_other_byte(self):
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 2, "calc.py:2 x", (b"\tb + c",), (b"\tb - c",))), b"a\n\tb - c\n\td,\n\te\n")
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 2, "calc.py:2 x", (b"\tb + c", b"\td,"), (b"\tb", b"\t- c", b"\td"))), b"a\n\tb\n\t- c\n\td\n\te\n")
def test_removes_lines_and_adds_them(self):
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 3, "calc.py:3 x", (b"\td,",), ())), b"a\n\tb + c\n\te\n")
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 3, "calc.py:3 x", (), (b"\tf,",))), b"a\n\tb + c\n\tf,\n\td,\n\te\n")
def test_is_none_where_the_line_does_not_start_the_lines_the_mutant_changes(self):
for line, was in ((1, (b"\tb + c",)), (2, (b"\tb + c", b"\te")), (2, (b"b + c",)), (0, (b"a",)), (-1, (b"\te",)), (5, (b"\te", b"")), (9, (b"",)), (7, ())):
with self.subTest(line=line, was=was):
self.assertIsNone(mutated(self.SOURCE, Mutant("calc.py", line, "x", was, (b"z",))))
self.assertEqual(mutated(self.SOURCE, Mutant("calc.py", 6, "x", (), (b"z",))), self.SOURCE + b"\nz")
def test_mutates_the_last_line_of_a_file(self):
self.assertEqual(mutated(b"a\nb + c", Mutant("calc.go", 2, "x", (b"b + c",), (b"b - c",))), b"a\nb - c")
self.assertIsNone(mutated(b"a\nb + c", Mutant("calc.go", 3, "x", (b"b + c",), (b"b - c",))))
class LineAtHeadTest(unittest.TestCase):
# Lines 3 and 4 became one, two lines went in after line 9, and line 20 went.
DIFF = "diff --git a/calc.go b/calc.go\n--- a/calc.go\n+++ b/calc.go\n@@ -3,2 +3 @@\n-a\n-b\n+c\n@@ -9,0 +9,2 @@\n+d\n+e\n@@ -20 +20,0 @@\n-f\n"
def test_a_line_above_every_change_keeps_its_number(self):
self.assertEqual(line_at_head(self.DIFF, 2), 2)
def test_a_line_below_a_change_moves_by_the_lines_it_added_and_removed(self):
self.assertEqual([line_at_head(self.DIFF, line) for line in (5, 9, 10, 19, 21)], [4, 8, 11, 20, 21])
def test_a_line_the_head_changed_or_removed_has_none(self):
self.assertEqual([line_at_head(self.DIFF, line) for line in (3, 4, 20)], [None, None, None])
def test_no_diff_keeps_every_line(self):
self.assertEqual(line_at_head("", 12), 12)
class BugAtSidesTest(unittest.TestCase):
MUTANT = Mutant("calc.go", 3, "calc.go:3:11 ARITHMETIC_BASE", (b"\treturn a + b",), (b"\treturn a - b",))
BASE = b"package calc\n\n\treturn a + b\n"
# The head adds a line above the bug's.
HEAD = b"package calc\n// Add adds.\n\n\treturn a + b\n"
DIFF = "@@ -1,0 +2 @@\n+// Add adds.\n"
def test_the_bug_is_the_same_change_at_each_side_on_the_line_as_that_side_numbers_it(self):
found = bug_at_sides(self.MUTANT, self.DIFF, {"base": self.BASE, "head": self.HEAD})
self.assertEqual(found, {"base": self.BASE.replace(b"+", b"-"), "head": self.HEAD.replace(b"+", b"-")})
def test_a_line_the_head_changed_holds_no_bug(self):
self.assertIsNone(bug_at_sides(self.MUTANT, "@@ -3 +3 @@\n-\treturn a + b\n+\treturn b + a\n", {"base": self.BASE, "head": self.BASE}))
def test_a_side_without_the_file_or_without_the_line_the_mutant_changes_holds_no_bug(self):
self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": None}))
self.assertIsNone(bug_at_sides(self.MUTANT, "", {"base": self.BASE, "head": b"package calc\n\n\treturn sum(a, b)\n"}))
def test_a_mutant_of_several_lines_holds_no_bug_where_the_head_changed_one_after_the_first(self):
mutant = Mutant("calc.py", 1, "calc.py:1 x", (b"low = min(", b"\ta,"), (b"low = max(", b"\ta,"))
base, head = b"low = min(\n\ta,\n\tb)\n", b"low = min(\n\tc,\n\tb)\n"
self.assertIsNone(bug_at_sides(mutant, "@@ -2 +2 @@\n-\ta,\n+\tc,\n", {"base": base, "head": head}))
self.assertEqual(bug_at_sides(mutant, "", {"base": base, "head": base}), {"base": base.replace(b"min", b"max"), "head": base.replace(b"min", b"max")})
if __name__ == "__main__":
unittest.main()
+181
View File
@@ -0,0 +1,181 @@
"""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 task_bench.python_bugs import killed_mutants, task_text
from task_bench.planted_mutant import Mutant
from failure import Failure
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 four failed tests, the last on an error the code raised.
PYTEST_FAILURES = """============================= test session starts ==============================
collected 5 items
test_calc.py .FFFF [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]]] = []
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/pkg").mkdir(parents=True)
pathlib.Path(cwd, "mutants/pkg/calc.py").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_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(self):
self.assertIsInstance(killed_mutants(str(self.top), ["bin/pkg/gone.py"], self.mutmut(), 3), Failure)
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()
+7 -5
View File
@@ -18,7 +18,8 @@ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from task_bench import api_proxy, bench_folder, main, runs
from test_env import assert_not_root, isolated_env
from task_bench.runs import checked_tree, closed, Containers, docker_cli, fix_attempted, opened, ran_tests, TimedOut
from task_bench.plant import drawn, Mutant
from task_bench.plant import drawn
from task_bench.planted_mutant import Mutant
from claude_code.entries import Entry, entry_from
from failure import Failure
from task_bench.figures import Figures, Result
@@ -235,7 +236,7 @@ class BenchTest(unittest.TestCase):
def test_the_command_line_fails_with_the_reason_where_the_places_or_the_bench_fail(self):
argv = [part for name, value in self.given.items() for part in (name, value)]
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go file that the base holds, so there is nowhere to plant a bug.\n")):
for places, said in ((Failure("no history"), "no history\n"), ("- `gone.go:1` `Gone`: removed\n", "The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug.\n")):
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as errors:
self.assertEqual(main.main(argv, self.env, lambda home: places), 1)
self.assertEqual((out.getvalue(), errors.getvalue().splitlines(keepends=True)[-1]), ("", said))
@@ -308,7 +309,7 @@ class BenchTest(unittest.TestCase):
def test_fails_where_the_places_name_no_go_file_of_the_base(self):
with contextlib.redirect_stderr(io.StringIO()):
found = main.bench({**self.given, "--base": "main"}, self.env, lambda home: "- `gone.go:1` `Gone`: removed\n- `README.md:1` `Calc`: thin\n", self.home)
self.assertEqual(found, Failure("The places the seats found hard don't name any Go file that the base holds, so there is nowhere to plant a bug."))
self.assertEqual(found, Failure("The places the seats found hard don't name any Go or Python file that the base holds, so there is nowhere to plant a bug."))
self.assertFalse(self.log.exists())
def test_fails_where_the_tests_fail_without_a_bug(self):
@@ -379,7 +380,8 @@ class BenchTest(unittest.TestCase):
# Tests that catch both mutants, at a head benched against itself, where each mutant's line stands.
(self.repo / "calc_test.go").write_text(TESTS.replace("calc.go &&", "calc.go && grep -q '2 \\* a' calc.go &&"))
self.commit("Tests that catch Twice")
mutants = [Mutant("calc.go", 5, 11, "ARITHMETIC_BASE"), Mutant("calc.go", 9, 11, "ARITHMETIC_BASE")]
# The seed draws from the mutants in the order of their lines.
mutants = [Mutant("calc.go", line, "", (), ()) for line in (5, 9)]
for seed in (1, 2, 3, 4):
report = self.bench(**{"--base": "HEAD", "--bugs": "1", "--runs": "1", "--seed": str(seed)})
self.assertNotIsInstance(report, Failure, report)
@@ -490,7 +492,7 @@ class InTurn(Recorded):
class RunOutcomesTest(unittest.TestCase):
MUTANT = Mutant("calc.go", 4, 11, "ARITHMETIC_BASE")
MUTANT = Mutant("calc.go", 4, "calc.go:4:11 ARITHMETIC_BASE", (b"\treturn a + b",), (b"\treturn a - b",))
def setUp(self):
folder = tempfile.TemporaryDirectory()
+57 -4
View File
@@ -6,7 +6,7 @@
`Bar = 0.1`
`Next ID = 526`
`Next ID = 530`
## Renamed
@@ -16,11 +16,15 @@
| ID | Release | Blocked by | Exempt | Item | L | E | I | R | S | Moves | Score |
|---|---|---|---|---|---|---|---|---|---|---|---|
| 508 | 0.16.0 | | owner | **Plant bugs for `task-bench` in Python, Rust, TypeScript and PHP, from the mutants `mutate-changes` runs for each, so this repo benches itself.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 3, code health by 2 | 1.8 |
| 508 | 0.16.0 | | owner | **Plant bugs for `task-bench` in Python, from the mutants mutmut kills, and re-apply every language's mutant as changed lines.** | 4 | 2 | 1 | 5 | 6 | 1.1 by 3, code health by 2 | 1.8 |
| 506 | 0.16.0 | | owner | **Go over the bench features in each release review: reapply each reference patch, drop a feature that no longer breaks a goal, and add features until they cover the places the seats find hardest.** | 2 | 2 | 2 | 4 | 3 | 1.1 by 3 | 1.1 |
| 512 | 0.16.0 | | | **Make stability-reviewer check that keys built from path segments, or matched by prefix, cannot collide.** | 1 | 2 | 2 | 3 | 1 | 1.1 by 2 | 0.9 |
| 529 | 0.16.0 | 508 | owner | **Document a `task-bench` command for this repo in the README, with an image that holds what its tests need, so each scoring run benches it.** | 2 | 2 | 1 | 3 | 3 | 1.1 by 2 | 0.7 |
| 507 | 0.16.0 | | owner | **Bench rebuilding a feature the project shipped: revert its commit at the head, hand Haiku its item tagline, and check with the tests that commit added.** | 3 | 2 | 1 | 4 | 5 | 1.1 by 3 | 0.7 |
| 524 | 0.16.0 | | owner | **Write fejkdata's first six bench features, each a spec, acceptance tests in Go and a reference patch that builds it, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 6 | 1.1 by 3 | 0.5 |
| 526 | 0.16.0 | 508 | owner | **Plant bugs for `task-bench` in Rust, from the mutants cargo-mutants kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 527 | 0.16.0 | 508 | owner | **Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 528 | 0.16.0 | 508 | owner | **Plant bugs for `task-bench` in PHP, from the mutants Infection kills.** | 3 | 2 | 1 | 4 | 4 | 1.1 by 1 | 0.3 |
| 525 | 0.16.0 | | owner | **Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.** | 3 | 2 | 1 | 4 | 7 | 1.1 by 3 | 0.3 |
| 477 | 0.17.0 | | question | **Rewrite `## Goals` and `## Audience` for a setup others install and run apart from their own `~/.claude`.** | 1 | 1 | 2 | 2 | 2 | | 0.0 |
| 478 | 0.17.0 | | question | **Name the project, its repo and its two commands, today proposed as `do-release` and `do-epic`.** | 1 | 1 | 2 | 2 | 1 | | 0.0 |
@@ -112,9 +116,11 @@
## Details
### 508. Plant bugs for `task-bench` in Python, Rust, TypeScript and PHP, from the mutants `mutate-changes` runs for each, so this repo benches itself.
### 508. Plant bugs for `task-bench` in Python, from the mutants mutmut kills, and re-apply every language's mutant as changed lines.
Each tool reports a killed mutant by file and line, and some by column; the planter re-applies it from that report, as it does Gremlins'.
A killed mutant is the lines it changes and what it puts in their place, so one planter re-applies Gremlins' and mutmut's alike. Each language has a module that runs its mutation tool and reads its test runner's failure. Rust, TypeScript and PHP are items of their own, each blocked by this one; so is the bench command this repo documents for itself.
Split from the item for all four languages when a re-score put that at L 4: a milestone is split before it starts, and Python is the one language this repo can check for real.
### 506. Go over the bench features in each release review: reapply each reference patch, drop a feature that no longer breaks a goal, and add features until they cover the places the seats find hardest.
@@ -127,6 +133,14 @@ An outside reviewer found two bugs in one chunk that our stability round passed.
Touches:
- `agents/stability-reviewer.md`: `### 5. Edge Cases & Input Validation` (small)
### 529. Document a `task-bench` command for this repo in the README, with an image that holds what its tests need, so each scoring run benches it.
The bench runs the tests in an image without network, and this repo's tests run on the host through `uvx`, so no image holds pytest, git and tmux today. Build one, pinned, and name it in the command. A scoring run starts the bench the README documents, so from then on each one spends Haiku runs.
Touches:
- `README.md`
- `task-bench-image/Dockerfile`
### 507. Bench rebuilding a feature the project shipped: revert its commit at the head, hand Haiku its item tagline, and check with the tests that commit added.
Such tasks cost nothing to write and are realistic. A commit whose revert doesn't apply cleanly at both the base and the head is skipped.
@@ -144,6 +158,45 @@ The second part of item 504, which says what a bench feature is and when a run c
Done when `task-bench` counts a run of each: its acceptance tests fail at fejkdata's base and head and pass with its reference patch. The six land in fejkdata's checkout or its config folder, wherever its `bench-tasks` setting points, so the item changes no file of this repo and carries no `Touches:` list. About 1,000 lines of Go and specs.
### 526. Plant bugs for `task-bench` in Rust, from the mutants cargo-mutants kills.
cargo-mutants runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from the diffs it writes under `mutants.out`. Tell Haiku the failure `cargo test` prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no Rust.
Touches:
- `bin/task_bench/rust_bugs.py`
- `bin/task_bench/test_rust_bugs.py`
- `bin/task_bench/plant.py`: `LANGUAGES`
- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest`
- `bin/mutate_changes/in_diff_tools.py`: `run_cargo_mutants`
- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner`
- `README.md`: lines 231-231, lines 281-281
### 527. Plant bugs for `task-bench` in TypeScript, from the mutants Stryker kills.
Stryker runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from its JSON report. Tell Haiku the failure the project's test runner prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no TypeScript.
Touches:
- `bin/task_bench/typescript_bugs.py`
- `bin/task_bench/test_typescript_bugs.py`
- `bin/task_bench/plant.py`: `LANGUAGES`
- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest`
- `bin/mutate_changes/in_diff_tools.py`: `run_stryker`
- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner`
- `README.md`: lines 231-231, lines 281-281
### 528. Plant bugs for `task-bench` in PHP, from the mutants Infection kills.
Infection runs over the changed lines only today. Run it over the files that hold the seats' places, at the tree's top without git, and turn each killed mutant into the lines it changes, read from its JSON log. Tell Haiku the failure PHPUnit prints, without the test's name or file. Check the module against the tool's real output on a small project in a container, since this repo holds no PHP.
Touches:
- `bin/task_bench/php_bugs.py`
- `bin/task_bench/test_php_bugs.py`
- `bin/task_bench/plant.py`: `LANGUAGES`
- `bin/task_bench/test_plant.py`: `ShippedLanguagesTest`
- `bin/mutate_changes/in_diff_tools.py`: `run_infection`
- `bin/task_bench/main.py`: lines 14-40, lines 100-110, `bugs_planner`
- `README.md`: lines 231-231, lines 281-281
### 525. Write fejkdata's first five source-data tasks for `task-bench`, each a seeded register for a made-up country, a spec, a checker and a reference patch, in the `bench-tasks` folder its config names.
The second part of item 505, which says what a source-data task is and when a run counts. The country code of each comes from ISO 3166-1's user-assigned range (AA, QM–QZ, XA–XZ, ZZ), leaving out XK, which the EU and others use for Kosovo, so no task meets real data. Each register has the quirks real ones publish.