Spaces:
Running
Running
File size: 3,263 Bytes
ee446e8 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | #!/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()
|