@jesdi/skills 0.0.81 → 0.0.83
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +2 -1
- package/skills/crap-gate/launcher.sh +104 -0
- package/skills/crap-gate/run.sh +15 -75
- package/skills/crap-gate/test_launcher.py +39 -0
- package/skills/implement-spec/launcher.sh +104 -0
- package/skills/implement-spec/run.sh +10 -89
- package/skills/implement-spec/tests/test_launcher.py +138 -0
- package/skills/test-weigh-in/SKILL.md +16 -0
- package/skills/test-weigh-in/dashboard.html +112 -0
- package/skills/test-weigh-in/launcher.sh +104 -0
- package/skills/test-weigh-in/rules.toml +134 -0
- package/skills/test-weigh-in/run.sh +21 -0
- package/skills/test-weigh-in/tests/brittle_repo.py +79 -0
- package/skills/test-weigh-in/tests/conftest.py +35 -0
- package/skills/test-weigh-in/tests/fixture_repo.py +99 -0
- package/skills/test-weigh-in/tests/kill_repo.py +87 -0
- package/skills/test-weigh-in/tests/maint_repo.py +139 -0
- package/skills/test-weigh-in/tests/map_fixture.py +56 -0
- package/skills/test-weigh-in/tests/pt_repo.py +46 -0
- package/skills/test-weigh-in/tests/red_repo.py +44 -0
- package/skills/test-weigh-in/tests/rule_repo.py +208 -0
- package/skills/test-weigh-in/tests/rules_fixture.py +65 -0
- package/skills/test-weigh-in/tests/smell_repo.py +138 -0
- package/skills/test-weigh-in/tests/test_brittleness.py +75 -0
- package/skills/test-weigh-in/tests/test_brittleness_history.py +168 -0
- package/skills/test-weigh-in/tests/test_coverage_run.py +201 -0
- package/skills/test-weigh-in/tests/test_coverage_value.py +76 -0
- package/skills/test-weigh-in/tests/test_dashboard_map.py +20 -0
- package/skills/test-weigh-in/tests/test_interpreters.py +115 -0
- package/skills/test-weigh-in/tests/test_kill_matrix.py +126 -0
- package/skills/test-weigh-in/tests/test_maintainability_smells.py +113 -0
- package/skills/test-weigh-in/tests/test_mutation_recovery.py +67 -0
- package/skills/test-weigh-in/tests/test_mutation_sampling.py +53 -0
- package/skills/test-weigh-in/tests/test_mutation_score.py +140 -0
- package/skills/test-weigh-in/tests/test_mutation_stale.py +30 -0
- package/skills/test-weigh-in/tests/test_mutmut_contract.py +43 -0
- package/skills/test-weigh-in/tests/test_ruff_pt_smells.py +45 -0
- package/skills/test-weigh-in/tests/test_runs.py +175 -0
- package/skills/test-weigh-in/tests/test_score.py +26 -0
- package/skills/test-weigh-in/tests/test_scoring.py +154 -0
- package/skills/test-weigh-in/tests/test_smell_rules.py +96 -0
- package/skills/test-weigh-in/tests/test_smells.py +71 -0
- package/skills/test-weigh-in/tests/test_walking_skeleton.py +91 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/demo/__init__.py +0 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/demo/board.py +2 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/demo/config.py +2 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/pyproject.toml +8 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_board.py +19 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_config.py +19 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_parser.py +19 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_render.py +19 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_report.py +17 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_session.py +19 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_store.py +17 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_sync.py +17 -0
- package/skills/test-weigh-in/tests/testdata/default_repo/uv.lock +1 -0
- package/skills/test-weigh-in/weigh.py +133 -0
- package/skills/test-weigh-in/weigh_coverage.py +154 -0
- package/skills/test-weigh-in/weigh_dashboard.py +72 -0
- package/skills/test-weigh-in/weigh_env.py +112 -0
- package/skills/test-weigh-in/weigh_git.py +119 -0
- package/skills/test-weigh-in/weigh_inventory.py +49 -0
- package/skills/test-weigh-in/weigh_mutation.py +190 -0
- package/skills/test-weigh-in/weigh_pytest_plugin.py +56 -0
- package/skills/test-weigh-in/weigh_ruff.py +22 -0
- package/skills/test-weigh-in/weigh_rules.py +65 -0
- package/skills/test-weigh-in/weigh_runs.py +173 -0
- package/skills/test-weigh-in/weigh_score.py +80 -0
- package/skills/test-weigh-in/weigh_smells.py +355 -0
- package/skills/test-weigh-in/weigh_snapshot.py +49 -0
- package/skills-manifest.json +11 -5
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""The target repo's interpreter and the overlay that carries the measurement plugin."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import subprocess
|
|
7
|
+
import tempfile
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
HERE = Path(__file__).resolve().parent
|
|
11
|
+
PLUGIN = "weigh_pytest_plugin.py"
|
|
12
|
+
MIN_PYTHON = (3, 10)
|
|
13
|
+
MIN_PYTEST = (7, 0)
|
|
14
|
+
# the wrapper's cached uv; a direct `python3 weigh.py` uses the one on PATH
|
|
15
|
+
# the mutation tier's tool and its closure, every package pinned and installed --no-deps
|
|
16
|
+
MUTMUT = "mutmut==3.8.1"
|
|
17
|
+
# `uv pip compile --universal --python-version 3.10` of MUTMUT, minus pytest and its own closure (pluggy, iniconfig,
|
|
18
|
+
# packaging, exceptiongroup, tomli): those come from the target repo
|
|
19
|
+
MUTMUT_CLOSURE = (
|
|
20
|
+
MUTMUT, "click==8.5.0", "colorama==0.4.6; sys_platform == 'win32'",
|
|
21
|
+
"coverage==7.16.2; python_full_version < '3.11'", "coverage==7.17.0; python_full_version >= '3.11'",
|
|
22
|
+
"libcst==1.9.0", "linkify-it-py==2.2.0", "markdown-it-py==4.2.0", "mdit-py-plugins==0.6.1", "mdurl==0.1.2",
|
|
23
|
+
"platformdirs==4.12.4; python_full_version < '3.11'", "platformdirs==4.14.3; python_full_version >= '3.11'",
|
|
24
|
+
"pygments==2.21.0", "pyyaml==6.0.3; python_full_version != '3.13.*'", "pyyaml-ft==8.0.0; python_full_version == '3.13.*'",
|
|
25
|
+
"rich==15.0.0", "setproctitle==1.3.8", "textual==8.2.8", "toml==0.10.2; python_full_version < '3.11'",
|
|
26
|
+
"typing-extensions==4.16.0",
|
|
27
|
+
)
|
|
28
|
+
UV = os.environ.get("TEST_WEIGH_IN_UV") or "uv"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class SetupError(Exception):
|
|
32
|
+
pass
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def find_interpreter(repo, explicit=None):
|
|
36
|
+
"""--python wins, then a venv synced from uv.lock when .venv is missing (frozen: the lock is never rewritten), then .venv, then venv."""
|
|
37
|
+
if explicit:
|
|
38
|
+
return Path(explicit).absolute() # not resolve(): a venv's python is a symlink to the base one
|
|
39
|
+
if (repo / "uv.lock").is_file() and not (repo / ".venv").exists():
|
|
40
|
+
proc = subprocess.run([UV, "sync", "--frozen", "-q"], cwd=repo, capture_output=True, text=True)
|
|
41
|
+
if proc.returncode:
|
|
42
|
+
raise SetupError("uv sync failed:\n" + proc.stdout + proc.stderr)
|
|
43
|
+
for rel in (".venv/bin/python", "venv/bin/python"):
|
|
44
|
+
if (repo / rel).is_file():
|
|
45
|
+
return repo / rel
|
|
46
|
+
raise SetupError(f"no interpreter found in {repo}: pass --python PATH")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def check_versions(python):
|
|
50
|
+
"""Refuse an interpreter or pytest below the supported minimum, before any test runs."""
|
|
51
|
+
code = ("import sys\nprint('.'.join(map(str, sys.version_info[:3])))\n"
|
|
52
|
+
"from importlib.metadata import version\nprint(version('pytest'))")
|
|
53
|
+
proc = subprocess.run([str(python), "-I", "-B", "-c", code], capture_output=True, text=True)
|
|
54
|
+
if proc.returncode:
|
|
55
|
+
raise SetupError(f"cannot read the versions of {python} (is pytest installed?):\n" + proc.stderr)
|
|
56
|
+
py, pytest = proc.stdout.split()
|
|
57
|
+
if tuple(map(int, py.split(".")[:2])) < MIN_PYTHON:
|
|
58
|
+
raise SetupError(f"python {py} is below the supported minimum 3.10")
|
|
59
|
+
if tuple(map(int, re.findall(r"\d+", pytest)[:2])) < MIN_PYTEST:
|
|
60
|
+
raise SetupError(f"pytest {pytest} is below the supported minimum 7.0")
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def cache_root():
|
|
64
|
+
return Path(os.environ.get("TEST_WEIGH_IN_CACHE_DIR") or Path.home() / ".cache" / "test-weigh-in")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _python_version(python):
|
|
68
|
+
return subprocess.run([str(python), "-I", "-B", "-c", "import sys;print(*sys.version_info[:2], sys.implementation.name)"],
|
|
69
|
+
capture_output=True, text=True).stdout.strip()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def mutmut_overlay(python):
|
|
73
|
+
"""The pinned mutmut closure, without pytest's (the target's own is used), keyed by the pins and the interpreter's version."""
|
|
74
|
+
root = cache_root()
|
|
75
|
+
overlay = root / f"mutmut-{hashlib.sha256(chr(0).join((*MUTMUT_CLOSURE, _python_version(python))).encode()).hexdigest()[:16]}"
|
|
76
|
+
if not overlay.is_dir():
|
|
77
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
78
|
+
tmp = Path(tempfile.mkdtemp(dir=root))
|
|
79
|
+
proc = subprocess.run([UV, "pip", "install", "-q", "--python", str(python), "--no-deps", "--target", str(tmp), *MUTMUT_CLOSURE],
|
|
80
|
+
capture_output=True, text=True)
|
|
81
|
+
if proc.returncode:
|
|
82
|
+
shutil.rmtree(tmp)
|
|
83
|
+
raise SetupError(f"cannot install {MUTMUT} into the overlay:\n" + proc.stdout + proc.stderr)
|
|
84
|
+
try:
|
|
85
|
+
tmp.rename(overlay)
|
|
86
|
+
except OSError: # another run won the race
|
|
87
|
+
shutil.rmtree(tmp)
|
|
88
|
+
return overlay
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def build_overlay(python):
|
|
92
|
+
"""Plugin and coverage (installed --no-deps, so no pytest: the repo's pytest is the one used); built aside, then renamed into place.
|
|
93
|
+
|
|
94
|
+
Keyed by the plugin's content and the interpreter's version, so an overlay left by an older plugin or another Python is never reused."""
|
|
95
|
+
root = cache_root()
|
|
96
|
+
version = _python_version(python)
|
|
97
|
+
digest = hashlib.sha256((HERE / PLUGIN).read_bytes() + version.encode()).hexdigest()[:16]
|
|
98
|
+
overlay = root / f"overlay-{digest}"
|
|
99
|
+
if not overlay.is_dir():
|
|
100
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
101
|
+
tmp = Path(tempfile.mkdtemp(dir=root))
|
|
102
|
+
shutil.copy(HERE / PLUGIN, tmp)
|
|
103
|
+
proc = subprocess.run([UV, "pip", "install", "-q", "--no-deps", "--python", str(python), "--target", str(tmp), "coverage"],
|
|
104
|
+
capture_output=True, text=True)
|
|
105
|
+
if proc.returncode:
|
|
106
|
+
shutil.rmtree(tmp)
|
|
107
|
+
raise SetupError("cannot install coverage into the overlay:\n" + proc.stdout + proc.stderr)
|
|
108
|
+
try:
|
|
109
|
+
tmp.rename(overlay)
|
|
110
|
+
except OSError: # another run won the race
|
|
111
|
+
shutil.rmtree(tmp)
|
|
112
|
+
return overlay
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
"""Brittle test files from git history: a test file that changed in over half the commits that changed its mapped sources."""
|
|
2
|
+
import re
|
|
3
|
+
import subprocess
|
|
4
|
+
from typing import NamedTuple
|
|
5
|
+
|
|
6
|
+
from weigh_inventory import is_test
|
|
7
|
+
|
|
8
|
+
# Spec requirement 20: the commit window and the big-commit cutoff (is_brittle holds the "more than half")
|
|
9
|
+
MAX_COMMITS = 200
|
|
10
|
+
MAX_FILES = 20
|
|
11
|
+
SINCE = "12 months ago"
|
|
12
|
+
|
|
13
|
+
RENAME = re.compile(r"R\d*") # git's rename status, with its similarity score
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class Commit(NamedTuple):
|
|
17
|
+
sha: str
|
|
18
|
+
date: int
|
|
19
|
+
parents: list
|
|
20
|
+
files: set
|
|
21
|
+
renames: dict # {old path: new path}, for a commit with one parent
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def brittleness(repo, sources_by_test_file):
|
|
25
|
+
"""{test file: {"sources": [...], "brittle": True | False | None}}, None when unmeasured (no git, no mapped source)."""
|
|
26
|
+
commits = source_commits(repo) if is_repo(repo) else None
|
|
27
|
+
|
|
28
|
+
def brittle(test_file, sources):
|
|
29
|
+
return is_brittle(commits, test_file, sources) if commits is not None and sources else None
|
|
30
|
+
|
|
31
|
+
return {test_file: {"sources": sources, "brittle": brittle(test_file, sources)}
|
|
32
|
+
for test_file, sources in sorted(sources_by_test_file.items())}
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def brittle_percent(test_files):
|
|
36
|
+
"""% of the measured test files that are brittle, or None when none is measured."""
|
|
37
|
+
measured = [info["brittle"] for info in test_files.values() if info["brittle"] is not None]
|
|
38
|
+
return 100 * sum(measured) / len(measured) if measured else None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def is_brittle(commits, test_file, sources):
|
|
42
|
+
"""A test file is brittle when it changed in more than half of the commits that changed its sources: most edits to the
|
|
43
|
+
code under test also needed an edit to the test, the sign of a test tied to how the code works rather than what it does."""
|
|
44
|
+
touching = [files for files in commits if files & set(sources)]
|
|
45
|
+
return 2 * sum(test_file in files for files in touching) > len(touching)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def is_repo(repo):
|
|
49
|
+
return subprocess.run(["git", "rev-parse", "--verify", "-q", "HEAD"], cwd=repo, capture_output=True).returncode == 0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def source_commits(repo):
|
|
53
|
+
"""The files changed by each of the newest 200 commits, by date, of the last 12 months that change a source file and
|
|
54
|
+
at most 20 files. Each file carries the name HEAD gives it, so a renamed source keeps its history."""
|
|
55
|
+
log = _read_log(repo)
|
|
56
|
+
merge_parents = [(commit.sha, parent) for commit in log if len(commit.parents) > 1 for parent in commit.parents]
|
|
57
|
+
commits = [c for c in _with_head_names(log, _merge_renames(repo, merge_parents)) if _changes_source(c.files)]
|
|
58
|
+
commits.sort(key=lambda commit: commit.date, reverse=True) # stable: commits of the same second keep the log's order
|
|
59
|
+
return [commit.files for commit in commits[:MAX_COMMITS]]
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _changes_source(files):
|
|
63
|
+
return len(files) <= MAX_FILES and any(f.endswith(".py") and not is_test(f) for f in files)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _read_log(repo):
|
|
67
|
+
"""The commits of the last 12 months, every child before its parents (--topo-order), with renames detected (-M).
|
|
68
|
+
|
|
69
|
+
A merge lists only the files its resolution changed, those that differ from every parent (--cc): the changes it brings
|
|
70
|
+
in from a branch are counted in that branch's own commits."""
|
|
71
|
+
out = subprocess.run(["git", "log", "-M", "--cc", "--topo-order", f"--since={SINCE}", "--name-status", "-z",
|
|
72
|
+
"--format=%x01%H %ct %P"], cwd=repo, capture_output=True, text=True, check=True).stdout
|
|
73
|
+
log = []
|
|
74
|
+
for block in out.split("\x01")[1:]:
|
|
75
|
+
header, *tokens = [t.strip() for t in block.split("\0") if t.strip()]
|
|
76
|
+
sha, date, *parents = header.split()
|
|
77
|
+
files, renames, tokens = set(), {}, iter(tokens)
|
|
78
|
+
for status in tokens:
|
|
79
|
+
path = next(tokens)
|
|
80
|
+
if RENAME.fullmatch(status): # only a one-parent diff has a rename; a merge's status has a letter per parent
|
|
81
|
+
old, path = path, next(tokens)
|
|
82
|
+
renames[old] = path
|
|
83
|
+
files.add(path)
|
|
84
|
+
log.append(Commit(sha, int(date), parents, files, renames))
|
|
85
|
+
return log
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _with_head_names(log, merge_renames):
|
|
89
|
+
"""The commits of the log with each file under the name HEAD gives it.
|
|
90
|
+
|
|
91
|
+
Each commit hands its parents a map {path at the parent: name at HEAD}, adding the renames between the two, so a
|
|
92
|
+
rename is followed on every branch a merge brought past it, and a later file reusing the old name keeps its own."""
|
|
93
|
+
handed_down = {}
|
|
94
|
+
for commit in log: # every child before its parents
|
|
95
|
+
to_head = handed_down.pop(commit.sha, {})
|
|
96
|
+
for parent in commit.parents:
|
|
97
|
+
renames = commit.renames if len(commit.parents) == 1 else merge_renames[commit.sha, parent]
|
|
98
|
+
parent_map = handed_down.setdefault(parent, {})
|
|
99
|
+
for path, name in {**to_head, **{old: to_head.get(new, new) for old, new in renames.items()}}.items():
|
|
100
|
+
parent_map.setdefault(path, name)
|
|
101
|
+
yield commit._replace(files={to_head.get(f, f) for f in commit.files})
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _merge_renames(repo, merge_parents):
|
|
105
|
+
"""{(merge, parent): {old path: new path}}: the files renamed between each parent of a merge and the merge."""
|
|
106
|
+
if not merge_parents:
|
|
107
|
+
return {}
|
|
108
|
+
# --always prints each pair's merge id, even with no rename, so the output follows the pairs in order
|
|
109
|
+
out = subprocess.run(["git", "diff-tree", "--stdin", "--always", "-M", "-r", "-z", "--name-status", "--diff-filter=R"],
|
|
110
|
+
cwd=repo, input="".join(f"{merge} {parent}\n" for merge, parent in merge_parents),
|
|
111
|
+
capture_output=True, text=True, check=True).stdout
|
|
112
|
+
renames, pairs, tokens = {}, iter(merge_parents), iter(out.split("\0")[:-1])
|
|
113
|
+
for token in tokens:
|
|
114
|
+
if RENAME.fullmatch(token):
|
|
115
|
+
old, new = next(tokens), next(tokens)
|
|
116
|
+
current[old] = new
|
|
117
|
+
else: # the merge id that opens the next pair
|
|
118
|
+
current = renames[next(pairs)] = {}
|
|
119
|
+
return renames
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Which tracked Python files are tests or source, and how many lines they hold."""
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import subprocess
|
|
5
|
+
from fnmatch import fnmatchcase
|
|
6
|
+
from posixpath import split
|
|
7
|
+
|
|
8
|
+
# The one definition of a test file: any file under a folder of TEST_DIRS, or a file whose name matches TEST_NAMES.
|
|
9
|
+
TEST_DIRS = ("tests", "test")
|
|
10
|
+
TEST_NAMES = ("test_*.py", "*_test.py", "conftest.py")
|
|
11
|
+
# The same, as glob patterns relative to any folder, for coverage's --omit.
|
|
12
|
+
TEST_GLOBS = tuple(f"{d}/**" for d in TEST_DIRS) + TEST_NAMES
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
# git's message for a folder with no repository above it; a broken .git file says "not a git repository: <path>"
|
|
16
|
+
NO_REPOSITORY = re.compile(r"not a git repository \(or any (of the )?parent")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def is_test(rel):
|
|
20
|
+
"""A repo-relative posix path is a test file."""
|
|
21
|
+
folder, name = split(rel)
|
|
22
|
+
return any(d in TEST_DIRS for d in folder.split("/")) or any(fnmatchcase(name, n) for n in TEST_NAMES)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def python_files(repo):
|
|
26
|
+
"""Tracked Python files of a git work tree; in a folder git finds no repository above, every one outside hidden folders.
|
|
27
|
+
|
|
28
|
+
Any other git failure (an unreadable index, an unsafe directory) raises: it never falls back to the untracked files."""
|
|
29
|
+
probe = subprocess.run(["git", "rev-parse", "--is-inside-work-tree"], cwd=repo, capture_output=True, text=True,
|
|
30
|
+
env={**os.environ, "LC_ALL": "C"})
|
|
31
|
+
if probe.returncode and NO_REPOSITORY.search(probe.stderr):
|
|
32
|
+
rels = (p.relative_to(repo).as_posix() for p in repo.rglob("*.py"))
|
|
33
|
+
return sorted(r for r in rels if not any(x.startswith(".") or x in ("site-packages", "__pycache__") for x in r.split("/")))
|
|
34
|
+
# -z: names with spaces or non-ASCII characters come through unquoted
|
|
35
|
+
out = subprocess.run(["git", "ls-files", "-z", "*.py"], cwd=repo, capture_output=True, text=True, check=True).stdout
|
|
36
|
+
return [rel for rel in out.split("\0") if rel]
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def count_lines(repo):
|
|
40
|
+
files = python_files(repo)
|
|
41
|
+
counts = {"test_files": 0, "test_lines": 0, "source_lines": 0}
|
|
42
|
+
for rel in files:
|
|
43
|
+
lines = len((repo / rel).read_text(errors="replace").splitlines())
|
|
44
|
+
if is_test(rel):
|
|
45
|
+
counts["test_files"] += 1
|
|
46
|
+
counts["test_lines"] += lines
|
|
47
|
+
else:
|
|
48
|
+
counts["source_lines"] += lines
|
|
49
|
+
return counts
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
"""Mutation score: a pinned mutmut run in a temporary detached worktree of HEAD, so the target repo is never written."""
|
|
2
|
+
import ast
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import os
|
|
6
|
+
import shutil
|
|
7
|
+
import subprocess
|
|
8
|
+
import tempfile
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from weigh_env import SetupError, cache_root, mutmut_overlay
|
|
12
|
+
from weigh_inventory import is_test, python_files
|
|
13
|
+
from weigh_runs import aggregate
|
|
14
|
+
from weigh_snapshot import git
|
|
15
|
+
|
|
16
|
+
ROOT = "worktrees"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def refuse_dirty(repo):
|
|
20
|
+
"""A tree with uncommitted changes (untracked files included) is refused, naming them: the score is of the commit."""
|
|
21
|
+
dirty = git(repo, "status", "--porcelain", "-uall")
|
|
22
|
+
if dirty:
|
|
23
|
+
raise SetupError("--mutation needs a clean tree, the score is of the committed code; uncommitted changes:\n" + dirty)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def refuse_red(cases):
|
|
27
|
+
failing = sorted({n.split("[", 1)[0] for n, c in cases.items() if c["outcome"] in ("failed", "error")})
|
|
28
|
+
if failing:
|
|
29
|
+
raise SetupError("--mutation needs a green suite; failing tests:\n" + "\n".join(failing))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _alive(pid):
|
|
33
|
+
try:
|
|
34
|
+
os.kill(pid, 0)
|
|
35
|
+
except ProcessLookupError:
|
|
36
|
+
return False
|
|
37
|
+
except PermissionError:
|
|
38
|
+
pass
|
|
39
|
+
return True
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def remove_stale():
|
|
43
|
+
"""Remove the worktrees an earlier run left under the cache (named <pid>-<random>, pid no longer running).
|
|
44
|
+
|
|
45
|
+
Only these paths are removed, through the repository that owns each: `git worktree prune` would also drop the user's own."""
|
|
46
|
+
for wt in (cache_root() / ROOT).glob("*-*"):
|
|
47
|
+
if _alive(int(wt.name.split("-")[0])):
|
|
48
|
+
continue # ponytail: a pid reused by another process keeps its stale worktree until that process exits
|
|
49
|
+
common = subprocess.run(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], cwd=wt, capture_output=True, text=True).stdout.strip()
|
|
50
|
+
if common:
|
|
51
|
+
subprocess.run(["git", f"--git-dir={common}", "worktree", "remove", "--force", str(wt)], capture_output=True)
|
|
52
|
+
shutil.rmtree(wt, ignore_errors=True)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _configure(wt, files):
|
|
56
|
+
"""mutmut's config in the worktree's pyproject.toml, unless the project already has its own."""
|
|
57
|
+
pyproject = wt / "pyproject.toml"
|
|
58
|
+
text = pyproject.read_text() if pyproject.exists() else ""
|
|
59
|
+
if "[tool.mutmut]" in text:
|
|
60
|
+
return
|
|
61
|
+
source = [f for f in files if not is_test(f)]
|
|
62
|
+
tests = sorted({os.path.dirname(f) or "." for f in files if is_test(f)})
|
|
63
|
+
pyproject.write_text(text + "\n[tool.mutmut]\npaths_to_mutate = %s\ntests_dir = %s\n" % (json.dumps(source), json.dumps([t + "/" for t in tests])))
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _function(tree, mangled):
|
|
67
|
+
"""The def node of a mutmut name such as x_parse or xǁClassǁmethod, found in a parsed module."""
|
|
68
|
+
node = tree
|
|
69
|
+
for part in mangled.split("ǁ")[1:] if "ǁ" in mangled else [mangled[2:]]:
|
|
70
|
+
node = next((n for n in ast.walk(node) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) and n.name == part), None)
|
|
71
|
+
if node is None:
|
|
72
|
+
return None
|
|
73
|
+
return node
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def _mutant_line(wt, mutant):
|
|
77
|
+
"""(source file, source line) of the first line a mutant changes, found by comparing mutmut's mutated copy with its original."""
|
|
78
|
+
module, name = mutant.rsplit(".", 1)
|
|
79
|
+
mangled = name.split("__mutmut_")[0]
|
|
80
|
+
base = module.replace(".", "/")
|
|
81
|
+
rel = base + ".py" if (wt / (base + ".py")).exists() else base + "/__init__.py"
|
|
82
|
+
text = (wt / "mutants" / rel).read_text()
|
|
83
|
+
lines = text.splitlines()
|
|
84
|
+
defs = {n.name: lines[n.lineno - 1:n.end_lineno] for n in ast.walk(ast.parse(text)) if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef))}
|
|
85
|
+
orig, mutated = defs[mangled + "__mutmut_orig"], defs[name]
|
|
86
|
+
offset = next((i for i, (a, b) in enumerate(zip(orig, mutated)) if i and a != b), 0) # line 0 is the def, whose name differs
|
|
87
|
+
original = _function(ast.parse((wt / rel).read_text()), mangled)
|
|
88
|
+
return rel, (original.lineno if original else 1) + offset
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _sample(seed, by_function, per_function):
|
|
92
|
+
"""Up to per_function mutants of each function on different lines (all of them for None), in the order of a hash of the commit, function and mutant."""
|
|
93
|
+
sampled = []
|
|
94
|
+
for func, mutants in by_function.items():
|
|
95
|
+
ranked = sorted(mutants, key=lambda m: (hashlib.sha256(f"{seed}:{func}:{m[0]}".encode()).hexdigest(), m[0]))
|
|
96
|
+
lines = set()
|
|
97
|
+
for name, line in ranked:
|
|
98
|
+
if per_function is None or (len(lines) < per_function and line not in lines):
|
|
99
|
+
lines.add(line)
|
|
100
|
+
sampled.append(name)
|
|
101
|
+
return sorted(sampled)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def _failing(python, wt, env, mutant, tests, timeout):
|
|
105
|
+
"""The tests (params folded) that fail with the mutant active, every one of them run (pytest without -x); None when the run hangs."""
|
|
106
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
107
|
+
out = os.path.join(tmp, "cases.json")
|
|
108
|
+
run_env = {**env, "MUTANT_UNDER_TEST": mutant, "TEST_WEIGH_IN_OUT": out}
|
|
109
|
+
try:
|
|
110
|
+
subprocess.run([str(python), "-m", "pytest", "-p", "no:randomly", "-p", "no:cacheprovider", "--maxfail=1000000", "-p", "weigh_pytest_plugin", *tests],
|
|
111
|
+
cwd=wt / "mutants", env=run_env, capture_output=True, timeout=timeout)
|
|
112
|
+
except subprocess.TimeoutExpired:
|
|
113
|
+
return None
|
|
114
|
+
if not os.path.exists(out):
|
|
115
|
+
raise SetupError(f"pytest did not run for the mutant {mutant}")
|
|
116
|
+
with open(out) as f:
|
|
117
|
+
tested = aggregate(json.load(f)["cases"])
|
|
118
|
+
return {n for n, t in tested.items() if t["outcome"] == "failed"}
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _kills(python, wt, env, mutant, tests, timeout):
|
|
122
|
+
"""The tests that kill the mutant. A hung run says nothing of the tests it never reached: each test then runs alone,
|
|
123
|
+
and kills it when it fails or hangs."""
|
|
124
|
+
killed = _failing(python, wt, env, mutant, tests, timeout)
|
|
125
|
+
if killed is None:
|
|
126
|
+
killed = {t for t in tests if _failing(python, wt, env, mutant, [t], timeout) != set()}
|
|
127
|
+
return sorted(killed)
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _matrix(python, repo, wt, env, per_function):
|
|
131
|
+
"""Pseudo-tested share and the sampled kill matrix, from mutmut's results in the worktree. Every generated mutant is a
|
|
132
|
+
sampling candidate; one in a function no test covers has an empty row."""
|
|
133
|
+
data = json.loads((wt / "mutants" / "mutmut-stats.json").read_text())
|
|
134
|
+
covering = {f: sorted({t.split("[", 1)[0] for t in tests}) for f, tests in data["tests_by_mangled_function_name"].items() if tests}
|
|
135
|
+
exit_codes = {}
|
|
136
|
+
for meta in (wt / "mutants").rglob("*.meta"):
|
|
137
|
+
exit_codes.update(json.loads(meta.read_text())["exit_code_by_key"])
|
|
138
|
+
by_function, where, survived = {}, {}, {}
|
|
139
|
+
for mutant, code in sorted(exit_codes.items()):
|
|
140
|
+
func = mutant.rsplit("__mutmut_", 1)[0]
|
|
141
|
+
where[mutant] = _mutant_line(wt, mutant)
|
|
142
|
+
by_function.setdefault(func, []).append((mutant, where[mutant][1]))
|
|
143
|
+
if func in covering:
|
|
144
|
+
survived[func] = survived.get(func, True) and code == 0
|
|
145
|
+
sampled = _sample(git(repo, "rev-parse", "HEAD"), by_function, per_function)
|
|
146
|
+
timeout = 60 + 10 * sum(data.get("duration_by_test", {}).values()) # ponytail: a hung mutant waits this long
|
|
147
|
+
tests_of = lambda m: covering.get(m.rsplit("__mutmut_", 1)[0], [])
|
|
148
|
+
return {
|
|
149
|
+
"pseudo_tested": 100 * sum(survived.values()) / len(survived) if survived else 0.0,
|
|
150
|
+
"sampled": sampled,
|
|
151
|
+
"mutants": {m: {"file": where[m][0], "line": where[m][1]} for m in sampled},
|
|
152
|
+
"matrix": {m: _kills(python, wt, env, m, tests_of(m), timeout) if tests_of(m) else [] for m in sampled},
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def score(python, repo, overlay, per_function=3):
|
|
157
|
+
"""The pinned mutmut run on HEAD and its kill matrix, as a dict: score (percent of all mutants killed), pseudo_tested
|
|
158
|
+
(percent of the covered functions whose mutants all survived), sampled (mutant ids: per_function per function on
|
|
159
|
+
different lines, every one for None), mutants {id: {file, line}} and matrix {id: ids of the killing tests}.
|
|
160
|
+
The worktree is gone on every exit."""
|
|
161
|
+
root = cache_root() / ROOT
|
|
162
|
+
root.mkdir(parents=True, exist_ok=True)
|
|
163
|
+
wt = Path(tempfile.mkdtemp(prefix=f"{os.getpid()}-", dir=root))
|
|
164
|
+
wt.rmdir()
|
|
165
|
+
proc = None
|
|
166
|
+
try:
|
|
167
|
+
added = subprocess.run(["git", "worktree", "add", "-q", "--detach", str(wt), "HEAD"], cwd=repo, capture_output=True, text=True)
|
|
168
|
+
if added.returncode:
|
|
169
|
+
raise SetupError("cannot create the temporary worktree:\n" + added.stderr)
|
|
170
|
+
_configure(wt, python_files(wt))
|
|
171
|
+
env = {**os.environ, "PYTHONPATH": str(mutmut_overlay(python)), "PYTHONDONTWRITEBYTECODE": "1"}
|
|
172
|
+
proc = subprocess.Popen([str(python), "-m", "mutmut", "run"], cwd=wt, env=env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True)
|
|
173
|
+
out = proc.communicate()[0]
|
|
174
|
+
if proc.returncode:
|
|
175
|
+
raise SetupError(f"mutmut run exited {proc.returncode}:\n" + out)
|
|
176
|
+
exported = subprocess.run([str(python), "-m", "mutmut", "export-cicd-stats"], cwd=wt, env=env, capture_output=True, text=True)
|
|
177
|
+
stats = wt / "mutants" / "mutmut-cicd-stats.json"
|
|
178
|
+
if exported.returncode or not stats.exists():
|
|
179
|
+
raise SetupError("mutmut export-cicd-stats failed:\n" + exported.stdout + exported.stderr)
|
|
180
|
+
stats = json.loads(stats.read_text())
|
|
181
|
+
if not stats["total"]:
|
|
182
|
+
raise SetupError("mutmut found no mutants: no source code to mutate")
|
|
183
|
+
env["PYTHONPATH"] = f"{overlay}{os.pathsep}{env['PYTHONPATH']}"
|
|
184
|
+
return {"score": 100 * stats["killed"] / stats["total"], **_matrix(python, repo, wt, env, per_function)}
|
|
185
|
+
finally:
|
|
186
|
+
if proc and proc.poll() is None:
|
|
187
|
+
proc.kill()
|
|
188
|
+
proc.wait()
|
|
189
|
+
subprocess.run(["git", "worktree", "remove", "--force", str(wt)], cwd=repo, capture_output=True)
|
|
190
|
+
shutil.rmtree(wt, ignore_errors=True)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
"""Pytest plugin loaded into the target's interpreter: writes each case's outcome and duration to TEST_WEIGH_IN_OUT."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import sys
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
_cases = {}
|
|
10
|
+
_start = time.perf_counter()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _context(item, when):
|
|
14
|
+
"""Under `coverage run`, record each phase's lines under "<nodeid>|<when>"; a plain run never imports coverage."""
|
|
15
|
+
cov = sys.modules.get("coverage")
|
|
16
|
+
current = cov and cov.Coverage.current()
|
|
17
|
+
if current:
|
|
18
|
+
current.switch_context(f"{item.nodeid}|{when}")
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@pytest.hookimpl(tryfirst=True)
|
|
22
|
+
def pytest_runtest_setup(item):
|
|
23
|
+
_context(item, "setup")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@pytest.hookimpl(tryfirst=True)
|
|
27
|
+
def pytest_runtest_call(item):
|
|
28
|
+
_context(item, "call")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@pytest.hookimpl(tryfirst=True)
|
|
32
|
+
def pytest_runtest_teardown(item):
|
|
33
|
+
_context(item, "teardown")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def pytest_runtest_logreport(report):
|
|
37
|
+
case = _cases.setdefault(report.nodeid, {"outcome": "passed", "duration": 0.0})
|
|
38
|
+
if report.when == "call":
|
|
39
|
+
case["outcome"] = "xfail" if hasattr(report, "wasxfail") else report.outcome
|
|
40
|
+
case["duration"] = report.duration
|
|
41
|
+
elif report.failed and case["outcome"] != "failed":
|
|
42
|
+
case["outcome"] = "error"
|
|
43
|
+
elif report.skipped and report.when == "setup":
|
|
44
|
+
case["outcome"] = "xfail" if hasattr(report, "wasxfail") else "skipped"
|
|
45
|
+
# a teardown skip leaves the call's outcome as it was
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pytest_sessionfinish(session):
|
|
49
|
+
data = {
|
|
50
|
+
"pytest_version": pytest.__version__,
|
|
51
|
+
"python_version": ".".join(map(str, sys.version_info[:3])),
|
|
52
|
+
"runtime_seconds": time.perf_counter() - _start,
|
|
53
|
+
"cases": _cases,
|
|
54
|
+
}
|
|
55
|
+
with open(os.environ["TEST_WEIGH_IN_OUT"], "w") as out:
|
|
56
|
+
json.dump(data, out)
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
"""Ruff's PT rules over the target repo's test files: [(path, row, code)] for the rules in rules.toml."""
|
|
2
|
+
import json
|
|
3
|
+
import subprocess
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from weigh_env import UV, SetupError
|
|
7
|
+
from weigh_inventory import is_test, python_files
|
|
8
|
+
|
|
9
|
+
RUFF = "ruff==0.17.3"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def violations(repo, codes):
|
|
13
|
+
"""--isolated: the target repo's own ruff configuration changes nothing; uv runs ruff outside the repo's environment."""
|
|
14
|
+
files = [f for f in python_files(repo) if is_test(f)]
|
|
15
|
+
if not files or not codes:
|
|
16
|
+
return []
|
|
17
|
+
proc = subprocess.run([UV, "tool", "run", "--isolated", RUFF, "check", "--isolated", "--no-cache", "--select", ",".join(codes),
|
|
18
|
+
"--output-format", "json", "--", *files], cwd=repo, capture_output=True, text=True)
|
|
19
|
+
if proc.returncode not in (0, 1):
|
|
20
|
+
raise SetupError("ruff failed:\n" + proc.stdout + proc.stderr)
|
|
21
|
+
root = repo.resolve()
|
|
22
|
+
return [(Path(v["filename"]).resolve().relative_to(root).as_posix(), v["location"]["row"], v["code"]) for v in json.loads(proc.stdout)]
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
"""Load, validate and hash rules.toml (version 1)."""
|
|
2
|
+
import hashlib
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from weigh_env import SetupError
|
|
9
|
+
|
|
10
|
+
DEFAULT = Path(__file__).resolve().parent / "rules.toml"
|
|
11
|
+
TABLE = re.compile(r"^\[([A-Za-z0-9_.]+)\]$")
|
|
12
|
+
PILLARS = ("regression", "refactoring", "feedback", "maintainability", "economy")
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class RulesError(SetupError):
|
|
16
|
+
pass
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def parse(text):
|
|
20
|
+
# ponytail: the subset rules.toml uses (dotted [tables], string/number/bool values); tomllib needs Python 3.11 and the system python3 may be older.
|
|
21
|
+
root, table = {}, None
|
|
22
|
+
for n, raw in enumerate(text.splitlines(), 1):
|
|
23
|
+
line = raw.split("#", 1)[0].strip() if '"' not in raw else raw.strip()
|
|
24
|
+
if not line:
|
|
25
|
+
continue
|
|
26
|
+
m = TABLE.match(line)
|
|
27
|
+
if m:
|
|
28
|
+
table = root
|
|
29
|
+
for part in m[1].split("."):
|
|
30
|
+
table = table.setdefault(part, {})
|
|
31
|
+
continue
|
|
32
|
+
key, sep, value = line.partition("=")
|
|
33
|
+
if not sep:
|
|
34
|
+
raise RulesError(f"rules.toml line {n}: cannot read {raw!r}")
|
|
35
|
+
value = value.strip()
|
|
36
|
+
try:
|
|
37
|
+
parsed = json.loads(value)
|
|
38
|
+
except ValueError:
|
|
39
|
+
raise RulesError(f"rules.toml line {n}: cannot read value {value!r}")
|
|
40
|
+
(table if table is not None else root)[key.strip()] = parsed
|
|
41
|
+
return root
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def load():
|
|
45
|
+
path = Path(os.environ.get("TEST_WEIGH_IN_RULES") or DEFAULT)
|
|
46
|
+
raw = path.read_bytes()
|
|
47
|
+
rules = parse(raw.decode())
|
|
48
|
+
rules["sha256"] = hashlib.sha256(raw).hexdigest()
|
|
49
|
+
validate(rules)
|
|
50
|
+
return rules
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def validate(rules):
|
|
54
|
+
if rules.get("version") != 1:
|
|
55
|
+
raise RulesError(f"rules.toml: unsupported version {rules.get('version')!r}")
|
|
56
|
+
for key in PILLARS:
|
|
57
|
+
pillar = rules.get("pillars", {}).get(key)
|
|
58
|
+
if not pillar or not pillar.get("metrics"):
|
|
59
|
+
raise RulesError(f"rules.toml: pillar {key} is missing or has no metrics")
|
|
60
|
+
for mid, m in pillar["metrics"].items():
|
|
61
|
+
if m["target"] == m["bad"]:
|
|
62
|
+
raise RulesError(f"rules.toml: {pillar['name']}: {m['name']} has target and bad anchors both {m['target']}")
|
|
63
|
+
total = sum(m["weight"] for m in pillar["metrics"].values())
|
|
64
|
+
if abs(total - 1) > 1e-9:
|
|
65
|
+
raise RulesError(f"rules.toml: {pillar['name']} weights sum to {total:g}, not 1")
|