@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.
- 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-prune/SKILL.md +4 -2
- package/skills/test-prune/prune_strengthen.py +24 -12
- package/skills/test-prune/tests/test_prune_guards.py +1 -1
- package/skills/test-prune/tests/test_prune_inputs.py +10 -5
- package/skills/test-prune/tests/test_prune_strengthen.py +34 -12
- 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 +156 -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 +70 -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 +134 -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 +13 -7
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
"""Per-test smells from each test function's syntax tree, one test at a time."""
|
|
2
|
+
import ast
|
|
3
|
+
import copy
|
|
4
|
+
import hashlib
|
|
5
|
+
|
|
6
|
+
from weigh_inventory import is_test
|
|
7
|
+
|
|
8
|
+
MOCK_ASSERTS = ("assert_called", "assert_any_call", "assert_has_calls", "assert_not_called", "assert_awaited", "assert_not_awaited")
|
|
9
|
+
# what an assertion on a mock reads
|
|
10
|
+
MOCK_ATTRS = ("called", "call_count", "call_args", "call_args_list", "mock_calls", "await_count", "await_args", "await_args_list")
|
|
11
|
+
MOCK_MAKERS = ("MagicMock", "Mock", "AsyncMock", "NonCallableMock", "create_autospec", "patch")
|
|
12
|
+
HELPER_ASSERTS = ("assert", "check_", "expect_")
|
|
13
|
+
RAISES = ("pytest.raises", "pytest.warns", "pytest.deprecated_call")
|
|
14
|
+
MOCK_HEAVY_ABOVE = 3
|
|
15
|
+
# Smells and Worst tests tabs: the smells of each pillar
|
|
16
|
+
PILLAR_SMELLS = {
|
|
17
|
+
"regression": ("No assertion",),
|
|
18
|
+
"refactoring": ("Mock-heavy", "Interaction-only", "Private access"),
|
|
19
|
+
"feedback": ("Real sleep",),
|
|
20
|
+
"maintainability": ("Eager test", "Conditional test logic", "Mystery guest", "Swallowed exception", "PT"),
|
|
21
|
+
"economy": ("Duplicate body",),
|
|
22
|
+
}
|
|
23
|
+
MAINTAINABILITY_SMELLS = PILLAR_SMELLS["maintainability"]
|
|
24
|
+
LONG_TEST_LINES = 50
|
|
25
|
+
EAGER_CYCLES = 3
|
|
26
|
+
SAFE_ROOTS = ("tmp_path", "tmp_path_factory", "monkeypatch")
|
|
27
|
+
FILE_READS = ("read_text", "read_bytes", "open")
|
|
28
|
+
SLEEPS = ("time.sleep", "asyncio.sleep")
|
|
29
|
+
HOME_ENV = ("os.environ", "os.getenv", "os.path.expanduser", "Path.home", "pathlib.Path.home")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _dotted(node):
|
|
33
|
+
parts = []
|
|
34
|
+
while isinstance(node, ast.Attribute):
|
|
35
|
+
parts.append(node.attr)
|
|
36
|
+
node = node.value
|
|
37
|
+
if isinstance(node, ast.Name):
|
|
38
|
+
parts.append(node.id)
|
|
39
|
+
return ".".join(reversed(parts))
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _private(name):
|
|
43
|
+
return name.startswith("_") and not name.endswith("__")
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _from_test_module(node):
|
|
47
|
+
return is_test((node.module or "").replace(".", "/") + ".py")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _scope_nodes(nodes):
|
|
51
|
+
"""The nodes of a scope's statements in source order, not those inside the functions and classes it defines."""
|
|
52
|
+
for n in nodes:
|
|
53
|
+
yield n
|
|
54
|
+
if not isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda)):
|
|
55
|
+
yield from _scope_nodes(ast.iter_child_nodes(n))
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _module_privates(tree):
|
|
59
|
+
"""Private names the module imports, at module scope, from a non-test module."""
|
|
60
|
+
found = set()
|
|
61
|
+
for n in _scope_nodes(tree.body):
|
|
62
|
+
if isinstance(n, ast.ImportFrom) and not _from_test_module(n):
|
|
63
|
+
found |= {a.asname or a.name for a in n.names if _private(a.name)}
|
|
64
|
+
return found
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _aliases(nodes):
|
|
68
|
+
"""{name bound by an import among nodes: the dotted module or object it names}; a later import wins."""
|
|
69
|
+
found = {}
|
|
70
|
+
for n in nodes:
|
|
71
|
+
if isinstance(n, ast.Import):
|
|
72
|
+
for a in n.names:
|
|
73
|
+
found[a.asname or a.name.split(".")[0]] = a.name if a.asname else a.name.split(".")[0]
|
|
74
|
+
elif isinstance(n, ast.ImportFrom):
|
|
75
|
+
found.update({a.asname or a.name: f"{n.module}.{a.name}" if n.module else a.name for a in n.names})
|
|
76
|
+
return found
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _test_owned(owner, aliases):
|
|
80
|
+
"""The object an attribute is read from is the test's own: self, cls, or a name imported from a test module."""
|
|
81
|
+
dotted = _dotted(owner)
|
|
82
|
+
if dotted in ("self", "cls"):
|
|
83
|
+
return True
|
|
84
|
+
head, _, rest = dotted.partition(".")
|
|
85
|
+
return head in aliases and is_test(".".join(filter(None, (aliases[head], rest))).replace(".", "/") + ".py")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _conjuncts(test):
|
|
89
|
+
"""The checks of an assert: each side of an `and`, each pair of an equality of two tuples or lists."""
|
|
90
|
+
if isinstance(test, ast.BoolOp) and isinstance(test.op, ast.And):
|
|
91
|
+
return [c for v in test.values for c in _conjuncts(v)]
|
|
92
|
+
sides = [test.left, *test.comparators] if isinstance(test, ast.Compare) else []
|
|
93
|
+
if (len(sides) == 2 and isinstance(test.ops[0], ast.Eq) and all(isinstance(e, (ast.Tuple, ast.List)) for e in sides)
|
|
94
|
+
and len(sides[0].elts) == len(sides[1].elts) > 0):
|
|
95
|
+
return [c for a, b in zip(sides[0].elts, sides[1].elts) for c in _conjuncts(ast.Compare(a, [ast.Eq()], [b]))]
|
|
96
|
+
return [test]
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _reads_mock(expr):
|
|
100
|
+
return any(isinstance(a, ast.Attribute) and a.attr in MOCK_ATTRS for a in ast.walk(expr))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def _assertion(n):
|
|
104
|
+
""""plain", "mock" or None: the one classification of an assertion, shared by every rule that looks for one."""
|
|
105
|
+
if isinstance(n, ast.Expr):
|
|
106
|
+
return _assertion(n.value)
|
|
107
|
+
if isinstance(n, ast.Assert):
|
|
108
|
+
# `assert result == x and sender.call_count == 1` checks a result too
|
|
109
|
+
return "plain" if not all(_reads_mock(c) for c in _conjuncts(n.test)) else "mock"
|
|
110
|
+
if isinstance(n, (ast.With, ast.AsyncWith)):
|
|
111
|
+
return "plain" if any(isinstance(i.context_expr, ast.Call) and _dotted(i.context_expr.func) in RAISES for i in n.items) else None
|
|
112
|
+
if isinstance(n, ast.Call):
|
|
113
|
+
name = _dotted(n.func)
|
|
114
|
+
last = name.split(".")[-1]
|
|
115
|
+
if last.startswith(MOCK_ASSERTS):
|
|
116
|
+
return "mock"
|
|
117
|
+
if last.lower().startswith(HELPER_ASSERTS) or name == "pytest.fail":
|
|
118
|
+
return "plain"
|
|
119
|
+
return None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def _names(node):
|
|
123
|
+
return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _safe_names(func):
|
|
127
|
+
"""Names obtained from tmp_path or monkeypatch: the fixtures and what is assigned from them."""
|
|
128
|
+
safe = {a.arg for a in func.args.args if a.arg in SAFE_ROOTS}
|
|
129
|
+
for n in ast.walk(func):
|
|
130
|
+
if isinstance(n, ast.Assign) and _names(n.value) & safe:
|
|
131
|
+
safe |= {t.id for t in n.targets if isinstance(t, ast.Name)}
|
|
132
|
+
return safe
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _literal_path(node, safe, guests):
|
|
136
|
+
"""A path built from a string literal or from a name holding one, and not from tmp_path or monkeypatch."""
|
|
137
|
+
names = _names(node)
|
|
138
|
+
return bool(any(isinstance(c, ast.Constant) and isinstance(c.value, str) for c in ast.walk(node)) or names & guests) and not names & safe
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _guest_names(func, safe):
|
|
142
|
+
"""Names assigned a literal path, in source order, so a name assigned from another one carries its path."""
|
|
143
|
+
guests = set()
|
|
144
|
+
for n in sorted((n for n in ast.walk(func) if isinstance(n, ast.Assign)), key=lambda n: (n.lineno, n.col_offset)):
|
|
145
|
+
if _literal_path(n.value, safe, guests):
|
|
146
|
+
guests |= {t.id for t in n.targets if isinstance(t, ast.Name)}
|
|
147
|
+
return guests
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _reads_guest(n, safe, guests):
|
|
151
|
+
"""A file read or home/environment access whose path is not from tmp_path or monkeypatch."""
|
|
152
|
+
if isinstance(n, ast.Attribute) and _dotted(n) in HOME_ENV:
|
|
153
|
+
return "monkeypatch" not in safe
|
|
154
|
+
if not isinstance(n, ast.Call):
|
|
155
|
+
return False
|
|
156
|
+
if isinstance(n.func, ast.Name) and n.func.id == "open" and n.args:
|
|
157
|
+
target = n.args[0]
|
|
158
|
+
elif isinstance(n.func, ast.Attribute) and n.func.attr in FILE_READS:
|
|
159
|
+
target = n.func.value
|
|
160
|
+
else:
|
|
161
|
+
return False
|
|
162
|
+
return _literal_path(target, safe, guests)
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _eager(func):
|
|
166
|
+
"""Act-then-assert cycles: a statement that is not an assertion, followed by one that is."""
|
|
167
|
+
cycles, acted = 0, False
|
|
168
|
+
|
|
169
|
+
def walk(body):
|
|
170
|
+
nonlocal cycles, acted
|
|
171
|
+
for st in body:
|
|
172
|
+
if _assertion(st):
|
|
173
|
+
cycles, acted = cycles + acted, False
|
|
174
|
+
elif isinstance(st, (ast.With, ast.AsyncWith)):
|
|
175
|
+
walk(st.body)
|
|
176
|
+
else:
|
|
177
|
+
acted = True
|
|
178
|
+
|
|
179
|
+
walk(func.body)
|
|
180
|
+
return cycles
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def _swallows(func):
|
|
184
|
+
return any(isinstance(h, ast.ExceptHandler) and not any(isinstance(x, ast.Raise) or _assertion(x) for x in ast.walk(h))
|
|
185
|
+
for n in ast.walk(func) if isinstance(n, ast.Try) for h in n.handlers)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _sleeps(func):
|
|
189
|
+
return any(isinstance(n, ast.Call) and _dotted(n.func) in SLEEPS and n.args
|
|
190
|
+
and not (isinstance(n.args[0], ast.Constant) and n.args[0].value == 0) for n in ast.walk(func))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
class _Normalize(ast.NodeTransformer):
|
|
194
|
+
"""Names and literals become placeholders; call and attribute structure stays."""
|
|
195
|
+
|
|
196
|
+
def visit_Name(self, node):
|
|
197
|
+
return ast.Name(id="_", ctx=node.ctx)
|
|
198
|
+
|
|
199
|
+
def visit_arg(self, node):
|
|
200
|
+
return ast.arg(arg="_")
|
|
201
|
+
|
|
202
|
+
def visit_Constant(self, node):
|
|
203
|
+
return ast.Constant(value=type(node.value).__name__)
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _body_hash(func):
|
|
207
|
+
body = ast.Module(body=[_Normalize().visit(copy.deepcopy(st)) for st in func.body], type_ignores=[])
|
|
208
|
+
return hashlib.sha1(ast.dump(body).encode()).hexdigest()
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def smells_of(func, module_privates, module_aliases):
|
|
212
|
+
aliases = {**module_aliases, **_aliases(ast.walk(func))}
|
|
213
|
+
kinds = {_assertion(n) for n in ast.walk(func)}
|
|
214
|
+
plain, mock, private = "plain" in kinds, "mock" in kinds, False
|
|
215
|
+
mocks = 0
|
|
216
|
+
for n in ast.walk(func):
|
|
217
|
+
if isinstance(n, ast.Call):
|
|
218
|
+
name = _dotted(n.func)
|
|
219
|
+
if name.split(".")[-1] in MOCK_MAKERS or name.startswith(("patch.", "mock.patch.")) or name == "monkeypatch.setattr":
|
|
220
|
+
mocks += 1
|
|
221
|
+
elif isinstance(n, ast.ImportFrom):
|
|
222
|
+
private |= not _from_test_module(n) and any(_private(a.name) for a in n.names)
|
|
223
|
+
elif isinstance(n, ast.Name):
|
|
224
|
+
private |= n.id in module_privates
|
|
225
|
+
elif isinstance(n, ast.Attribute):
|
|
226
|
+
private |= _private(n.attr) and not _test_owned(n.value, aliases)
|
|
227
|
+
safe = _safe_names(func)
|
|
228
|
+
guests = _guest_names(func, safe)
|
|
229
|
+
return [s for s, has in (("No assertion", not plain and not mock), ("Interaction-only", mock and not plain),
|
|
230
|
+
("Mock-heavy", mocks > MOCK_HEAVY_ABOVE), ("Private access", private),
|
|
231
|
+
("Eager test", _eager(func) >= EAGER_CYCLES),
|
|
232
|
+
("Conditional test logic", any(isinstance(n, (ast.If, ast.For, ast.While)) for n in ast.walk(func))),
|
|
233
|
+
("Mystery guest", any(_reads_guest(n, safe, guests) for n in ast.walk(func))),
|
|
234
|
+
("Swallowed exception", _swallows(func)), ("Real sleep", _sleeps(func))) if has]
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _definitions(tree):
|
|
238
|
+
"""({"Class::name" or "name": function}, {"Class": (enclosing prefix, class)}), by the qualification pytest gives;
|
|
239
|
+
a later definition wins, as in Python."""
|
|
240
|
+
functions, classes = {}, {}
|
|
241
|
+
|
|
242
|
+
def visit(body, prefix):
|
|
243
|
+
for st in body:
|
|
244
|
+
if isinstance(st, ast.ClassDef):
|
|
245
|
+
classes[prefix + st.name] = (prefix, st)
|
|
246
|
+
visit(st.body, f"{prefix}{st.name}::")
|
|
247
|
+
elif isinstance(st, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
248
|
+
functions[prefix + st.name] = st
|
|
249
|
+
|
|
250
|
+
visit(tree.body, "")
|
|
251
|
+
return functions, classes
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def _mro(classes, cls, seen=frozenset()):
|
|
255
|
+
"""Python's method resolution order (C3) of a class of the module; a base defined elsewhere ends its line."""
|
|
256
|
+
if cls not in classes or cls in seen:
|
|
257
|
+
return [cls]
|
|
258
|
+
prefix, node = classes[cls]
|
|
259
|
+
bases = [next((q for q in (prefix + d, d) if q in classes), d)
|
|
260
|
+
for d in (_dotted(b).replace(".", "::") for b in node.bases)]
|
|
261
|
+
lines, order = [_mro(classes, b, seen | {cls}) for b in bases] + [bases], [cls]
|
|
262
|
+
while lines := [line for line in lines if line]:
|
|
263
|
+
head = next((line[0] for line in lines if not any(line[0] in other[1:] for other in lines)), None)
|
|
264
|
+
if head is None: # no consistent order: Python refuses to create such a class
|
|
265
|
+
return order + [c for line in lines for c in line if c not in order]
|
|
266
|
+
order.append(head)
|
|
267
|
+
lines = [line[1:] if line[0] == head else line for line in lines]
|
|
268
|
+
return order
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def _resolve(module, qualified):
|
|
272
|
+
"""The function of a test: by its full qualification, else the method its class inherits, found in Python's
|
|
273
|
+
resolution order among the classes of the module (None when the method lives in another module)."""
|
|
274
|
+
functions, classes = module["functions"], module["classes"]
|
|
275
|
+
if qualified in functions:
|
|
276
|
+
return functions[qualified]
|
|
277
|
+
cls, _, name = qualified.rpartition("::")
|
|
278
|
+
return next((functions[f"{c}::{name}"] for c in _mro(classes, cls)[1:] if f"{c}::{name}" in functions), None)
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def find_smells(repo, tests, ruff=()):
|
|
282
|
+
"""({node: {smells, lines}}, clusters) for every test; a test whose source cannot be read or parsed has none.
|
|
283
|
+
|
|
284
|
+
ruff holds (path, row, code) violations: each is a smell of the test whose lines contain the row.
|
|
285
|
+
|
|
286
|
+
A cluster is the sorted node ids of 2 or more tests with one normalized body; each gets the smell Duplicate body."""
|
|
287
|
+
modules, result, bodies = {}, {}, {}
|
|
288
|
+
for node in tests:
|
|
289
|
+
path, _, qualified = node.partition("::")
|
|
290
|
+
if path not in modules:
|
|
291
|
+
try:
|
|
292
|
+
tree = ast.parse((repo / path).read_text(errors="replace"))
|
|
293
|
+
functions, classes = _definitions(tree)
|
|
294
|
+
modules[path] = {"functions": functions, "classes": classes, "privates": _module_privates(tree),
|
|
295
|
+
"aliases": _aliases(_scope_nodes(tree.body))}
|
|
296
|
+
except (OSError, SyntaxError, ValueError):
|
|
297
|
+
modules[path] = None
|
|
298
|
+
module = modules[path]
|
|
299
|
+
found = module and _resolve(module, qualified)
|
|
300
|
+
result[node] = {"smells": smells_of(found, module["privates"], module["aliases"]) if found else [],
|
|
301
|
+
"lines": found.end_lineno - found.lineno + 1 if found else 0}
|
|
302
|
+
if found:
|
|
303
|
+
result[node]["smells"] += sorted({c for p, row, c in ruff if p == path and found.lineno <= row <= found.end_lineno})
|
|
304
|
+
if found:
|
|
305
|
+
bodies.setdefault(_body_hash(found), []).append(node)
|
|
306
|
+
clusters = sorted(sorted(g) for g in bodies.values() if len(g) > 1)
|
|
307
|
+
for node in (n for c in clusters for n in c):
|
|
308
|
+
result[node]["smells"].append("Duplicate body")
|
|
309
|
+
return result, clusters
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def smell_values(tests):
|
|
313
|
+
"""Percentages of all tests. A hollow test is one with no assertion or one the kill matrix found hollow; an
|
|
314
|
+
insufficient-evidence test counts in no Economy metric (duplicate clusters)."""
|
|
315
|
+
n = len(tests) or 1
|
|
316
|
+
share = lambda smell: 100 * sum(smell in t["smells"] for t in tests.values()) / n
|
|
317
|
+
return {"hollow_tests": 100 * sum("No assertion" in t["smells"] or t.get("hollow", False) for t in tests.values()) / n,
|
|
318
|
+
"duplicate_clusters": 100 * sum("Duplicate body" in t["smells"] and not t.get("insufficient_evidence") for t in tests.values()) / n,
|
|
319
|
+
"smelly_tests": 100 * sum(any(s.startswith(MAINTAINABILITY_SMELLS) for s in t["smells"]) for t in tests.values()) / n,
|
|
320
|
+
"long_tests": 100 * sum(t["lines"] > LONG_TEST_LINES for t in tests.values()) / n, "mock_heavy": share("Mock-heavy"),
|
|
321
|
+
"interaction_only": share("Interaction-only"), "private_access": share("Private access")}
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
def pillar_smells(tests, smells):
|
|
325
|
+
"""{smell: sorted node ids that have it}, for the smells given (a prefix such as "PT" matches every PT code)."""
|
|
326
|
+
found = {}
|
|
327
|
+
for node, t in sorted(tests.items()):
|
|
328
|
+
for s in t["smells"]:
|
|
329
|
+
if s.startswith(smells):
|
|
330
|
+
found.setdefault(s, []).append(node)
|
|
331
|
+
return dict(sorted(found.items()))
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _measured(test, pillar, slow):
|
|
335
|
+
"""(reasons, weight) a test ranks low by in a pillar beyond its smells: its length, duration or redundant coverage."""
|
|
336
|
+
if pillar == "maintainability" and test["lines"] > LONG_TEST_LINES:
|
|
337
|
+
return [f"{test['lines']} lines"], test["lines"]
|
|
338
|
+
if pillar == "feedback" and test["duration"] > slow:
|
|
339
|
+
return [f"{test['duration']:.2f} s"], test["duration"]
|
|
340
|
+
# unique coverage is measured only for tests that passed unflaky
|
|
341
|
+
if pillar == "economy" and test["outcome"] == "passed" and not test["flaky"] and not test.get("unique_coverage", 0):
|
|
342
|
+
return ["No unique coverage"], 0
|
|
343
|
+
return [], 0
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def worst_tests(tests, pillar, slow, limit=10):
|
|
347
|
+
"""The lowest-ranked tests of a pillar, each with its reasons: most reasons first, then the longest or slowest.
|
|
348
|
+
A test is slow above `slow` seconds."""
|
|
349
|
+
ranked = []
|
|
350
|
+
for node, t in tests.items():
|
|
351
|
+
extra, weight = _measured(t, pillar, slow)
|
|
352
|
+
reasons = [s for s in t["smells"] if s.startswith(PILLAR_SMELLS.get(pillar, ()))] + extra
|
|
353
|
+
if reasons:
|
|
354
|
+
ranked.append((-len(reasons), -weight, node, reasons))
|
|
355
|
+
return [{"test": n, "reason": ", ".join(r)} for _, _, n, r in sorted(ranked)[:limit]]
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""Repo key, commit state and exclusive snapshot writing under ~/.test-weigh-in/."""
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import re
|
|
5
|
+
import subprocess
|
|
6
|
+
from datetime import datetime, timezone
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from weigh_env import SetupError
|
|
10
|
+
|
|
11
|
+
REMOTE = re.compile(r"^(?:[a-z+]+://)?(?:[^@/]+@)?([^:/]+)[:/](.+?)(?:\.git)?/?$")
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def git(repo, *args):
|
|
15
|
+
return subprocess.run(["git", *args], cwd=repo, capture_output=True, text=True).stdout.strip()
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def repo_key(repo):
|
|
19
|
+
origin = git(repo, "remote", "get-url", "origin")
|
|
20
|
+
m = REMOTE.match(origin)
|
|
21
|
+
key = f"{m[1]}/{m[2]}" if m else f"local/{repo.name}"
|
|
22
|
+
# The key is a path under ~/.test-weigh-in: an origin like host:../../x must not climb out of it.
|
|
23
|
+
if any(part in ("", ".", "..") for part in key.split("/")):
|
|
24
|
+
raise SetupError(f"cannot store snapshots for origin {origin!r}: its path has an empty, . or .. segment")
|
|
25
|
+
return key
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def commit_state(repo):
|
|
29
|
+
return git(repo, "rev-parse", "--short", "HEAD"), bool(git(repo, "status", "--porcelain"))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def home_dir(repo):
|
|
33
|
+
return Path.home() / ".test-weigh-in" / repo_key(repo)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def write_snapshot(home, data):
|
|
37
|
+
home.mkdir(parents=True, exist_ok=True)
|
|
38
|
+
now = os.environ.get("TEST_WEIGH_IN_NOW")
|
|
39
|
+
when = datetime.fromisoformat(now.replace("Z", "+00:00")) if now else datetime.now(timezone.utc)
|
|
40
|
+
stem = f"{when:%Y%m%dT%H%M%SZ}_{data['commit']}"
|
|
41
|
+
n = 1
|
|
42
|
+
while True:
|
|
43
|
+
path = home / (f"{stem}.json" if n == 1 else f"{stem}-{n}.json")
|
|
44
|
+
try:
|
|
45
|
+
with path.open("x") as out:
|
|
46
|
+
json.dump(data, out, indent=2)
|
|
47
|
+
return path
|
|
48
|
+
except FileExistsError:
|
|
49
|
+
n += 1
|
package/skills-manifest.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schemaVersion": 1,
|
|
3
|
-
"generatedAt": "2026-11-
|
|
3
|
+
"generatedAt": "2026-11-03T07:02:30.559Z",
|
|
4
4
|
"skills": [
|
|
5
5
|
{
|
|
6
6
|
"name": "agents-wayfinder",
|
|
@@ -34,8 +34,8 @@
|
|
|
34
34
|
},
|
|
35
35
|
{
|
|
36
36
|
"name": "crap-gate",
|
|
37
|
-
"version": "0.1.
|
|
38
|
-
"hash": "sha256-
|
|
37
|
+
"version": "0.1.5",
|
|
38
|
+
"hash": "sha256-ddf100022e078ad567efc30cdffb02d2e332e59db5866614e42c100173a7974f",
|
|
39
39
|
"description": "Score every function a branch changed with CRAP (cyclomatic complexity × untested fraction), fail on existing functions above 15 and new functions above 9, and drive a fixer + independent reviewer loop until the gate passes. Use when implementation is done and before pushing, when the user says \"run the crap gate\", \"check CRAP\", \"is this change tested enough\", or when a push gate reports CRAP violations."
|
|
40
40
|
},
|
|
41
41
|
{
|
|
@@ -58,8 +58,8 @@
|
|
|
58
58
|
},
|
|
59
59
|
{
|
|
60
60
|
"name": "implement-spec",
|
|
61
|
-
"version": "0.1.
|
|
62
|
-
"hash": "sha256-
|
|
61
|
+
"version": "0.1.48",
|
|
62
|
+
"hash": "sha256-c1c51c34db8cb4c87c3437b3b0c1569dbabb60e327b3afdeaa5e0b9306efa0ba",
|
|
63
63
|
"description": "Implement a specification in code."
|
|
64
64
|
},
|
|
65
65
|
{
|
|
@@ -100,10 +100,16 @@
|
|
|
100
100
|
},
|
|
101
101
|
{
|
|
102
102
|
"name": "test-prune",
|
|
103
|
-
"version": "0.1.
|
|
104
|
-
"hash": "sha256-
|
|
103
|
+
"version": "0.1.6",
|
|
104
|
+
"hash": "sha256-cc46e2d40c52615a88a53f87c62f60ddc6944cacad55427a83f9191cd0900410",
|
|
105
105
|
"description": "Mutation-guided test pruning: a fixer proposes deleting redundant tests and strengthening weak ones, an independent reviewer accepts or rejects each proposal, and prune.py applies the accepted batch behind a cold mutation run and the ratchet. Use when the user says \"prune tests\", \"test-prune\", \"mutation test pruning\" or \"strengthen weak tests\", or when a scheduled job runs it with `--unattended`."
|
|
106
106
|
},
|
|
107
|
+
{
|
|
108
|
+
"name": "test-weigh-in",
|
|
109
|
+
"version": "0.1.0",
|
|
110
|
+
"hash": "sha256-b121ea2a0c8d1f96aac95e5d3d45ebdf11f64d89ec71ef04c67bdeb12bfd1179",
|
|
111
|
+
"description": "Measure a Python/pytest suite and score it on five pillars (Protection against regressions, Resistance to refactoring, Fast feedback, Maintainability, Economy), writing a JSON snapshot and a static HTML dashboard. Read-only. Use when the user asks to weigh, measure or score their test suite."
|
|
112
|
+
},
|
|
107
113
|
{
|
|
108
114
|
"name": "to-openspec",
|
|
109
115
|
"version": "0.1.3",
|