Have mutmut copy each entry of the folder rather than '.', which copied mutants/ into itself and collected the tests twice

This commit is contained in:
2026-11-11 19:14:49 +01:00
parent e99eef43b9
commit 79e8ce1368
3 changed files with 42 additions and 46 deletions
+9 -15
View File
@@ -1,7 +1,6 @@
"""The setup.cfg that has mutmut mutate a branch's changed files, and the tests left out because they fail before any mutant.""" """The setup.cfg that has mutmut mutate a branch's changed files, and the tests left out because they fail before any mutant."""
import configparser import configparser
import io import io
import os
import re import re
from failure import Failure from failure import Failure
@@ -18,10 +17,11 @@ class CaseKept(configparser.ConfigParser):
return optionstr return optionstr
def mutmut_config(existing: str, sources: list[str], left: list[str]) -> str | Failure: def mutmut_config(existing: str, sources: list[str], copied: list[str], left: list[str]) -> str | Failure:
"""The setup.cfg that has mutmut mutate the sources, copy the rest of the folder, which their tests import, and pass pytest the options that leave tests out. """The setup.cfg that has mutmut mutate the sources, copy the folder's other entries, which their tests import, and pass pytest the options that leave tests out.
existing is the project's own setup.cfg, empty where it has none. Its settings stay, though its comments go, and its [mutmut] pytest_add_cli_args come before the options that leave tests out.""" copied names each file and folder at the folder's top. Not ".": mutmut makes mutants/ before it copies, so "." would copy mutants/ into itself and
pytest would collect the tests twice. existing is the project's own setup.cfg, empty where it has none. Its settings stay, though its comments go, and its [mutmut] pytest_add_cli_args come before the options that leave tests out."""
config = CaseKept(interpolation=None) config = CaseKept(interpolation=None)
try: try:
config.read_string(existing) config.read_string(existing)
@@ -31,7 +31,7 @@ def mutmut_config(existing: str, sources: list[str], left: list[str]) -> str | F
config.add_section("mutmut") config.add_section("mutmut")
section = config["mutmut"] section = config["mutmut"]
section["source_paths"] = listed(sources) section["source_paths"] = listed(sources)
section["also_copy"] = "." section["also_copy"] = listed(copied)
if left: if left:
section["pytest_add_cli_args"] = "\n".join(filter(None, [section.get("pytest_add_cli_args", ""), listed(left)])) section["pytest_add_cli_args"] = "\n".join(filter(None, [section.get("pytest_add_cli_args", ""), listed(left)]))
written = io.StringIO() written = io.StringIO()
@@ -45,14 +45,8 @@ def listed(items: list[str]) -> str:
def left_out(output: str) -> list[str]: def left_out(output: str) -> list[str]:
"""The nodeid of each test, or test file that failed to collect, that a failed run's short summary reports.""" """The pytest options that leave out each test a failed run's short summary reports: --deselect for a test, --ignore for a file that failed to collect."""
summary = SUMMARY.split(output) summary = SUMMARY.split(output)
return REPORTED.findall(summary[-1]) if len(summary) > 1 else [] if len(summary) < 2:
return []
return [f"--deselect={nodeid}" if "::" in nodeid else f"--ignore={nodeid}" for nodeid in REPORTED.findall(summary[-1])]
def leaving_out(nodeids: list[str], copy: str) -> list[str]:
"""The pytest options that leave out each nodeid: --deselect for a test, --ignore for a file.
mutmut 3.8.1 runs pytest in copy's mutants/ folder, yet pytest 9.2 reports each nodeid from copy, as mutants/<path>. --deselect takes the
nodeid as reported, and --ignore an absolute path, built the same way whether or not the nodeid starts with mutants/."""
return [f"--deselect={nodeid}" if "::" in nodeid else f"--ignore={os.path.join(copy, 'mutants', nodeid.removeprefix('mutants/'))}" for nodeid in nodeids]
+19 -14
View File
@@ -15,7 +15,7 @@ from mutate_changes.tool_process import failed, Ran, run_tool
from failure import Failure from failure import Failure
from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses
from git_cli.git_repo import git from git_cli.git_repo import git
from mutate_changes.mutmut_setup import leaving_out, left_out, mutmut_config from mutate_changes.mutmut_setup import left_out, mutmut_config
CAUGHT = frozenset({"caught by type check", "killed"}) CAUGHT = frozenset({"caught by type check", "killed"})
CONFIGS = ("pyproject.toml", "setup.cfg") CONFIGS = ("pyproject.toml", "setup.cfg")
@@ -82,8 +82,8 @@ def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], prefix:
return Failure(f"could not make a scratch folder in {top}: {failure}") return Failure(f"could not make a scratch folder in {top}: {failure}")
try: try:
copy = os.path.join(scratch, "copy") copy = os.path.join(scratch, "copy")
copy_files(root, listed.split("\0"), copy) copied = copy_files(root, listed.split("\0"), copy)
return mutate_copy(copy, folder, ["mutmut", "run", "--max-children", str(jobs), *globs], prefix) return mutate_copy(copy, copied, folder, ["mutmut", "run", "--max-children", str(jobs), *globs], prefix)
except OSError as failure: except OSError as failure:
return Failure(f"could not set mutmut up in {scratch}, a copy of {root}: {failure}") return Failure(f"could not set mutmut up in {scratch}, a copy of {root}: {failure}")
finally: finally:
@@ -117,8 +117,11 @@ def project_setup(root: str) -> str | Failure:
return Failure(f"could not read the mutmut settings in {root}: {failure}") return Failure(f"could not read the mutmut settings in {root}: {failure}")
def copy_files(root: str, paths: list[str], copy: str) -> None: def copy_files(root: str, paths: list[str], copy: str) -> list[str]:
"""Copy the files git lists in root, tracked or not ignored, to copy, symlinks as symlinks. Leaves out mutmut's own mutants/ and the scratch folders of runs that never cleaned up.""" """Copy the files git lists in root, tracked or not ignored, to copy, symlinks as symlinks, and name each file and folder copied to copy's top.
Leaves out mutmut's own mutants/ and the scratch folders of runs that never cleaned up."""
copied = set()
for path in paths: for path in paths:
source, target = os.path.join(root, path), os.path.join(copy, path) source, target = os.path.join(root, path), os.path.join(copy, path)
gone_or_submodule = not os.path.lexists(source) or os.path.isdir(source) and not os.path.islink(source) gone_or_submodule = not os.path.lexists(source) or os.path.isdir(source) and not os.path.islink(source)
@@ -126,10 +129,12 @@ def copy_files(root: str, paths: list[str], copy: str) -> None:
continue continue
os.makedirs(os.path.dirname(target), exist_ok=True) os.makedirs(os.path.dirname(target), exist_ok=True)
shutil.copy2(source, target, follow_symlinks=False) shutil.copy2(source, target, follow_symlinks=False)
copied.add(path.split("/")[0])
return sorted(copied)
def mutate_copy(copy: str, folder: Folder, argv: list[str], prefix: str | None) -> list[str] | Failure: def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], prefix: str | None) -> list[str] | Failure:
ran = run_until_stats_pass(copy, folder, argv, prefix) ran = run_until_stats_pass(copy, copied, folder, argv, prefix)
if isinstance(ran, Failure): if isinstance(ran, Failure):
return ran return ran
output, left = ran output, left = ran
@@ -140,17 +145,17 @@ def mutate_copy(copy: str, folder: Folder, argv: list[str], prefix: str | None)
return results if isinstance(results, Failure) else failed(f"mutmut results in {folder.label}", results) return results if isinstance(results, Failure) else failed(f"mutmut results in {folder.label}", results)
shown, counted = not_killed(folder, statuses(results.output), copy) shown, counted = not_killed(folder, statuses(results.output), copy)
unreached = " No test reaches them." if NO_TEST in output else "" unreached = " No test reaches them." if NO_TEST in output else ""
left_files = sorted({nodeid.partition("::")[0].removeprefix("mutants/") for nodeid in left}) left_files = sorted({option.partition("=")[2].partition("::")[0] for option in left})
left_note = f" Left out tests in {', '.join(left_files)} that fail without a mutant." if left else "" left_note = f" Left out tests in {', '.join(left_files)} that fail without a mutant." if left else ""
return [f"mutmut in {folder.label}: {counted} mutants on changed lines, {len(shown)} not killed.{unreached}{left_note}", *shown] return [f"mutmut in {folder.label}: {counted} mutants on changed lines, {len(shown)} not killed.{unreached}{left_note}", *shown]
def run_until_stats_pass(copy: str, folder: Folder, argv: list[str], prefix: str | None) -> tuple[str, list[str]] | Failure: def run_until_stats_pass(copy: str, copied: list[str], folder: Folder, argv: list[str], prefix: str | None) -> tuple[str, list[str]] | Failure:
"""mutmut's output, and the nodeid of each test it left out because the test fails before any mutant: mutmut runs no mutant while one fails.""" """mutmut's output, and the options that left out each test that fails before any mutant: mutmut runs no mutant while one fails."""
ran = configured_run(copy, folder, LIST_FAILURES, argv, prefix) ran = configured_run(copy, copied, folder, LIST_FAILURES, argv, prefix)
left: list[str] = [] left: list[str] = []
if isinstance(ran, Ran) and STATS_FAILED in ran.output and (left := left_out(ran.output)): if isinstance(ran, Ran) and STATS_FAILED in ran.output and (left := left_out(ran.output)):
ran = configured_run(copy, folder, leaving_out(left, copy), argv, prefix) ran = configured_run(copy, copied, folder, left, argv, prefix)
if isinstance(ran, Failure): if isinstance(ran, Failure):
return ran return ran
if ran.code and NO_MUTANT not in ran.output and NO_TEST not in ran.output: if ran.code and NO_MUTANT not in ran.output and NO_TEST not in ran.output:
@@ -158,8 +163,8 @@ def run_until_stats_pass(copy: str, folder: Folder, argv: list[str], prefix: str
return ran.output, left return ran.output, left
def configured_run(copy: str, folder: Folder, options: list[str], argv: list[str], prefix: str | None) -> Ran | Failure: def configured_run(copy: str, copied: list[str], folder: Folder, options: list[str], argv: list[str], prefix: str | None) -> Ran | Failure:
config = mutmut_config(folder.setup, sorted(folder.files), options) config = mutmut_config(folder.setup, sorted(folder.files), copied, options)
if isinstance(config, Failure): if isinstance(config, Failure):
return Failure(f"{folder.label}: {config.reason}") return Failure(f"{folder.label}: {config.reason}")
pathlib.Path(copy, "setup.cfg").write_text(config, encoding="utf-8") pathlib.Path(copy, "setup.cfg").write_text(config, encoding="utf-8")
+14 -17
View File
@@ -12,7 +12,7 @@ from mutate_changes.changed_lines import added_lines, runs, tool_for
from failure import Failure from failure import Failure
from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses from mutate_changes.mutmut_mutants import function_keys, mutant_globs, mutated_line, named, statuses
from test_env import isolated_env from test_env import isolated_env
from mutate_changes.mutmut_setup import leaving_out, left_out, mutmut_config from mutate_changes.mutmut_setup import left_out, mutmut_config
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes" TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes"
SOURCE = "def double(n):\n\treturn n * 2\n\n\nclass Pt:\n\tdef moved(self, by=1):\n\t\treturn self.x + by\n" SOURCE = "def double(n):\n\treturn n * 2\n\n\nclass Pt:\n\tdef moved(self, by=1):\n\t\treturn self.x + by\n"
@@ -73,14 +73,14 @@ class ChangedLines(unittest.TestCase):
class MutmutSetup(unittest.TestCase): class MutmutSetup(unittest.TestCase):
def test_the_config_mutates_the_sources_and_copies_the_whole_folder(self): def test_the_config_mutates_the_sources_and_copies_each_entry_of_the_folder(self):
text = mutmut_config("", ["x/a.py", "b.py"], []) text = mutmut_config("", ["x/a.py", "b.py"], ["b.py", "x"], [])
self.assertEqual(read_as_mutmut(text, "source_paths"), ["x/a.py", "b.py"]) self.assertEqual(read_as_mutmut(text, "source_paths"), ["x/a.py", "b.py"])
self.assertEqual(read_as_mutmut(text, "also_copy"), ["."]) self.assertEqual(read_as_mutmut(text, "also_copy"), ["b.py", "x"])
def test_the_config_keeps_the_projects_settings_and_appends_the_tests_left_out(self): def test_the_config_keeps_the_projects_settings_and_appends_the_tests_left_out(self):
existing = "[tool:pytest]\naddopts = -q\n\n[mutmut]\npytest_add_cli_args = -k\n not Slow\ndebug = true\n" existing = "[tool:pytest]\naddopts = -q\n\n[mutmut]\npytest_add_cli_args = -k\n not Slow\ndebug = true\n"
text = mutmut_config(existing, ["a.py"], ["--deselect=t/test_a.py::T::test_b[50%]"]) text = mutmut_config(existing, ["a.py"], ["a.py", "t"], ["--deselect=t/test_a.py::T::test_b[50%]"])
self.assertEqual(read_as_mutmut(text, "pytest_add_cli_args"), ["-k", "not Slow", "--deselect=t/test_a.py::T::test_b[50%]"]) self.assertEqual(read_as_mutmut(text, "pytest_add_cli_args"), ["-k", "not Slow", "--deselect=t/test_a.py::T::test_b[50%]"])
self.assertEqual(read_as_mutmut(text, "debug"), ["true"]) self.assertEqual(read_as_mutmut(text, "debug"), ["true"])
config = configparser.ConfigParser() config = configparser.ConfigParser()
@@ -88,24 +88,20 @@ class MutmutSetup(unittest.TestCase):
self.assertEqual(config.get("tool:pytest", "addopts"), "-q") self.assertEqual(config.get("tool:pytest", "addopts"), "-q")
def test_a_setup_cfg_that_cannot_be_read_fails(self): def test_a_setup_cfg_that_cannot_be_read_fails(self):
self.assertIsInstance(mutmut_config("[mutmut]\na = 1\na = 2\n", ["a.py"], []), Failure) self.assertIsInstance(mutmut_config("[mutmut]\na = 1\na = 2\n", ["a.py"], ["a.py"], []), Failure)
def test_left_out_names_each_test_the_summary_reports_failing(self): def test_left_out_names_each_test_the_summary_reports_failing(self):
output = textwrap.dedent("""\ output = textwrap.dedent("""\
FAILED fake.py::t - this line is a test's own output, above the summary FAILED fake.py::t - this line is a test's own output, above the summary
ERROR root:x.py:3 a log line ERROR root:x.py:3 a log line
=========================== short test summary info ============================ =========================== short test summary info ============================
FAILED mutants/repo_checks/test_repo_checks.py::Repo::test_a - AssertionError: x - y FAILED repo_checks/test_repo_checks.py::Repo::test_a - AssertionError: x - y
ERROR mutants/larv_review/test_larv_review.py - FileNotFoundError: SKILL.md ERROR larv_review/test_larv_review.py - FileNotFoundError: SKILL.md
ERROR test_io.py
FAILED a/test_b.py::T::test_c FAILED a/test_b.py::T::test_c
2 failed, 2 errors in 3.10s 2 failed, 1 error in 3.10s
failed to collect stats. runner returned 1 failed to collect stats. runner returned 1
""") """)
self.assertEqual(left_out(output), ["mutants/repo_checks/test_repo_checks.py::Repo::test_a", "mutants/larv_review/test_larv_review.py", "test_io.py", "a/test_b.py::T::test_c"]) self.assertEqual(left_out(output), ["--deselect=repo_checks/test_repo_checks.py::Repo::test_a", "--ignore=larv_review/test_larv_review.py", "--deselect=a/test_b.py::T::test_c"])
def test_a_test_is_deselected_by_its_nodeid_and_a_file_ignored_by_its_path_in_mutants(self):
self.assertEqual(leaving_out(["mutants/t/test_a.py::T::test_b", "mutants/t/test_c.py", "t/test_d.py"], "/copy"), ["--deselect=mutants/t/test_a.py::T::test_b", "--ignore=/copy/mutants/t/test_c.py", "--ignore=/copy/mutants/t/test_d.py"])
def test_left_out_is_empty_without_a_summary(self): def test_left_out_is_empty_without_a_summary(self):
self.assertEqual(left_out("failed to collect stats. runner returned 1\n"), []) self.assertEqual(left_out("failed to collect stats. runner returned 1\n"), [])
@@ -145,15 +141,15 @@ class MutmutMutants(unittest.TestCase):
# Stands in for mutmut, run through --prefix as `python3 <this> <log> <mode> mutmut ...` in the scratch copy. It logs each call with # Stands in for mutmut, run through --prefix as `python3 <this> <log> <mode> mutmut ...` in the scratch copy. It logs each call with
# the setup.cfg it finds there, then writes a mutants/ copy and prints results, both shaped like mutmut 3's. # the setup.cfg it finds there, then writes a mutants/ copy and prints results, both shaped like mutmut 3's.
FAKE_MUTMUT = r"""import os, pathlib, sys FAKE_MUTMUT = r"""import pathlib, sys
log, mode, args = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3:] log, mode, args = pathlib.Path(sys.argv[1]), sys.argv[2], sys.argv[3:]
config = pathlib.Path("setup.cfg").read_text() config = pathlib.Path("setup.cfg").read_text()
with log.open("a") as written: with log.open("a") as written:
written.write(" ".join(args) + "\n" + config + "---\n") written.write(" ".join(args) + "\n" + config + "---\n")
if args[:2] == ["mutmut", "results"]: if args[:2] == ["mutmut", "results"]:
print(" calc.x_triple__mutmut_1: survived\n calc.x_triple__mutmut_2: killed\n calc.x_double__mutmut_1: survived") print(" calc.x_triple__mutmut_1: survived\n calc.x_triple__mutmut_2: killed\n calc.x_double__mutmut_1: survived")
elif mode == "fails-once" and not ("--deselect=mutants/test_calc.py::Calc::test_slow" in config and f"--ignore={os.getcwd()}/mutants/test_io.py" in config): elif mode == "fails-once" and not ("--deselect=test_calc.py::Calc::test_slow" in config and "--ignore=test_io.py" in config):
print("==== short test summary info ====\nFAILED mutants/test_calc.py::Calc::test_slow - boom\nERROR mutants/test_io.py - FileNotFoundError\nfailed to collect stats. runner returned 1") print("==== short test summary info ====\nFAILED test_calc.py::Calc::test_slow - boom\nERROR test_io.py - FileNotFoundError\nfailed to collect stats. runner returned 1")
sys.exit(1) sys.exit(1)
else: else:
pathlib.Path("mutants").mkdir(exist_ok=True) pathlib.Path("mutants").mkdir(exist_ok=True)
@@ -201,6 +197,7 @@ class MutateChangesTool(unittest.TestCase):
calls = self.log.read_text() calls = self.log.read_text()
self.assertIn("mutmut run --max-children 2 calc.x_triple*\n", calls) self.assertIn("mutmut run --max-children 2 calc.x_triple*\n", calls)
self.assertIn("source_paths = calc.py\n", calls) self.assertIn("source_paths = calc.py\n", calls)
self.assertIn("also_copy = calc.py\n\tsetup.cfg\n\ttest_calc.py\n", calls)
self.assertEqual((self.checkout / "pkg" / "setup.cfg").read_text(), "[mutmut]\n") self.assertEqual((self.checkout / "pkg" / "setup.cfg").read_text(), "[mutmut]\n")
self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "pkg"]) self.assertEqual(sorted(path.name for path in self.checkout.iterdir()), [".git", "pkg"])