Plant bugs for task-bench in Python from the mutants mutmut kills
CI / tests (pull_request) Failing after 3m46s
CI / tests (pull_request) Failing after 3m46s
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in New Issue
Block a user