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
+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