@jesdi/skills 0.0.80 → 0.0.82

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.
Files changed (76) hide show
  1. package/package.json +2 -1
  2. package/skills/crap-gate/launcher.sh +104 -0
  3. package/skills/crap-gate/run.sh +15 -75
  4. package/skills/crap-gate/test_launcher.py +39 -0
  5. package/skills/implement-spec/launcher.sh +104 -0
  6. package/skills/implement-spec/run.sh +10 -89
  7. package/skills/implement-spec/tests/test_launcher.py +138 -0
  8. package/skills/test-prune/SKILL.md +4 -2
  9. package/skills/test-prune/prune_strengthen.py +24 -12
  10. package/skills/test-prune/tests/test_prune_guards.py +1 -1
  11. package/skills/test-prune/tests/test_prune_inputs.py +10 -5
  12. package/skills/test-prune/tests/test_prune_strengthen.py +34 -12
  13. package/skills/test-weigh-in/SKILL.md +16 -0
  14. package/skills/test-weigh-in/dashboard.html +112 -0
  15. package/skills/test-weigh-in/launcher.sh +104 -0
  16. package/skills/test-weigh-in/rules.toml +134 -0
  17. package/skills/test-weigh-in/run.sh +21 -0
  18. package/skills/test-weigh-in/tests/brittle_repo.py +79 -0
  19. package/skills/test-weigh-in/tests/conftest.py +35 -0
  20. package/skills/test-weigh-in/tests/fixture_repo.py +99 -0
  21. package/skills/test-weigh-in/tests/kill_repo.py +87 -0
  22. package/skills/test-weigh-in/tests/maint_repo.py +139 -0
  23. package/skills/test-weigh-in/tests/map_fixture.py +56 -0
  24. package/skills/test-weigh-in/tests/pt_repo.py +46 -0
  25. package/skills/test-weigh-in/tests/red_repo.py +44 -0
  26. package/skills/test-weigh-in/tests/rule_repo.py +208 -0
  27. package/skills/test-weigh-in/tests/rules_fixture.py +65 -0
  28. package/skills/test-weigh-in/tests/smell_repo.py +138 -0
  29. package/skills/test-weigh-in/tests/test_brittleness.py +75 -0
  30. package/skills/test-weigh-in/tests/test_brittleness_history.py +168 -0
  31. package/skills/test-weigh-in/tests/test_coverage_run.py +201 -0
  32. package/skills/test-weigh-in/tests/test_coverage_value.py +76 -0
  33. package/skills/test-weigh-in/tests/test_dashboard_map.py +20 -0
  34. package/skills/test-weigh-in/tests/test_interpreters.py +115 -0
  35. package/skills/test-weigh-in/tests/test_kill_matrix.py +126 -0
  36. package/skills/test-weigh-in/tests/test_maintainability_smells.py +113 -0
  37. package/skills/test-weigh-in/tests/test_mutation_recovery.py +67 -0
  38. package/skills/test-weigh-in/tests/test_mutation_sampling.py +53 -0
  39. package/skills/test-weigh-in/tests/test_mutation_score.py +140 -0
  40. package/skills/test-weigh-in/tests/test_mutation_stale.py +30 -0
  41. package/skills/test-weigh-in/tests/test_mutmut_contract.py +43 -0
  42. package/skills/test-weigh-in/tests/test_ruff_pt_smells.py +45 -0
  43. package/skills/test-weigh-in/tests/test_runs.py +156 -0
  44. package/skills/test-weigh-in/tests/test_score.py +26 -0
  45. package/skills/test-weigh-in/tests/test_scoring.py +154 -0
  46. package/skills/test-weigh-in/tests/test_smell_rules.py +96 -0
  47. package/skills/test-weigh-in/tests/test_smells.py +71 -0
  48. package/skills/test-weigh-in/tests/test_walking_skeleton.py +91 -0
  49. package/skills/test-weigh-in/tests/testdata/default_repo/demo/__init__.py +0 -0
  50. package/skills/test-weigh-in/tests/testdata/default_repo/demo/board.py +2 -0
  51. package/skills/test-weigh-in/tests/testdata/default_repo/demo/config.py +2 -0
  52. package/skills/test-weigh-in/tests/testdata/default_repo/pyproject.toml +8 -0
  53. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_board.py +19 -0
  54. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_config.py +19 -0
  55. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_parser.py +19 -0
  56. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_render.py +19 -0
  57. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_report.py +17 -0
  58. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_session.py +19 -0
  59. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_store.py +17 -0
  60. package/skills/test-weigh-in/tests/testdata/default_repo/tests/test_sync.py +17 -0
  61. package/skills/test-weigh-in/tests/testdata/default_repo/uv.lock +1 -0
  62. package/skills/test-weigh-in/weigh.py +133 -0
  63. package/skills/test-weigh-in/weigh_coverage.py +154 -0
  64. package/skills/test-weigh-in/weigh_dashboard.py +72 -0
  65. package/skills/test-weigh-in/weigh_env.py +112 -0
  66. package/skills/test-weigh-in/weigh_git.py +119 -0
  67. package/skills/test-weigh-in/weigh_inventory.py +49 -0
  68. package/skills/test-weigh-in/weigh_mutation.py +190 -0
  69. package/skills/test-weigh-in/weigh_pytest_plugin.py +70 -0
  70. package/skills/test-weigh-in/weigh_ruff.py +22 -0
  71. package/skills/test-weigh-in/weigh_rules.py +65 -0
  72. package/skills/test-weigh-in/weigh_runs.py +134 -0
  73. package/skills/test-weigh-in/weigh_score.py +80 -0
  74. package/skills/test-weigh-in/weigh_smells.py +355 -0
  75. package/skills/test-weigh-in/weigh_snapshot.py +49 -0
  76. package/skills-manifest.json +13 -7
