stocks / scripts /mutation.py
user
python version
ee446e8
Raw History Blame Contribute Delete
3.26 kB
#!/usr/bin/env python3
"""Run mutation testing with optional per-file scoping.
Usage:
python scripts/mutation.py # full configured scope
python scripts/mutation.py core/dsl/security.py # single file
python scripts/mutation.py core/dsl/ # all files in a directory
When paths are provided, mutmut's ``only_mutate`` config is temporarily
set so that only the matching files are mutated; the rest of the project
is still copied into mutants/ so imports keep working.
"""
import shutil
import signal
import subprocess
import sys
from pathlib import Path
PROJECT_ROOT = Path(__file__).resolve().parent.parent
PYPROJECT = PROJECT_ROOT / "pyproject.toml"
BACKUP = PYPROJECT.with_suffix(".toml.mutmut_backup")
def _restore_and_exit(signum: int, _frame: object) -> None:
# Python's default handling of SIGTERM/SIGINT does NOT run try/finally
# blocks the way a raised exception would -- a raw signal can end the
# process before `main`'s finally executes, leaving `only_mutate`
# stuck in the shared pyproject.toml. Restoring here, synchronously,
# in the handler closes that gap.
if BACKUP.exists():
shutil.copy2(BACKUP, PYPROJECT)
BACKUP.unlink()
sys.exit(128 + signum)
def normalize_paths(paths: list[str]) -> list[str]:
normalized = []
for p in paths:
if not p.endswith(".py"):
p = p.rstrip("/") + "/*"
normalized.append(p)
return normalized
def set_only_mutate(pyproject_path: Path, paths: list[str]) -> None:
text = pyproject_path.read_text()
lines = text.split("\n")
new_lines = []
in_mutmut = False
inserted = False
for line in lines:
stripped = line.strip()
if stripped == "[tool.mutmut]":
in_mutmut = True
elif stripped.startswith("[") and in_mutmut:
in_mutmut = False
if in_mutmut and stripped.startswith("only_mutate"):
new_lines.append(f"only_mutate = {paths!r}")
inserted = True
continue
new_lines.append(line)
if in_mutmut and not inserted and stripped.startswith("source_paths"):
new_lines.append(f"only_mutate = {paths!r}")
inserted = True
if not inserted:
raise ValueError("Could not insert only_mutate into [tool.mutmut]")
pyproject_path.write_text("\n".join(new_lines))
def main() -> None:
if BACKUP.exists():
print(f"⚠️ Found leftover {BACKUP.name} from a previous crashed/killed run -- restoring it first.")
shutil.copy2(BACKUP, PYPROJECT)
BACKUP.unlink()
raw_paths = sys.argv[1:]
paths = normalize_paths(raw_paths) if raw_paths else None
if paths:
signal.signal(signal.SIGTERM, _restore_and_exit)
signal.signal(signal.SIGINT, _restore_and_exit)
shutil.copy2(PYPROJECT, BACKUP)
try:
set_only_mutate(PYPROJECT, paths)
subprocess.run(["uv", "run", "mutmut", "run"], check=True)
finally:
if BACKUP.exists():
shutil.copy2(BACKUP, PYPROJECT)
BACKUP.unlink()
else:
subprocess.run(["uv", "run", "mutmut", "run"], check=True)
if __name__ == "__main__":
main()