Answer principles round 1: 1 🔴, 7 🟡 (0 misread); every effect is handed in as an argument, no test patches a global, and the traces principle scopes tools that run on their user's machine
CI / tests (pull_request) Successful in 3m43s

This commit is contained in:
2026-11-19 12:42:03 +01:00
parent 8ca612b7a4
commit cb3135bc8c
124 changed files with 1437 additions and 793 deletions
+8 -8
View File
@@ -3,16 +3,16 @@ import os
import pathlib
from mutate_changes.changed_lines import by_folder, label, runs
from mutate_changes.tool_process import failed, Ran, remove, run_tool, scratch_folder
from mutate_changes.tool_process import failed, Ran, remove, Run, scratch_folder
from failure import Failure
from git_cli.git_repo import git
from git_cli.git_repo import Git
# cargo-mutants' exit codes for a run that finished: every mutant caught, some missed, and some timed out.
CARGO_FINISHED = frozenset({0, 2, 3})
CARGO_OUTCOMES = ("caught", "missed", "timeout", "unviable")
def run_cargo_mutants(top: str, base: str, paths: list[str], prefix: str | None, jobs: int) -> list[str] | Failure:
def run_cargo_mutants(top: str, base: str, paths: list[str], run: Run, git: Git, jobs: int) -> list[str] | Failure:
"""A line with cargo-mutants' mutant count, then a line per mutant it missed or that timed out, as `<path>:<line>:<column>: <outcome>: <mutation>`.
cargo-mutants runs in top."""
@@ -26,7 +26,7 @@ def run_cargo_mutants(top: str, base: str, paths: list[str], prefix: str | None,
try:
pathlib.Path(scratch, "branch.diff").write_text(diff, encoding="utf-8")
relative = os.path.relpath(scratch, top)
ran = run_tool(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top, prefix)
ran = run(["cargo", "mutants", "--in-diff", os.path.join(relative, "branch.diff"), "--output", relative, "--jobs", str(jobs)], top)
if isinstance(ran, Failure) or ran.code not in CARGO_FINISHED:
return ran if isinstance(ran, Failure) else failed("cargo mutants", ran)
outcomes = {outcome: outcome_lines(pathlib.Path(scratch, "mutants.out", f"{outcome}.txt")) for outcome in CARGO_OUTCOMES}
@@ -44,7 +44,7 @@ def outcome_lines(path: pathlib.Path) -> list[str]:
# Stryker and Infection also exit nonzero on a mutation score below a threshold the project sets, which their exit code doesn't
# tell from a run that broke, so either fails the run.
def run_stryker(top: str, changed: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure:
def run_stryker(top: str, changed: dict[str, frozenset[int]], run: Run, jobs: int) -> list[str] | Failure:
"""For each folder Stryker runs in, a line naming it, then Stryker's own report of the mutants on the changed lines. Last, a line
naming the files with no package.json above them, if any.
@@ -58,16 +58,16 @@ def run_stryker(top: str, changed: dict[str, frozenset[int]], prefix: str | None
unplaced = sorted(files)
continue
mutate = ",".join(f"{path}:{first}-{last}" for path, lines in sorted(files.items()) for first, last in runs(lines))
ran = run_tool(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder), prefix)
ran = run(["npx", "--no", "--package=@stryker-mutator/core", "stryker", "run", "--mutate", mutate, "--concurrency", str(jobs), "--reporters", "clear-text"], os.path.join(top, folder))
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else whole_output(f"Stryker in {label(folder)}", ran)
report.extend([f"Stryker in {label(folder)}:", *ran.output.splitlines()])
return [*report, *([f"Not mutated, as no package.json is above them: {', '.join(unplaced)}."] if unplaced else [])]
def run_infection(top: str, base: str, prefix: str | None, jobs: int) -> list[str] | Failure:
def run_infection(top: str, base: str, run: Run, jobs: int) -> list[str] | Failure:
"""A line naming where Infection ran, top, then its own report of the mutants on the lines the branch changes since base."""
ran = run_tool(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top, prefix)
ran = run(["vendor/bin/infection", "--git-diff-lines", f"--git-diff-base={base}", f"--threads={jobs}", "--show-mutations=max", "--no-progress"], top)
if isinstance(ran, Failure) or ran.code:
return ran if isinstance(ran, Failure) else whole_output("Infection", ran)
return ["Infection in the checkout's top:", *ran.output.splitlines()]
+21 -13
View File
@@ -42,22 +42,28 @@ Exit 1 too when git fails, a file cannot be read or copied, a tool cannot start,
Infection also exit nonzero on a mutation score below a threshold the project sets, which fails the run as well and prints their
whole report.
"""
import functools
import os
import sys
import time
import typing
from mutate_changes.changed_lines import added_lines, not_mutated, tool_for
from machine_load.slots import CPUS_PER_SLOT
from git_cli.git_repo import default_ref, git, top
from git_cli.git_repo import default_ref, Git, top
from failure import Failure
from git_cli import git_repo
from mutate_changes.in_diff_tools import run_cargo_mutants, run_infection, run_stryker
from mutate_changes.mutmut_tool import run_mutmut
from mutate_changes.tool_process import run_tool
USAGE = "usage: mutate-changes [--base <ref>] [--prefix <shell text>] [--jobs <n>]"
# A panel of three readers, seated as the README's audience, picked the command's name and these options on 2026-11-11.
OPTIONS = ("--base", "--jobs", "--prefix")
def main(argv: list[str]) -> int:
def main(argv: list[str], env: typing.Mapping[str, str]) -> int:
"""Runs mutate-changes with the arguments argv; git and each tool run in the environment env."""
if argv in (["-h"], ["--help"]):
print(__doc__.strip())
return 0
@@ -66,7 +72,7 @@ def main(argv: list[str]) -> int:
print(f"{given.reason}; {USAGE}", file=sys.stderr)
return 1
started = time.monotonic()
report = mutate(given)
report = mutate(given, env)
if isinstance(report, Failure):
print(report.reason, file=sys.stderr)
return 1
@@ -89,12 +95,13 @@ def options(argv: list[str]) -> dict[str, str] | Failure:
return given
def mutate(given: dict[str, str]) -> list[str] | Failure:
def mutate(given: dict[str, str], env: typing.Mapping[str, str]) -> list[str] | Failure:
"""Each tool's report on the lines the branch adds, then the lines naming the changed files no tool mutates."""
checkout = top()
git = functools.partial(git_repo.git, env=env)
checkout = top(git)
if isinstance(checkout, Failure):
return checkout
base = given.get("--base") or default_ref(cwd=checkout)
base = given.get("--base") or default_ref(cwd=checkout, run=git)
if isinstance(base, Failure):
return base
found = git("merge-base", base, "HEAD", cwd=checkout)
@@ -105,27 +112,28 @@ def mutate(given: dict[str, str]) -> list[str] | Failure:
if isinstance(names, Failure):
return names
paths = list(filter(None, names.split("\0")))
changed = changed_by_tool(checkout, merge_base, paths)
changed = changed_by_tool(checkout, merge_base, paths, git)
if isinstance(changed, Failure):
return changed
prefix, jobs = given.get("--prefix"), int(given.get("--jobs", CPUS_PER_SLOT))
jobs = int(given.get("--jobs", CPUS_PER_SLOT))
run = functools.partial(run_tool, prefix=given.get("--prefix"), env=env, killpg=os.killpg)
report = [] if changed else ["No tool ran: the branch adds no line to a file that a tool mutates."]
for tool, files in sorted(changed.items()):
if tool == "cargo-mutants":
lines = run_cargo_mutants(checkout, merge_base, sorted(files), prefix, jobs)
lines = run_cargo_mutants(checkout, merge_base, sorted(files), run, git, jobs)
elif tool == "infection":
lines = run_infection(checkout, merge_base, prefix, jobs)
lines = run_infection(checkout, merge_base, run, jobs)
elif tool == "stryker":
lines = run_stryker(checkout, files, prefix, jobs)
lines = run_stryker(checkout, files, run, jobs)
else:
lines = run_mutmut(checkout, files, prefix, jobs)
lines = run_mutmut(checkout, files, run, git, jobs)
if isinstance(lines, Failure):
return lines
report.extend(lines)
return [*report, *not_mutated(paths)]
def changed_by_tool(checkout: str, merge_base: str, paths: list[str]) -> dict[str, dict[str, frozenset[int]]] | Failure:
def changed_by_tool(checkout: str, merge_base: str, paths: list[str], git: Git) -> dict[str, dict[str, frozenset[int]]] | Failure:
"""Each tool's files among paths, by path from the checkout's top, with the lines the working tree adds since merge_base."""
changed: dict[str, dict[str, frozenset[int]]] = {}
for path in paths:
+15 -15
View File
@@ -11,10 +11,10 @@ import shutil
import tomllib
from mutate_changes.changed_lines import by_folder, label
from mutate_changes.tool_process import failed, Ran, remove, run_tool, scratch_folder
from mutate_changes.tool_process import failed, Ran, remove, Run, scratch_folder
from failure import Failure
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 left_out, mutmut_config
CAUGHT = frozenset({"caught by type check", "killed"})
@@ -42,20 +42,20 @@ class Folder:
return label(self.path)
def run_mutmut(top: str, changed: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure:
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(by_folder(top, changed, CONFIGS).items()):
lines = mutate_folder(top, path, files, prefix, jobs)
lines = mutate_folder(top, path, files, run, git, jobs)
if isinstance(lines, Failure):
return lines
report.extend(lines)
return report
def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], prefix: str | None, jobs: int) -> list[str] | Failure:
def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], run: Run, git: Git, jobs: int) -> list[str] | Failure:
root = os.path.join(top, path)
folder = read_folder(root, path, files)
if isinstance(folder, Failure):
@@ -72,7 +72,7 @@ def mutate_folder(top: str, path: str, files: dict[str, frozenset[int]], prefix:
try:
copy = os.path.join(scratch, "copy")
copied = copy_files(root, listed.split("\0"), copy)
return mutate_copy(copy, copied, folder, ["mutmut", "run", "--max-children", str(jobs), *globs], prefix)
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}")
finally:
@@ -122,8 +122,8 @@ 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], prefix: str | None) -> list[str] | Failure:
ran = run_until_stats_pass(copy, copied, folder, argv, prefix)
def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], run: Run) -> list[str] | Failure:
ran = run_until_stats_pass(copy, copied, folder, argv, run)
if isinstance(ran, Failure):
return ran
output, left = ran
@@ -131,7 +131,7 @@ def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], p
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."]
results = run_tool(["mutmut", "results", "--all", "true"], copy, prefix)
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)
@@ -141,14 +141,14 @@ def mutate_copy(copy: str, copied: list[str], folder: Folder, argv: list[str], p
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, copied: list[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], run: Run) -> tuple[str, list[str]] | Failure:
"""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, copied, folder, [], argv, prefix)
ran = configured_run(copy, copied, folder, [], argv, run)
left: list[str] = []
if isinstance(ran, Ran) and STATS_FAILED in ran.output:
ran = configured_run(copy, copied, folder, LIST_FAILURES, argv, prefix)
ran = configured_run(copy, copied, folder, LIST_FAILURES, argv, run)
if isinstance(ran, Ran) and STATS_FAILED in ran.output and (left := left_out(ran.output)):
ran = configured_run(copy, copied, folder, left, argv, prefix)
ran = configured_run(copy, copied, folder, left, argv, run)
if isinstance(ran, Failure):
return ran
if ran.code and NO_MUTANT not in ran.output and NO_TEST not in ran.output:
@@ -156,12 +156,12 @@ def run_until_stats_pass(copy: str, copied: list[str], folder: Folder, argv: lis
return ran.output, left
def configured_run(copy: str, copied: list[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], run: Run) -> Ran | Failure:
config = mutmut_config(folder.setup, sorted(folder.files), copied, options)
if isinstance(config, Failure):
return Failure(f"{folder.label}: {config.reason}")
pathlib.Path(copy, "setup.cfg").write_text(config, encoding="utf-8")
return run_tool(argv, copy, prefix)
return run(argv, copy)
def not_killed(folder: Folder, found: dict[str, str], copy: str) -> tuple[list[str], int]:
+7 -7
View File
@@ -8,8 +8,8 @@ import tempfile
import textwrap
import threading
import time
import typing
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
@@ -226,8 +226,8 @@ class ToolProcess(unittest.TestCase):
self.assertTrue(pathlib.Path(folder, "stopped").is_file())
def test_an_interrupted_tool_that_ignores_sigint_is_killed_after_the_grace_period(self):
with tempfile.TemporaryDirectory() as folder, unittest.mock.patch("mutate_changes.tool_process.GRACE_SECONDS", 0.5):
self.assertLess(self.interrupted(folder, "trap '' INT; echo $$ > started; sleep 60;"), 30)
with tempfile.TemporaryDirectory() as folder:
self.assertLess(self.interrupted(folder, "trap '' INT; echo $$ > started; sleep 60;", grace=0.5), 30)
self.assert_ends(int(pathlib.Path(folder, "started").read_text()))
def test_an_interrupt_ends_the_run_where_the_tool_s_processes_end_first(self):
@@ -237,10 +237,10 @@ class ToolProcess(unittest.TestCase):
killpg(group, number)
raise ProcessLookupError
with unittest.mock.patch("os.killpg", then_gone), tempfile.TemporaryDirectory() as folder:
self.interrupted(folder, "sleep 60 & echo $! > started; wait;")
with tempfile.TemporaryDirectory() as folder:
self.interrupted(folder, "sleep 60 & echo $! > started; wait;", killpg=then_gone)
def interrupted(self, folder: str, script: str) -> float:
def interrupted(self, folder: str, script: str, **seams: typing.Any) -> float:
"""Run script as the prefix of a tool in folder, interrupt run_tool once script writes folder/started, and return how long run_tool took."""
started = pathlib.Path(folder, "started")
@@ -252,7 +252,7 @@ class ToolProcess(unittest.TestCase):
threading.Thread(target=interrupt, daemon=True).start()
began = time.monotonic()
with self.assertRaises(KeyboardInterrupt):
run_tool(["true"], folder, script)
run_tool(["true"], folder, **{"prefix": script, "env": os.environ, "killpg": os.killpg, **seams})
return time.monotonic() - began
def assert_ends(self, pid: int) -> None:
@@ -1,5 +1,6 @@
"""mutate-changes run on a branch, against fake mutation tools that log how they were called."""
import contextlib
import functools
import io
import os
import pathlib
@@ -11,14 +12,15 @@ import sys
import tempfile
import time
import unittest
import unittest.mock
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
from mutate_changes.test_mutate_changes import ended
from git_cli import git_repo
from test_env import isolated_env
from mutate_changes import main
from mutate_changes.in_diff_tools import run_cargo_mutants
from mutate_changes.tool_process import run_tool
TOOL = pathlib.Path(__file__).resolve().parents[1] / "mutate-changes"
SETUP = "[mutmut]\ndo_not_mutate = *_old.py\n"
@@ -138,8 +140,8 @@ class MutateChangesRuns(unittest.TestCase):
before = os.getcwd()
os.chdir(cwd or self.checkout)
try:
with unittest.mock.patch.dict(os.environ, {**isolated_env(), **(env or {})}, clear=True), contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:
code = main.main(list(args))
with contextlib.redirect_stdout(io.StringIO()) as out, contextlib.redirect_stderr(io.StringIO()) as err:
code = main.main(list(args), {**isolated_env(), **(env or {})})
finally:
os.chdir(before)
return subprocess.CompletedProcess(args, code, out.getvalue(), err.getvalue())
@@ -361,8 +363,10 @@ class MutateChangesRuns(unittest.TestCase):
(self.checkout / "-x.py").write_text("def f():\n\treturn 1\n")
(self.checkout / "-x.rs").write_text("fn f() {}\n")
base = self.git("rev-parse", "HEAD").strip()
self.assertEqual(main.changed_by_tool(str(self.checkout), base, ["-x.py", "-x.rs"]), {"cargo-mutants": {"-x.rs": frozenset({1})}, "mutmut": {"-x.py": frozenset({1, 2})}})
ran = run_cargo_mutants(str(self.checkout), base, ["-x.rs"], f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", 1)
git = functools.partial(git_repo.git, env=isolated_env())
self.assertEqual(main.changed_by_tool(str(self.checkout), base, ["-x.py", "-x.rs"], git), {"cargo-mutants": {"-x.rs": frozenset({1})}, "mutmut": {"-x.py": frozenset({1, 2})}})
run = functools.partial(run_tool, prefix=f"python3 {self.temp / 'fake_tools.py'} {self.log} 0", env=isolated_env(), killpg=os.killpg)
ran = run_cargo_mutants(str(self.checkout), base, ["-x.rs"], run, git, 1)
self.assertIsInstance(ran, list)
self.assertIn("+++ b/-x.rs\n", self.log.read_text())
+14 -7
View File
@@ -1,7 +1,6 @@
"""Start a mutation tool, through --prefix's shell text where the run gives one, and wait for it; and make and remove its scratch folder."""
import contextlib
import dataclasses
import os
import pathlib
import shlex
import shutil
@@ -9,6 +8,7 @@ import signal
import subprocess
import sys
import tempfile
import typing
from failure import Failure
@@ -21,14 +21,21 @@ class Ran:
output: str # stdout and stderr, as the tool interleaved them
def run_tool(argv: list[str], cwd: str, prefix: str | None) -> Ran | Failure:
"""Run a tool in cwd, reading each byte of its output that is not UTF-8 as U+FFFD.
class Run(typing.Protocol):
"""Runs a tool in cwd as `run_tool` does, with the run's prefix, environment and killpg bound."""
def __call__(self, argv: list[str], cwd: str) -> Ran | Failure: ...
# The tests hand in a shorter grace, and a killpg that finds the tool's processes gone.
def run_tool(argv: list[str], cwd: str, *, prefix: str | None, env: typing.Mapping[str, str], killpg: typing.Callable[[int, int], None], grace: float = GRACE_SECONDS) -> Ran | Failure:
"""Run a tool in cwd with the environment env, reading each byte of its output that is not UTF-8 as U+FFFD.
With a prefix, sh runs `<prefix> "$@"` with argv as its arguments, so the prefix keeps its own quoting and each of argv stays one word."""
command = ["sh", "-c", f'{prefix} "$@"', "sh", *argv] if prefix else argv
try:
# In a session of its own, the tool and each process it starts share one process group, which ends whole below.
process = subprocess.Popen(command, cwd=cwd, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", start_new_session=True)
process = subprocess.Popen(command, cwd=cwd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8", errors="replace", start_new_session=True)
except OSError as failure:
return Failure(f"{shlex.join(argv)} could not start: {failure.strerror}")
try:
@@ -38,12 +45,12 @@ def run_tool(argv: list[str], cwd: str, prefix: str | None) -> Ran | Failure:
# reaches only this process, so pass the tool SIGINT first: a container's CLI, such as docker compose, then stops its container.
try:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGINT)
killpg(process.pid, signal.SIGINT)
with contextlib.suppress(subprocess.TimeoutExpired):
process.wait(timeout=GRACE_SECONDS)
process.wait(timeout=grace)
finally:
with contextlib.suppress(ProcessLookupError):
os.killpg(process.pid, signal.SIGKILL)
killpg(process.pid, signal.SIGKILL)
process.wait()
raise
return Ran(process.returncode, output)