@@ -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, "TEST_WEIGH_IN_ARTIFACTS": tmp}
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,70 @@
1
+ """Pytest plugin loaded into the target's interpreter: writes each case's outcome and duration to TEST_WEIGH_IN_OUT,
2
+ and sends the files pytest would write into the repo to TEST_WEIGH_IN_ARTIFACTS."""
3
+ import json
4
+ import os
5
+ import sys
6
+ import time
7
+
8
+ import pytest
9
+
10
+ _cases = {}
11
+ _start = time.perf_counter()
12
+ # Option dests of core and common-plugin file writers (junitxml, logging, basetemp, pytest-reportlog, pytest-html,
13
+ # pytest-json-report). They are read from the effective config, so addopts, PYTEST_ADDOPTS and ini values are covered.
14
+ # ponytail: a writer of an unknown plugin still gets through; weigh_runs refuses the run when the repo changed.
15
+ WRITERS = ("xmlpath", "log_file", "basetemp", "report_log", "htmlpath", "json_report_file")
16
+
17
+
18
+ @pytest.hookimpl(tryfirst=True)
19
+ def pytest_configure(config):
20
+ artifacts = os.environ["TEST_WEIGH_IN_ARTIFACTS"]
21
+ for dest in WRITERS:
22
+ set_by_ini = dest == "log_file" and config.getini("log_file")
23
+ if getattr(config.option, dest, None) or set_by_ini:
24
+ setattr(config.option, dest, os.path.join(artifacts, dest))
25
+
26
+
27
+ def _context(item, when):
28
+ """Under `coverage run`, record each phase's lines under "<nodeid>|<when>"; a plain run never imports coverage."""
29
+ cov = sys.modules.get("coverage")
30
+ current = cov and cov.Coverage.current()
31
+ if current:
32
+ current.switch_context(f"{item.nodeid}|{when}")
33
+
34
+
35
+ @pytest.hookimpl(tryfirst=True)
36
+ def pytest_runtest_setup(item):
37
+ _context(item, "setup")
38
+
39
+
40
+ @pytest.hookimpl(tryfirst=True)
41
+ def pytest_runtest_call(item):
42
+ _context(item, "call")
43
+
44
+
45
+ @pytest.hookimpl(tryfirst=True)
46
+ def pytest_runtest_teardown(item):
47
+ _context(item, "teardown")
48
+
49
+
50
+ def pytest_runtest_logreport(report):
51
+ case = _cases.setdefault(report.nodeid, {"outcome": "passed", "duration": 0.0})
52
+ if report.when == "call":
53
+ case["outcome"] = "xfail" if hasattr(report, "wasxfail") else report.outcome
54
+ case["duration"] = report.duration
55
+ elif report.failed and case["outcome"] != "failed":
56
+ case["outcome"] = "error"
57
+ elif report.skipped and report.when == "setup":
58
+ case["outcome"] = "xfail" if hasattr(report, "wasxfail") else "skipped"
59
+ # a teardown skip leaves the call's outcome as it was
60
+
61
+
62
+ def pytest_sessionfinish(session):
63
+ data = {
64
+ "pytest_version": pytest.__version__,
65
+ "python_version": ".".join(map(str, sys.version_info[:3])),
66
+ "runtime_seconds": time.perf_counter() - _start,
67
+ "cases": _cases,
68
+ }
69
+ with open(os.environ["TEST_WEIGH_IN_OUT"], "w") as out:
70
+ 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")
@@ -0,0 +1,134 @@
1
+ """The plain and coverage runs: pytest through the target's interpreter, cases aggregated into tests."""
2
+ import json
3
+ import os
4
+ import shlex
5
+ import subprocess
6
+ import tempfile
7
+
8
+ from weigh_coverage import contexts_regex
9
+ from weigh_env import SetupError
10
+ from weigh_inventory import TEST_GLOBS
11
+ from weigh_snapshot import git
12
+
13
+ PYTEST = ["-m", "pytest", "-p", "no:randomly", "-p", "no:cacheprovider", "-p", "weigh_pytest_plugin"]
14
+ # Paths inside the repo that the coverage run leaves out: environments, and the test files.
15
+ OMIT = (".venv/**", "venv/**") + TEST_GLOBS
16
+ # pytest exit codes of a run that executed its tests: all passed, some failed.
17
+ RAN = (0, 1)
18
+
19
+
20
+ def _pytest(python, repo, overlay, pytest_args, tmp, runner=(), env=None):
21
+ """One pytest run; the plugin sends pytest's file writers to tmp, and a run that still changed the repo is refused."""
22
+ args = shlex.split(pytest_args)
23
+ # --debug opens its log before any plugin is configured, so it cannot be redirected.
24
+ if any(a.split("=", 1)[0] == "--debug" for a in args + shlex.split(os.environ.get("PYTEST_ADDOPTS", ""))):
25
+ raise SetupError("--pytest-args: --debug writes files and would change the target repo")
26
+ out = os.path.join(tmp, "cases.json")
27
+ env = {**os.environ, **(env or {}), "PYTHONPATH": str(overlay), "PYTHONDONTWRITEBYTECODE": "1",
28
+ "TEST_WEIGH_IN_OUT": out, "TEST_WEIGH_IN_ARTIFACTS": tmp}
29
+ before = git(repo, "status", "--porcelain")
30
+ proc = subprocess.run([str(python), *runner, *PYTEST, *args], cwd=repo, env=env, capture_output=True, text=True)
31
+ if git(repo, "status", "--porcelain") != before:
32
+ raise SetupError("pytest changed the target repo; drop the --pytest-args or configuration that writes files:\n"
33
+ + git(repo, "status", "--porcelain"))
34
+ return proc, out
35
+
36
+
37
+ def plain_run(python, repo, overlay, pytest_args):
38
+ with tempfile.TemporaryDirectory() as tmp:
39
+ proc, out = _pytest(python, repo, overlay, pytest_args, tmp)
40
+ if proc.returncode not in RAN or not os.path.exists(out):
41
+ raise SetupError(f"pytest exited {proc.returncode} without running the tests:\n" + proc.stdout + proc.stderr)
42
+ with open(out) as f:
43
+ return json.load(f)
44
+
45
+
46
+ def aggregate(cases):
47
+ """Group cases by node id without [params]; durations sum, any failure wins, all-skipped is skipped."""
48
+ tests = {}
49
+ for node, case in cases.items():
50
+ tests.setdefault(node.split("[", 1)[0], []).append(case)
51
+ result = {}
52
+ for node, group in tests.items():
53
+ outcomes = {c["outcome"] for c in group}
54
+ if outcomes & {"failed", "error"}:
55
+ outcome = "failed"
56
+ elif outcomes == {"skipped"}:
57
+ outcome = "skipped"
58
+ else:
59
+ outcome = "passed"
60
+ result[node] = {"outcome": outcome, "duration": sum(c["duration"] for c in group), "cases": len(group)}
61
+ return result
62
+
63
+
64
+ def coverage_run(python, repo, overlay, pytest_args, eligible):
65
+ """Pytest under branch coverage with a context per test phase, as a dict: cases; report, the coverage json report of
66
+ the passing cases; value_report, the same of the eligible tests that also passed under coverage; arcs, the arcs of
67
+ each passing case's call context. A coverage report that fails is an error, so no metric comes from missing data."""
68
+ with tempfile.TemporaryDirectory() as tmp:
69
+ rc = os.path.join(tmp, "rc")
70
+ open(rc, "w").close()
71
+ data = os.path.join(tmp, "data")
72
+ # test files are the cost being weighed, not the code under test; anchored in the repo, so a folder
73
+ # named tests above it excludes nothing
74
+ omit = ",".join(f"{repo}/**/{p}" for p in OMIT)
75
+ run, out = _pytest(python, repo, overlay, pytest_args, tmp, env={"COVERAGE_RCFILE": rc},
76
+ runner=["-m", "coverage", "run", "--branch", f"--data-file={data}", f"--source={repo}", f"--omit={omit}"])
77
+ if run.returncode not in RAN or not os.path.exists(out):
78
+ raise SetupError(f"pytest under coverage exited {run.returncode} without running the tests:\n" + run.stdout + run.stderr)
79
+ with open(out) as f:
80
+ cases = json.load(f)["cases"]
81
+ eligible = eligible & {n for n, t in aggregate(cases).items() if t["outcome"] == "passed"}
82
+ env = {**os.environ, "PYTHONPATH": str(overlay), "PYTHONDONTWRITEBYTECODE": "1", "COVERAGE_RCFILE": rc}
83
+ coverage = lambda *a: subprocess.run([str(python), *a], cwd=repo, env=env, capture_output=True, text=True)
84
+ passing = contexts_regex(cases)
85
+ return {"cases": cases,
86
+ "report": _report(coverage, rc, data, os.path.join(tmp, "report.json"), passing),
87
+ "value_report": _report(coverage, rc, data, os.path.join(tmp, "eligible.json"), contexts_regex(cases, eligible)),
88
+ "arcs": _arcs(coverage, data, os.path.join(tmp, "arcs.json"), passing)}
89
+
90
+
91
+ def _report(coverage, rc, data, out, regex):
92
+ # coverage splits a config list at each comma and expands $NAME in it: write both as regex escapes that
93
+ # match the same characters (re.escape writes a literal $ as \$)
94
+ with open(rc, "w") as f:
95
+ f.write("[report]\ncontexts = " + regex.replace(",", r"\x2c").replace(r"\$", r"\x24") + "\n")
96
+ proc = coverage("-m", "coverage", "json", "--show-contexts", f"--data-file={data}", "-o", out, "-q")
97
+ if "No data to report" in proc.stdout + proc.stderr: # no source file ran at all: measured, and empty
98
+ return {"files": {}, "totals": {"covered_branches": 0, "num_branches": 0}}
99
+ if proc.returncode or not os.path.exists(out):
100
+ raise SetupError(f"coverage json exited {proc.returncode}:\n" + proc.stdout + proc.stderr)
101
+ with open(out) as f:
102
+ return json.load(f)
103
+
104
+
105
+ # Runs in the target's interpreter: coverage json has per-context lines but not per-context arcs.
106
+ # ponytail: one query per context and file; read the data file's arc table in one query if suites of thousands get slow
107
+ ARCS = """import json, re, sys
108
+ from coverage import Coverage, CoverageData
109
+ from coverage.python import PythonFileReporter
110
+ data, regex, out = sys.argv[1:]
111
+ cov = CoverageData(basename=data)
112
+ cov.read()
113
+ # raw arcs use the physical lines the tracer saw; the report maps them to each statement's first line, so
114
+ # map them the same way or a branch of a multi-line statement matches no reported branch
115
+ loaded = Coverage(data_file=data)
116
+ loaded.load()
117
+ reporters = {}
118
+ reporter = lambda path: reporters.setdefault(path, PythonFileReporter(path, loaded))
119
+ arcs = {}
120
+ for ctx in sorted(c for c in cov.measured_contexts() if re.search(regex, c)):
121
+ cov.set_query_contexts(["^" + re.escape(ctx) + "$"])
122
+ arcs[ctx] = {path: sorted(reporter(path).translate_arcs(a)) for path in cov.measured_files() if (a := cov.arcs(path))}
123
+ with open(out, "w") as f:
124
+ json.dump(arcs, f)
125
+ """
126
+
127
+
128
+ def _arcs(coverage, data, out, regex):
129
+ """{context: {measured path: [[from, to]]}} of the contexts the regex matches."""
130
+ proc = coverage("-c", ARCS, data, regex, out)
131
+ if proc.returncode or not os.path.exists(out):
132
+ raise SetupError(f"reading the coverage arcs exited {proc.returncode}:\n" + proc.stdout + proc.stderr)
133
+ with open(out) as f:
134
+ return json.load(f)
@@ -0,0 +1,80 @@
1
+ """Logistic metric scores, weighted pillar scores and the Fast feedback metrics."""
2
+ import math
3
+
4
+
5
+ def metric_score(x, target, bad, log=False):
6
+ if log:
7
+ x, target, bad = (math.log(max(v, 1e-9)) for v in (x, target, bad))
8
+ k = 2 * math.log(9) / (target - bad)
9
+ z = -k * (x - (target + bad) / 2)
10
+ return 0.0 if z > 700 else 100 / (1 + math.exp(z))
11
+
12
+
13
+ def display(score):
14
+ return min(99, max(1, round(score)))
15
+
16
+
17
+ def feedback_values(tests, runtime):
18
+ durations = sorted((t["duration"] for t in tests.values()), reverse=True)
19
+ n = len(durations)
20
+ top = durations[: max(1, math.ceil(n / 10))] if n else []
21
+ total = sum(durations)
22
+ return {
23
+ "total_runtime": runtime,
24
+ "p95_duration": durations[min(n - 1, int(n * 0.05))] if n else 0,
25
+ "slowest_decile_share": 100 * sum(top) / total if total else 0,
26
+ "tests_over_10s": 100 * sum(d > 10 for d in durations) / n if n else 0,
27
+ }
28
+
29
+
30
+ # Metrics read from the tests that give value (coverage, its test-file mapping, the kill matrix): a red suite leaves them partial.
31
+ VALUE_METRICS = {"mutation_score", "branch_coverage", "pseudo_tested_functions", "brittle_test_files", "no_unique_coverage",
32
+ "subsumed_in_kill_matrix"}
33
+
34
+
35
+ def score(rules, values, red=False):
36
+ """Metrics {id: {value, score}} and pillars {key: {score, partial}}; unmeasured metrics are left out and the weights re-normalized.
37
+
38
+ Without the mutation tier (no mutation_score), a pillar that gives partial weights uses them, and its metrics without one do not count.
39
+ With a red suite (a test that gives no value), every pillar using a value metric is partial (req 14)."""
40
+ metrics, pillars = {}, {}
41
+ for key, pillar in rules["pillars"].items():
42
+ partial_weights = "mutation_score" not in values and any("partial_weight" in m for m in pillar["metrics"].values())
43
+ scored = []
44
+ for mid, m in pillar["metrics"].items():
45
+ if mid in values:
46
+ s = metric_score(values[mid], m["target"], m["bad"], m.get("log", False))
47
+ metrics[mid] = {"value": values[mid], "score": s}
48
+ weight = m.get("partial_weight", 0) if partial_weights else m["weight"]
49
+ if weight:
50
+ scored.append((weight, s))
51
+ weight = sum(w for w, _ in scored)
52
+ pillars[key] = {
53
+ "score": sum(w * s for w, s in scored) / weight if weight else None,
54
+ "partial": not values.keys() >= pillar["metrics"].keys() or (red and bool(VALUE_METRICS & pillar["metrics"].keys())),
55
+ }
56
+ return metrics, pillars
57
+
58
+
59
+ MIN_EVIDENCE = 2
60
+
61
+
62
+ def kill_matrix(tests, passing, mutation):
63
+ """Flag each test hollow, subsumed or insufficient_evidence from the sampled kill matrix, and return the one metric the
64
+ matrix alone owns, subsumed_in_kill_matrix; the metrics the flags change are computed from them afterwards. Only
65
+ passing tests are judged.
66
+
67
+ On its lines = a sampled mutant whose line the test executes. Subsumed = at least 2 of them, it kills some, and one
68
+ other test kills all it kills."""
69
+ matrix = mutation["matrix"]
70
+ for node, test in tests.items():
71
+ covered = {rel: set(lines) for rel, lines in test.get("coverage", {}).items()}
72
+ on = [m for m, info in mutation["mutants"].items() if info["line"] in covered.get(info["file"], ())] if node in passing else []
73
+ kills = {m for m in on if node in matrix[m]}
74
+ enough = len(on) >= MIN_EVIDENCE
75
+ every = {m for m in matrix if node in matrix[m]}
76
+ test["insufficient_evidence"] = node in passing and not enough
77
+ test["hollow"] = enough and not kills
78
+ test["subsumed"] = enough and bool(kills) and any(
79
+ other != node and every <= {m for m in matrix if other in matrix[m]} for other in {t for row in matrix.values() for t in row})
80
+ return {"subsumed_in_kill_matrix": 100 * sum(t["subsumed"] for t in tests.values()) / (len(tests) or 1)}