@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,133 @@
1
+ """Weigh a repo's test suite: `weigh.py <repo-path> [--pytest-args "..."]`."""
2
+ import argparse
3
+ import signal
4
+ import sys
5
+ import webbrowser
6
+ from pathlib import Path
7
+
8
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
9
+
10
+ from weigh_env import SetupError, build_overlay, check_versions, find_interpreter
11
+ from weigh_coverage import branch_percent, overlaps, per_test, test_file_sources, unique_coverage, valued
12
+ from weigh_git import brittle_percent, brittleness, is_repo
13
+ from weigh_dashboard import summary, write_dashboard
14
+ from weigh_inventory import count_lines
15
+ from weigh_rules import RulesError, load as load_rules
16
+ from weigh_ruff import violations
17
+ from weigh_runs import aggregate, coverage_run, plain_run
18
+ from weigh_smells import find_smells, smell_values
19
+ from weigh_mutation import refuse_dirty, refuse_red, remove_stale, score as mutation_score
20
+ from weigh_score import feedback_values, kill_matrix, score
21
+ from weigh_snapshot import commit_state, home_dir, write_snapshot
22
+
23
+
24
+ def main(argv=None):
25
+ parser = argparse.ArgumentParser(prog="weigh.py")
26
+ parser.add_argument("repo_path")
27
+ parser.add_argument("--pytest-args", default="")
28
+ parser.add_argument("--python")
29
+ parser.add_argument("--mutation", action="store_true")
30
+ parser.add_argument("--matrix-per-function", default="3", type=lambda v: None if v == "all" else int(v))
31
+ parser.add_argument("--no-open", action="store_true")
32
+ args = parser.parse_args(argv)
33
+ repo = Path(args.repo_path).resolve()
34
+ try:
35
+ rules = load_rules()
36
+ except (RulesError, OSError, KeyError) as e:
37
+ print(f"weigh.py: {e}", file=sys.stderr)
38
+ return 2
39
+ try:
40
+ if args.mutation:
41
+ remove_stale() # before any refusal: an interrupted run's worktree never outlives the next start
42
+ if not is_repo(repo):
43
+ raise SetupError("--mutation needs a git repository with a commit")
44
+ refuse_dirty(repo)
45
+ home = home_dir(repo)
46
+ python = find_interpreter(repo, args.python)
47
+ check_versions(python)
48
+ overlay = build_overlay(python)
49
+ run = plain_run(python, repo, overlay, args.pytest_args)
50
+ if args.mutation:
51
+ refuse_red(run["cases"])
52
+ eligible = {n for n, t in aggregate(run["cases"]).items() if t["outcome"] == "passed"}
53
+ cov = coverage_run(python, repo, overlay, args.pytest_args, eligible)
54
+ mutation = mutation_score(python, repo, overlay, args.matrix_per_function) if args.mutation else None
55
+ except SetupError as e:
56
+ print(f"weigh.py: {e}", file=sys.stderr)
57
+ return 1
58
+ tests = aggregate(run["cases"])
59
+ commit, dirty = commit_state(repo)
60
+ inventory = {
61
+ "tests": len(tests),
62
+ "cases": len(run["cases"]),
63
+ **count_lines(repo),
64
+ "runtime_seconds": max(run["runtime_seconds"], sum(c["duration"] for c in run["cases"].values())),
65
+ }
66
+ values = feedback_values(tests, inventory["runtime_seconds"])
67
+ if mutation is not None:
68
+ values["mutation_score"] = mutation["score"]
69
+ values["pseudo_tested_functions"] = mutation["pseudo_tested"]
70
+ found, clusters = find_smells(repo, tests, violations(repo, rules.get("ruff", {}).get("pt", [])))
71
+ for node, info in found.items():
72
+ tests[node].update(info)
73
+ if inventory["source_lines"]:
74
+ values["test_source_ratio"] = inventory["test_lines"] / inventory["source_lines"]
75
+ # failing, erroring and skipped tests cost (runtime, lines, smells) but give no value: no coverage, overlap or uniqueness
76
+ covered = per_test(cov["report"], cov["arcs"], repo)
77
+ cov_tests = aggregate(cov["cases"])
78
+ for node, test in tests.items():
79
+ test.update(covered.get(node, {"coverage": {}, "branches": {}}))
80
+ test["flaky"] = cov_tests.get(node, {}).get("outcome") != test["outcome"]
81
+ # value metrics count only tests that passed in both runs
82
+ passing = valued(tests)
83
+ unique = unique_coverage(passing)
84
+ for node, test in tests.items():
85
+ test["unique_coverage"] = unique.get(node, 0)
86
+ if branch_percent(cov["value_report"]) is not None:
87
+ values["branch_coverage"] = branch_percent(cov["value_report"])
88
+ if mutation is not None: # flags tests before the metrics they change are computed
89
+ values.update(kill_matrix(tests, passing, mutation))
90
+ values.update(smell_values(tests))
91
+ if passing:
92
+ # a count-based metric is a percentage of all tests (req 17); only valued tests can lack unique coverage, and an
93
+ # insufficient-evidence test counts in no Economy metric
94
+ values["no_unique_coverage"] = 100 * sum(not u and not tests[n].get("insufficient_evidence") for n, u in unique.items()) / len(tests)
95
+ test_files = brittleness(repo, test_file_sources(tests))
96
+ if (percent := brittle_percent(test_files)) is not None:
97
+ values["brittle_test_files"] = percent
98
+ metrics, pillars = score(rules, values, red=len(passing) < len(tests))
99
+ data = {
100
+ "commit": commit,
101
+ "dirty": dirty,
102
+ "pytest_args": args.pytest_args,
103
+ "pytest_version": run["pytest_version"],
104
+ "python_version": run["python_version"],
105
+ "rules": {"version": rules["version"], "sha256": rules["sha256"]},
106
+ "inventory": inventory,
107
+ "metrics": metrics,
108
+ "pillars": pillars,
109
+ "mutation_settings": {"mutation": args.mutation, "matrix_per_function": "all" if args.matrix_per_function is None else args.matrix_per_function},
110
+ **({"mutation": {k: mutation[k] for k in ("sampled", "mutants", "matrix")}} if mutation is not None else {}),
111
+ "tests": tests,
112
+ "test_files": test_files,
113
+ "overlaps": overlaps(passing),
114
+ "clusters": clusters,
115
+ }
116
+ path = write_snapshot(home, data)
117
+ dashboard = write_dashboard(home, data, rules)
118
+ print(summary(data, rules, path, dashboard))
119
+ if not args.no_open:
120
+ webbrowser.open(dashboard.as_uri())
121
+ return 0
122
+
123
+
124
+ def _terminate(signum, frame):
125
+ raise KeyboardInterrupt
126
+
127
+
128
+ if __name__ == "__main__":
129
+ signal.signal(signal.SIGTERM, _terminate)
130
+ try:
131
+ sys.exit(main())
132
+ except KeyboardInterrupt: # the temporary worktree is removed on the way out
133
+ sys.exit(130)
@@ -0,0 +1,154 @@
1
+ """Read `coverage json --show-contexts` into per-test coverage, and derive unique coverage and overlaps."""
2
+ import os
3
+ import re
4
+ from itertools import combinations
5
+
6
+ from weigh_inventory import is_test
7
+
8
+ OVERLAP_JACCARD = 0.9
9
+
10
+
11
+ # Case outcomes that pass: an expected failure aggregates into a passing test, so its coverage counts like a pass.
12
+ PASSING = ("passed", "xfail")
13
+
14
+
15
+ def contexts_regex(cases, eligible=None):
16
+ """Matches the call context of every passing case, of the eligible tests only when given."""
17
+ passing = [re.escape(f"{node}|call") for node, c in cases.items()
18
+ if c["outcome"] in PASSING and (eligible is None or node.split("[", 1)[0] in eligible)]
19
+ return "^(" + "|".join(passing) + ")$" if passing else "(?!)"
20
+
21
+
22
+ def _relative(path, repo):
23
+ rel = os.path.relpath(path, repo) if os.path.isabs(path) else path
24
+ return None if is_test(rel) else rel
25
+
26
+
27
+ def per_test(report, arcs, repo):
28
+ """{test node id: {"coverage": {path: sorted lines}, "branches": {path: sorted [from, to]}}}, paths repo-relative,
29
+ from the call contexts; setup, teardown and collection are not the test's."""
30
+ found = {}
31
+
32
+ def add(ctx, kind, rel, item):
33
+ if ctx.endswith("|call"):
34
+ node = ctx[: -len("|call")].split("[", 1)[0]
35
+ found.setdefault(node, {"coverage": {}, "branches": {}})[kind].setdefault(rel, set()).add(item)
36
+
37
+ branches = {}
38
+ for path, info in report["files"].items():
39
+ if rel := _relative(path, repo):
40
+ branches[rel] = {tuple(a) for a in info.get("executed_branches", [])}
41
+ for line, contexts in info.get("contexts", {}).items():
42
+ for ctx in contexts:
43
+ add(ctx, "coverage", rel, int(line))
44
+ for ctx, files in arcs.items():
45
+ for path, file_arcs in files.items():
46
+ rel = _relative(path, repo)
47
+ for arc in map(tuple, file_arcs):
48
+ if arc in branches.get(rel, ()):
49
+ add(ctx, "branches", rel, arc)
50
+ return {node: {kind: {rel: sorted(items) for rel, items in files.items()} for kind, files in test.items()}
51
+ for node, test in found.items()}
52
+
53
+
54
+ def branch_percent(report):
55
+ """Branch arcs only: percent_covered mixes statements in. Code that ran without a branch misses none (100); with no
56
+ code run at all, the metric is not measured."""
57
+ totals = report["totals"]
58
+ if not totals["num_branches"]:
59
+ return 100.0 if report["files"] else None
60
+ return 100 * totals["covered_branches"] / totals["num_branches"]
61
+
62
+
63
+ def valued(tests):
64
+ """The tests that give value: passed in the plain run and the same under coverage, so not flaky."""
65
+ return {node: test for node, test in tests.items() if test["outcome"] == "passed" and not test["flaky"]}
66
+
67
+
68
+ def _items(test):
69
+ """The lines and branches a test covers."""
70
+ return ({(rel, n) for rel, lines in test.get("coverage", {}).items() for n in lines}
71
+ | {(rel, tuple(arc)) for rel, arcs in test.get("branches", {}).items() for arc in arcs})
72
+
73
+
74
+ def unique_coverage(tests):
75
+ """{node: lines and branches covered by that test and no other}, over the tests given."""
76
+ sets = {node: _items(t) for node, t in tests.items()}
77
+ seen = {}
78
+ for items in sets.values():
79
+ for item in items:
80
+ seen[item] = seen.get(item, 0) + 1
81
+ return {node: sum(seen[item] == 1 for item in items) for node, items in sets.items()}
82
+
83
+
84
+ def overlaps(tests):
85
+ # ponytail: all pairs, quadratic in the passing tests; bucket by file if suites of thousands get slow
86
+ sets = {node: items for node, t in tests.items() if (items := _items(t))}
87
+ found = []
88
+ for a, b in combinations(sets, 2):
89
+ jaccard = len(sets[a] & sets[b]) / len(sets[a] | sets[b])
90
+ if jaccard >= OVERLAP_JACCARD:
91
+ found.append({"tests": [a, b], "jaccard": jaccard})
92
+ return found
93
+
94
+
95
+ MAP_SHARE = 0.2
96
+
97
+
98
+ def test_file_sources(tests):
99
+ """{test file: sorted source files holding at least 20% of the lines its tests cover}."""
100
+ lines = {}
101
+ for node, t in tests.items():
102
+ for rel, covered in t.get("coverage", {}).items():
103
+ lines.setdefault(node.split("::", 1)[0], {}).setdefault(rel, set()).update(covered)
104
+ mapped = {}
105
+ for file, per_source in lines.items():
106
+ total = sum(map(len, per_source.values()))
107
+ mapped[file] = sorted(rel for rel, n in per_source.items() if len(n) >= MAP_SHARE * total)
108
+ return mapped
109
+
110
+
111
+ MAP_SIMILAR = 0.6
112
+
113
+
114
+ def _axis(b, others, n):
115
+ """Top eigenvector of the double-centred matrix b by power iteration from a fixed start, orthogonal to `others`."""
116
+ v = [1.0 + i % 7 for i in range(n)]
117
+ for _ in range(100):
118
+ for o in others:
119
+ d = sum(x * y for x, y in zip(v, o))
120
+ v = [x - d * y for x, y in zip(v, o)]
121
+ w = [sum(b[i][j] * v[j] for j in range(n)) for i in range(n)]
122
+ norm = sum(x * x for x in w) ** 0.5
123
+ if not norm:
124
+ return [0.0] * n
125
+ v = [x / norm for x in w]
126
+ lam = sum(sum(b[i][j] * v[j] for j in range(n)) * v[i] for i in range(n))
127
+ return [x * max(lam, 0) ** 0.5 for x in v]
128
+
129
+
130
+ def similarity_map(tests):
131
+ """Dots for the map, one per test given: [{test, x, y, similar: [[other, jaccard >= 0.6]]}], x and y in 0..1.
132
+ Placement is classical MDS of 1 - similarity from a fixed start, so it is the same on every load."""
133
+ # ponytail: dense n x n, fine for hundreds of tests; sample or bucket if suites of thousands get slow
134
+ nodes = list(tests)
135
+ sets = [_items(tests[n]) for n in nodes]
136
+ n = len(nodes)
137
+ if not n:
138
+ return []
139
+ sim = [[(len(a & b) / len(a | b) if a | b else 0.0) if i != j else 1.0 for j, b in enumerate(sets)] for i, a in enumerate(sets)]
140
+ sq = [[(1 - s) ** 2 for s in row] for row in sim]
141
+ row_mean = [sum(r) / n for r in sq]
142
+ total = sum(row_mean) / n
143
+ b = [[-0.5 * (sq[i][j] - row_mean[i] - row_mean[j] + total) for j in range(n)] for i in range(n)]
144
+ x = _axis(b, [], n)
145
+ y = _axis(b, [[v / (sum(u * u for u in x) ** 0.5 or 1) for v in x]], n)
146
+
147
+ def unit(axis):
148
+ lo, hi = min(axis, default=0), max(axis, default=0)
149
+ return [(v - lo) / (hi - lo) if hi > lo else 0.5 for v in axis]
150
+
151
+ xs, ys = unit(x), unit(y)
152
+ return [{"test": node, "x": xs[i], "y": ys[i],
153
+ "similar": [[nodes[j], sim[i][j]] for j in range(n) if j != i and sim[i][j] >= MAP_SIMILAR]}
154
+ for i, node in enumerate(nodes)]
@@ -0,0 +1,72 @@
1
+ """Render dashboard.html from the template and print the chat summary."""
2
+ import json
3
+ from pathlib import Path
4
+
5
+ from weigh_coverage import similarity_map, valued
6
+ from weigh_score import display
7
+ from weigh_smells import PILLAR_SMELLS, pillar_smells, worst_tests
8
+
9
+ TEMPLATE = Path(__file__).resolve().parent / "dashboard.html"
10
+
11
+
12
+ def inventory_line(inv):
13
+ return (f"{inv['tests']} tests ({inv['cases']} cases) in {inv['test_files']} files, "
14
+ f"{inv['test_lines']} test lines, {inv['source_lines']} source lines, {inv['runtime_seconds']:.1f} s")
15
+
16
+
17
+ def _failing(tests):
18
+ return sum(t["outcome"] == "failed" for t in tests.values())
19
+
20
+
21
+ def _flaky(tests):
22
+ return sum(t.get("flaky", False) for t in tests.values())
23
+
24
+
25
+ def _slow(rules):
26
+ """A test is slow when it takes longer than the target of the p95 test duration."""
27
+ return rules["pillars"]["feedback"]["metrics"]["p95_duration"]["target"]
28
+
29
+
30
+ def write_dashboard(home, data, rules):
31
+ failing = _failing(data["tests"])
32
+ page = {
33
+ "banner": f"{failing} tests are failing" if failing > 1 else "1 test is failing" if failing else None,
34
+ "skipped": [n for n, t in data["tests"].items() if t["outcome"] == "skipped"],
35
+ "insufficient": [n for n, t in data["tests"].items() if t.get("insufficient_evidence")],
36
+ "overlaps": data.get("overlaps", []),
37
+ "map": [{**d, "runtime": data["tests"][d["test"]]["duration"], "unique": data["tests"][d["test"]].get("unique_coverage", 0)}
38
+ for d in similarity_map(valued(data["tests"]))],
39
+ "inventory": inventory_line(data["inventory"]),
40
+ "pillars": [
41
+ {"key": k, "name": p["name"], **data["pillars"][k],
42
+ "metrics": [{"name": m["name"], **data["metrics"][i]} for i, m in p["metrics"].items() if i in data["metrics"]],
43
+ "total": len(p["metrics"]),
44
+ "worst": worst_tests(data["tests"], k, _slow(rules)),
45
+ "smells": pillar_smells(data["tests"], PILLAR_SMELLS.get(k, ()))}
46
+ for k, p in rules["pillars"].items()
47
+ ],
48
+ }
49
+ # "</" and U+2028/9 would end the script block or the literal early
50
+ blob = json.dumps(page).replace("</", "<\\/").replace("\u2028", "\\u2028").replace("\u2029", "\\u2029")
51
+ path = home / "dashboard.html"
52
+ path.write_text(TEMPLATE.read_text().replace("__DATA__", blob))
53
+ return path
54
+
55
+
56
+ def summary(data, rules, snapshot, dashboard):
57
+ lines = [inventory_line(data["inventory"])]
58
+ for k, p in rules["pillars"].items():
59
+ s = data["pillars"][k]
60
+ shown = "not measured" if s["score"] is None else str(display(s["score"]))
61
+ lines.append(f"{p['name']}: {shown}" + (" (partial)" if s["partial"] else ""))
62
+ failing, flaky = _failing(data["tests"]), _flaky(data["tests"])
63
+ if failing:
64
+ lines.append(f"Warning: {failing} tests are failing" if failing > 1 else "Warning: 1 test is failing")
65
+ if flaky:
66
+ lines.append(f"Warning: {flaky} flaky tests" if flaky > 1 else "Warning: 1 flaky test")
67
+ scored = {k: p["score"] for k, p in data["pillars"].items() if p["score"] is not None}
68
+ if scored:
69
+ lowest = min(scored, key=scored.get)
70
+ worst = worst_tests(data["tests"], lowest, _slow(rules), 3)
71
+ lines += [f"Worst tests ({rules['pillars'][lowest]['name']}):", *(f" {w['test']} ({w['reason']})" for w in worst)]
72
+ return "\n".join([*lines, f"Snapshot: {snapshot}", f"Dashboard: {dashboard}"])
@@ -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