lie-detector 0.0.0-stage → 0.1.0
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/LICENSE +21 -0
- package/README.md +264 -2
- package/dist/cli.js +282 -0
- package/dist/diff.js +250 -0
- package/dist/mutators/py.js +35 -0
- package/dist/mutators/ts.js +288 -0
- package/dist/mutators/types.js +1 -0
- package/dist/quick/py.js +18 -0
- package/dist/quick/ts.js +159 -0
- package/dist/quick/types.js +1 -0
- package/dist/report/coverage.js +53 -0
- package/dist/report/index.js +72 -0
- package/dist/report/json.js +3 -0
- package/dist/report/markdown.js +128 -0
- package/dist/report/terminal.js +35 -0
- package/dist/report/types.js +1 -0
- package/dist/restore.js +63 -0
- package/dist/runner.js +133 -0
- package/package.json +62 -4
- package/scripts/__init__.py +0 -0
- package/scripts/py/__init__.py +0 -0
- package/scripts/py/mutate.py +344 -0
- package/scripts/py/quick.py +184 -0
- package/scripts/py/test_mutate.py +63 -0
- package/scripts/py/test_quick.py +39 -0
- package/skills/test-quality-audit/SKILL.md +169 -0
- package/skills/test-quality-audit/references/mutation-operators.md +76 -0
- package/skills/test-quality-audit/references/quick-patterns.md +33 -0
- package/skills/test-quality-audit/references/report-format.md +93 -0
- package/skills/test-quality-audit/references/troubleshooting.md +68 -0
package/package.json
CHANGED
|
@@ -1,6 +1,64 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "lie-detector",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Find tests that pass but don't test anything. Mutation-testing skill for Claude Code.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"lie-detector": "./dist/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"dist",
|
|
11
|
+
"scripts",
|
|
12
|
+
"skills",
|
|
13
|
+
"README.md",
|
|
14
|
+
"LICENSE"
|
|
15
|
+
],
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "tsc -p tsconfig.json",
|
|
18
|
+
"dev": "tsx src/cli.ts",
|
|
19
|
+
"test": "vitest run --passWithNoTests",
|
|
20
|
+
"test:watch": "vitest",
|
|
21
|
+
"test:py": "python3 -m unittest scripts/py/test_mutate.py scripts/py/test_quick.py",
|
|
22
|
+
"test:all": "npm test && npm run test:py",
|
|
23
|
+
"e2e": "bash test/e2e.sh",
|
|
24
|
+
"prepublishOnly": "npm run build && npm test"
|
|
25
|
+
},
|
|
26
|
+
"keywords": [
|
|
27
|
+
"claude",
|
|
28
|
+
"claude-code",
|
|
29
|
+
"skill",
|
|
30
|
+
"mutation-testing",
|
|
31
|
+
"testing",
|
|
32
|
+
"test-quality"
|
|
33
|
+
],
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=22"
|
|
37
|
+
},
|
|
38
|
+
"dependencies": {
|
|
39
|
+
"@babel/generator": "^7.28.5",
|
|
40
|
+
"@babel/parser": "^7.28.5",
|
|
41
|
+
"@babel/traverse": "^7.28.5",
|
|
42
|
+
"@babel/types": "^7.28.5"
|
|
43
|
+
},
|
|
44
|
+
"devDependencies": {
|
|
45
|
+
"@types/babel__generator": "^7.27.0",
|
|
46
|
+
"@types/babel__traverse": "^7.28.0",
|
|
47
|
+
"@types/node": "^24.10.1",
|
|
48
|
+
"@vitest/coverage-v8": "^3.2.4",
|
|
49
|
+
"tsx": "^4.20.6",
|
|
50
|
+
"typescript": "^5.9.3",
|
|
51
|
+
"vitest": "^3.2.4"
|
|
52
|
+
},
|
|
53
|
+
"repository": {
|
|
54
|
+
"type": "git",
|
|
55
|
+
"url": "git+https://github.com/Selahattinozdmr/lie-detector.git"
|
|
56
|
+
},
|
|
57
|
+
"homepage": "https://selahattinozdmr.github.io/lie-detector/",
|
|
58
|
+
"bugs": {
|
|
59
|
+
"url": "https://github.com/Selahattinozdmr/lie-detector/issues"
|
|
60
|
+
},
|
|
61
|
+
"publishConfig": {
|
|
62
|
+
"access": "public"
|
|
63
|
+
}
|
|
64
|
+
}
|
|
File without changes
|
|
File without changes
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Small, stdlib-only Python mutator for lie-detector.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
python3 mutate.py --file path/to/file.py [--lines 1,2,3] [--max 50]
|
|
6
|
+
|
|
7
|
+
Prints a JSON array. Each item has the same shape as the TypeScript mutator's
|
|
8
|
+
Mutant: id, file, line, column, operator, original, replacement, mutatedSource.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import ast
|
|
15
|
+
import copy
|
|
16
|
+
import json
|
|
17
|
+
import sys
|
|
18
|
+
from typing import Dict, Iterable, List, Optional, Set, Tuple
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
COMPARE_MAP = {
|
|
22
|
+
ast.Lt: (ast.LtE, "< -> <="),
|
|
23
|
+
ast.LtE: (ast.Lt, "<= -> <"),
|
|
24
|
+
ast.Gt: (ast.GtE, "> -> >="),
|
|
25
|
+
ast.GtE: (ast.Gt, ">= -> >"),
|
|
26
|
+
ast.Eq: (ast.NotEq, "== -> !="),
|
|
27
|
+
ast.NotEq: (ast.Eq, "!= -> =="),
|
|
28
|
+
ast.Is: (ast.IsNot, "is -> is not"),
|
|
29
|
+
ast.IsNot: (ast.Is, "is not -> is"),
|
|
30
|
+
ast.In: (ast.NotIn, "in -> not in"),
|
|
31
|
+
ast.NotIn: (ast.In, "not in -> in"),
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
BINOP_MAP = {
|
|
35
|
+
ast.Add: (ast.Sub, "+ -> -"),
|
|
36
|
+
ast.Sub: (ast.Add, "- -> +"),
|
|
37
|
+
ast.Mult: (ast.Div, "* -> /"),
|
|
38
|
+
ast.Div: (ast.Mult, "/ -> *"),
|
|
39
|
+
ast.FloorDiv: (ast.Div, "// -> /"),
|
|
40
|
+
ast.Mod: (ast.Mult, "% -> *"),
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
BOOLOP_MAP = {
|
|
44
|
+
ast.And: (ast.Or, "and -> or"),
|
|
45
|
+
ast.Or: (ast.And, "or -> and"),
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _line(node: ast.AST) -> int:
|
|
50
|
+
return getattr(node, "lineno", 0) or 0
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _column(node: ast.AST) -> int:
|
|
54
|
+
return (getattr(node, "col_offset", 0) or 0) + 1
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _is_ignored(source: str, line: int) -> bool:
|
|
58
|
+
rows = source.splitlines()
|
|
59
|
+
current = rows[line - 1] if 0 <= line - 1 < len(rows) else ""
|
|
60
|
+
previous = rows[line - 2] if 0 <= line - 2 < len(rows) else ""
|
|
61
|
+
return "lie-detector-ignore" in current or "lie-detector-ignore" in previous
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _parents(tree: ast.AST) -> Dict[ast.AST, ast.AST]:
|
|
65
|
+
parent: Dict[ast.AST, ast.AST] = {}
|
|
66
|
+
for node in ast.walk(tree):
|
|
67
|
+
for child in ast.iter_child_nodes(node):
|
|
68
|
+
parent[child] = node
|
|
69
|
+
return parent
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _find_clone(root: ast.AST, candidate: dict) -> Optional[ast.AST]:
|
|
73
|
+
for node in ast.walk(root):
|
|
74
|
+
if (
|
|
75
|
+
type(node).__name__ == candidate["nodeType"]
|
|
76
|
+
and getattr(node, "lineno", 0) == candidate["line"]
|
|
77
|
+
and (getattr(node, "col_offset", 0) or 0) + 1 == candidate["column"]
|
|
78
|
+
and getattr(node, "end_lineno", None) == candidate["endLine"]
|
|
79
|
+
and getattr(node, "end_col_offset", None) == candidate["endColumn"]
|
|
80
|
+
):
|
|
81
|
+
return node
|
|
82
|
+
return None
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _apply(node: ast.AST, candidate: dict) -> None:
|
|
86
|
+
kind = candidate["kind"]
|
|
87
|
+
if kind == "compare":
|
|
88
|
+
new_cls = COMPARE_MAP[type(node.ops[candidate["opIndex"]])][0]
|
|
89
|
+
node.ops[candidate["opIndex"]] = new_cls()
|
|
90
|
+
elif kind == "binop":
|
|
91
|
+
new_cls = BINOP_MAP[type(node.op)][0]
|
|
92
|
+
node.op = new_cls()
|
|
93
|
+
elif kind == "boolop":
|
|
94
|
+
new_cls = BOOLOP_MAP[type(node.op)][0]
|
|
95
|
+
node.op = new_cls()
|
|
96
|
+
elif kind == "return":
|
|
97
|
+
node.value = ast.Constant(value=None)
|
|
98
|
+
elif kind == "negate":
|
|
99
|
+
node.test = ast.UnaryOp(op=ast.Not(), operand=node.test)
|
|
100
|
+
elif kind == "string":
|
|
101
|
+
node.value = candidate["replacement"]
|
|
102
|
+
node.kind = None
|
|
103
|
+
elif kind == "boolean":
|
|
104
|
+
node.value = candidate["replacement"] == "True"
|
|
105
|
+
node.kind = None
|
|
106
|
+
elif kind == "number":
|
|
107
|
+
node.value = 1 if node.value == 0 else 0
|
|
108
|
+
node.kind = None
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _add(
|
|
112
|
+
candidates: List[dict],
|
|
113
|
+
*,
|
|
114
|
+
kind: str,
|
|
115
|
+
node: ast.AST,
|
|
116
|
+
source: str,
|
|
117
|
+
lines: Optional[Set[int]],
|
|
118
|
+
operator: str,
|
|
119
|
+
original: str,
|
|
120
|
+
replacement: str,
|
|
121
|
+
node_type: Optional[str] = None,
|
|
122
|
+
op_index: int = 0,
|
|
123
|
+
) -> None:
|
|
124
|
+
line = _line(node)
|
|
125
|
+
if line <= 0:
|
|
126
|
+
return
|
|
127
|
+
if lines is not None and line not in lines:
|
|
128
|
+
return
|
|
129
|
+
if _is_ignored(source, line):
|
|
130
|
+
return
|
|
131
|
+
candidates.append(
|
|
132
|
+
{
|
|
133
|
+
"kind": kind,
|
|
134
|
+
"nodeType": node_type or type(node).__name__,
|
|
135
|
+
"line": line,
|
|
136
|
+
"column": _column(node),
|
|
137
|
+
"endLine": getattr(node, "end_lineno", None),
|
|
138
|
+
"endColumn": getattr(node, "end_col_offset", None),
|
|
139
|
+
"operator": operator,
|
|
140
|
+
"original": original,
|
|
141
|
+
"replacement": replacement,
|
|
142
|
+
"opIndex": op_index,
|
|
143
|
+
}
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def mutate_source(
|
|
148
|
+
source: str,
|
|
149
|
+
filename: str = "input.py",
|
|
150
|
+
lines: Optional[Iterable[int]] = None,
|
|
151
|
+
) -> List[dict]:
|
|
152
|
+
tree = ast.parse(source, filename=filename)
|
|
153
|
+
parent = _parents(tree)
|
|
154
|
+
allowed: Optional[Set[int]] = set(lines) if lines is not None else None
|
|
155
|
+
candidates: List[dict] = []
|
|
156
|
+
|
|
157
|
+
for node in ast.walk(tree):
|
|
158
|
+
node_type = type(node).__name__
|
|
159
|
+
|
|
160
|
+
if isinstance(node, ast.Compare):
|
|
161
|
+
for index, op in enumerate(node.ops):
|
|
162
|
+
mapped = COMPARE_MAP.get(type(op))
|
|
163
|
+
if mapped:
|
|
164
|
+
_add(
|
|
165
|
+
candidates,
|
|
166
|
+
kind="compare",
|
|
167
|
+
node=node,
|
|
168
|
+
source=source,
|
|
169
|
+
lines=allowed,
|
|
170
|
+
operator=mapped[1],
|
|
171
|
+
original=type(op).__name__,
|
|
172
|
+
replacement=mapped[0].__name__,
|
|
173
|
+
op_index=index,
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
elif isinstance(node, ast.BinOp):
|
|
177
|
+
mapped = BINOP_MAP.get(type(node.op))
|
|
178
|
+
if mapped:
|
|
179
|
+
_add(
|
|
180
|
+
candidates,
|
|
181
|
+
kind="binop",
|
|
182
|
+
node=node,
|
|
183
|
+
source=source,
|
|
184
|
+
lines=allowed,
|
|
185
|
+
operator=mapped[1],
|
|
186
|
+
original=type(node.op).__name__,
|
|
187
|
+
replacement=mapped[0].__name__,
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
elif isinstance(node, ast.BoolOp):
|
|
191
|
+
mapped = BOOLOP_MAP.get(type(node.op))
|
|
192
|
+
if mapped:
|
|
193
|
+
_add(
|
|
194
|
+
candidates,
|
|
195
|
+
kind="boolop",
|
|
196
|
+
node=node,
|
|
197
|
+
source=source,
|
|
198
|
+
lines=allowed,
|
|
199
|
+
operator=mapped[1],
|
|
200
|
+
original=type(node.op).__name__,
|
|
201
|
+
replacement=mapped[0].__name__,
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
elif isinstance(node, ast.Return) and node.value is not None:
|
|
205
|
+
if isinstance(node.value, ast.Constant) and node.value.value is None:
|
|
206
|
+
continue
|
|
207
|
+
_add(
|
|
208
|
+
candidates,
|
|
209
|
+
kind="return",
|
|
210
|
+
node=node,
|
|
211
|
+
source=source,
|
|
212
|
+
lines=allowed,
|
|
213
|
+
operator="return -> None",
|
|
214
|
+
original=ast.unparse(node.value),
|
|
215
|
+
replacement="None",
|
|
216
|
+
)
|
|
217
|
+
|
|
218
|
+
elif isinstance(node, (ast.If, ast.IfExp)):
|
|
219
|
+
_add(
|
|
220
|
+
candidates,
|
|
221
|
+
kind="negate",
|
|
222
|
+
node=node,
|
|
223
|
+
source=source,
|
|
224
|
+
lines=allowed,
|
|
225
|
+
operator="condition -> negated",
|
|
226
|
+
original=ast.unparse(node.test),
|
|
227
|
+
replacement="not (...)",
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
elif isinstance(node, ast.Constant):
|
|
231
|
+
p = parent.get(node)
|
|
232
|
+
if isinstance(p, (ast.Import, ast.ImportFrom, ast.JoinedStr, ast.Expr)):
|
|
233
|
+
continue
|
|
234
|
+
if isinstance(node.value, bool):
|
|
235
|
+
_add(
|
|
236
|
+
candidates,
|
|
237
|
+
kind="boolean",
|
|
238
|
+
node=node,
|
|
239
|
+
source=source,
|
|
240
|
+
lines=allowed,
|
|
241
|
+
operator=f"{node.value} -> {not node.value}",
|
|
242
|
+
original=str(node.value),
|
|
243
|
+
replacement=str(not node.value),
|
|
244
|
+
)
|
|
245
|
+
elif isinstance(node.value, str):
|
|
246
|
+
replacement = "" if node.value else "lie-detector"
|
|
247
|
+
_add(
|
|
248
|
+
candidates,
|
|
249
|
+
kind="string",
|
|
250
|
+
node=node,
|
|
251
|
+
source=source,
|
|
252
|
+
lines=allowed,
|
|
253
|
+
operator=f'string "{node.value}" -> "{replacement}"',
|
|
254
|
+
original=node.value,
|
|
255
|
+
replacement=replacement,
|
|
256
|
+
)
|
|
257
|
+
elif isinstance(node.value, (int, float)) and not isinstance(node.value, bool):
|
|
258
|
+
replacement = 1 if node.value == 0 else 0
|
|
259
|
+
_add(
|
|
260
|
+
candidates,
|
|
261
|
+
kind="number",
|
|
262
|
+
node=node,
|
|
263
|
+
source=source,
|
|
264
|
+
lines=allowed,
|
|
265
|
+
operator=f"{node.value} -> {replacement}",
|
|
266
|
+
original=str(node.value),
|
|
267
|
+
replacement=str(replacement),
|
|
268
|
+
)
|
|
269
|
+
|
|
270
|
+
mutants: List[dict] = []
|
|
271
|
+
seen = set()
|
|
272
|
+
for candidate in candidates:
|
|
273
|
+
key = (
|
|
274
|
+
candidate["nodeType"],
|
|
275
|
+
candidate["line"],
|
|
276
|
+
candidate["column"],
|
|
277
|
+
candidate["endLine"],
|
|
278
|
+
candidate["endColumn"],
|
|
279
|
+
candidate["operator"],
|
|
280
|
+
candidate["opIndex"],
|
|
281
|
+
)
|
|
282
|
+
if key in seen:
|
|
283
|
+
continue
|
|
284
|
+
seen.add(key)
|
|
285
|
+
|
|
286
|
+
clone = copy.deepcopy(tree)
|
|
287
|
+
target = _find_clone(clone, candidate)
|
|
288
|
+
if target is None:
|
|
289
|
+
continue
|
|
290
|
+
try:
|
|
291
|
+
_apply(target, candidate)
|
|
292
|
+
ast.fix_missing_locations(clone)
|
|
293
|
+
mutated_source = ast.unparse(clone).rstrip() + "\n"
|
|
294
|
+
except Exception:
|
|
295
|
+
continue
|
|
296
|
+
|
|
297
|
+
if mutated_source == source:
|
|
298
|
+
continue
|
|
299
|
+
|
|
300
|
+
mutants.append(
|
|
301
|
+
{
|
|
302
|
+
"id": f"{filename}:{candidate['line']}:{candidate['column']}:{len(mutants) + 1}",
|
|
303
|
+
"file": filename,
|
|
304
|
+
"line": candidate["line"],
|
|
305
|
+
"column": candidate["column"],
|
|
306
|
+
"operator": candidate["operator"],
|
|
307
|
+
"original": candidate["original"],
|
|
308
|
+
"replacement": candidate["replacement"],
|
|
309
|
+
"mutatedSource": mutated_source,
|
|
310
|
+
}
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
return mutants
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
317
|
+
parser = argparse.ArgumentParser(description="Generate Python mutants as JSON")
|
|
318
|
+
parser.add_argument("--file", required=True, help="Python source file")
|
|
319
|
+
parser.add_argument("--lines", default="", help="Comma-separated changed line numbers")
|
|
320
|
+
parser.add_argument("--max", type=int, default=0, help="Maximum mutants (0 = no limit)")
|
|
321
|
+
args = parser.parse_args(argv)
|
|
322
|
+
|
|
323
|
+
lines: Optional[Set[int]]
|
|
324
|
+
if args.lines.strip():
|
|
325
|
+
try:
|
|
326
|
+
lines = {int(part) for part in args.lines.split(",") if part.strip()}
|
|
327
|
+
except ValueError:
|
|
328
|
+
parser.error("--lines must be a comma-separated list of integers")
|
|
329
|
+
else:
|
|
330
|
+
lines = None
|
|
331
|
+
|
|
332
|
+
with open(args.file, "r", encoding="utf-8") as handle:
|
|
333
|
+
source = handle.read()
|
|
334
|
+
|
|
335
|
+
mutants = mutate_source(source, filename=args.file, lines=lines)
|
|
336
|
+
if args.max and args.max > 0:
|
|
337
|
+
mutants = mutants[: args.max]
|
|
338
|
+
json.dump(mutants, sys.stdout, ensure_ascii=False)
|
|
339
|
+
sys.stdout.write("\n")
|
|
340
|
+
return 0
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
if __name__ == "__main__":
|
|
344
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Static, zero-execution test quality checks for Python test files."""
|
|
3
|
+
|
|
4
|
+
from __future__ import annotations
|
|
5
|
+
|
|
6
|
+
import argparse
|
|
7
|
+
import ast
|
|
8
|
+
import json
|
|
9
|
+
import sys
|
|
10
|
+
from typing import Dict, List, Optional
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
MESSAGES = {
|
|
14
|
+
"no-assertion": "Test has no assert statement or assertion helper call.",
|
|
15
|
+
"tautology": "Assertion compares a literal to itself or asserts a constant truth.",
|
|
16
|
+
"self-comparison": "Assertion compares a value to itself.",
|
|
17
|
+
"snapshot-only": "Test only asserts a snapshot.",
|
|
18
|
+
"mock-only": "Test only asserts that a mock was called.",
|
|
19
|
+
"weak-assertion": "Test only asserts existence or truthiness.",
|
|
20
|
+
"empty-test": "Test body is empty.",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
SEVERITY = {
|
|
24
|
+
"no-assertion": "high",
|
|
25
|
+
"tautology": "high",
|
|
26
|
+
"self-comparison": "high",
|
|
27
|
+
"snapshot-only": "medium",
|
|
28
|
+
"mock-only": "medium",
|
|
29
|
+
"weak-assertion": "medium",
|
|
30
|
+
"empty-test": "high",
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
MOCK_METHODS = {
|
|
34
|
+
"assert_called",
|
|
35
|
+
"assert_called_once",
|
|
36
|
+
"assert_called_with",
|
|
37
|
+
"assert_called_once_with",
|
|
38
|
+
"assert_any_call",
|
|
39
|
+
"assert_has_calls",
|
|
40
|
+
"assert_not_called",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _call_attr(node: ast.AST) -> Optional[str]:
|
|
45
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
|
|
46
|
+
return node.func.attr
|
|
47
|
+
return None
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _is_none(node: ast.AST) -> bool:
|
|
51
|
+
return isinstance(node, ast.Constant) and node.value is None
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _is_constant_truth(node: ast.AST) -> bool:
|
|
55
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, bool):
|
|
56
|
+
return node.value is True
|
|
57
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)):
|
|
58
|
+
return node.value == 1
|
|
59
|
+
if isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.Not):
|
|
60
|
+
return _is_constant_truth(node.operand)
|
|
61
|
+
return False
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _is_weak_assert(node: ast.AST) -> bool:
|
|
65
|
+
if not isinstance(node, ast.Assert):
|
|
66
|
+
return False
|
|
67
|
+
test = node.test
|
|
68
|
+
if not isinstance(test, ast.Compare) or len(test.ops) != 1 or len(test.comparators) != 1:
|
|
69
|
+
return False
|
|
70
|
+
if not isinstance(test.ops[0], (ast.Is, ast.IsNot)):
|
|
71
|
+
return False
|
|
72
|
+
return _is_none(test.comparators[0])
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _is_self_compare(node: ast.AST) -> bool:
|
|
76
|
+
if not isinstance(node, ast.Assert):
|
|
77
|
+
return False
|
|
78
|
+
test = node.test
|
|
79
|
+
if not isinstance(test, ast.Compare) or len(test.ops) != 1 or len(test.comparators) != 1:
|
|
80
|
+
return False
|
|
81
|
+
left = ast.unparse(test.left)
|
|
82
|
+
right = ast.unparse(test.comparators[0])
|
|
83
|
+
return left == right
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _has_raises(body: List[ast.stmt]) -> bool:
|
|
87
|
+
for node in ast.walk(ast.Module(body=body, type_ignores=[])):
|
|
88
|
+
if isinstance(node, ast.With):
|
|
89
|
+
for item in node.items:
|
|
90
|
+
call = item.context_expr
|
|
91
|
+
if isinstance(call, ast.Call):
|
|
92
|
+
func = call.func
|
|
93
|
+
if isinstance(func, ast.Attribute) and func.attr == "raises":
|
|
94
|
+
return True
|
|
95
|
+
if isinstance(func, ast.Name) and func.id == "raises":
|
|
96
|
+
return True
|
|
97
|
+
return False
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def analyze_test(node: ast.FunctionDef) -> Optional[str]:
|
|
101
|
+
body = node.body
|
|
102
|
+
if len(body) == 1 and isinstance(body[0], ast.Pass):
|
|
103
|
+
return "empty-test"
|
|
104
|
+
|
|
105
|
+
asserts: List[ast.Assert] = []
|
|
106
|
+
value_helpers = 0
|
|
107
|
+
mock_calls = 0
|
|
108
|
+
|
|
109
|
+
for child in ast.walk(ast.Module(body=body, type_ignores=[])):
|
|
110
|
+
if isinstance(child, ast.Assert):
|
|
111
|
+
asserts.append(child)
|
|
112
|
+
elif isinstance(child, ast.Call):
|
|
113
|
+
attr = _call_attr(child)
|
|
114
|
+
if attr in MOCK_METHODS:
|
|
115
|
+
mock_calls += 1
|
|
116
|
+
elif attr and attr.startswith("assert"):
|
|
117
|
+
value_helpers += 1
|
|
118
|
+
|
|
119
|
+
has_raises = _has_raises(body)
|
|
120
|
+
has_value_assertion = bool(asserts) or value_helpers > 0 or has_raises
|
|
121
|
+
|
|
122
|
+
if not has_value_assertion and mock_calls == 0:
|
|
123
|
+
return "no-assertion"
|
|
124
|
+
|
|
125
|
+
if any(_is_constant_truth(assert_node.test) for assert_node in asserts):
|
|
126
|
+
return "tautology"
|
|
127
|
+
|
|
128
|
+
if any(_is_self_compare(assert_node) for assert_node in asserts):
|
|
129
|
+
return "self-comparison"
|
|
130
|
+
|
|
131
|
+
if mock_calls > 0 and not has_value_assertion:
|
|
132
|
+
return "mock-only"
|
|
133
|
+
|
|
134
|
+
if asserts and not has_raises and value_helpers == 0 and all(
|
|
135
|
+
_is_weak_assert(assert_node) for assert_node in asserts
|
|
136
|
+
):
|
|
137
|
+
return "weak-assertion"
|
|
138
|
+
|
|
139
|
+
return None
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def quick_scan(source: str, filename: str = "test_input.py") -> List[Dict[str, object]]:
|
|
143
|
+
tree = ast.parse(source, filename=filename)
|
|
144
|
+
findings: List[Dict[str, object]] = []
|
|
145
|
+
|
|
146
|
+
for node in tree.body:
|
|
147
|
+
if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
148
|
+
continue
|
|
149
|
+
if not node.name.startswith("test_"):
|
|
150
|
+
continue
|
|
151
|
+
|
|
152
|
+
pattern = analyze_test(node)
|
|
153
|
+
if pattern is None:
|
|
154
|
+
continue
|
|
155
|
+
|
|
156
|
+
findings.append(
|
|
157
|
+
{
|
|
158
|
+
"file": filename,
|
|
159
|
+
"line": node.lineno,
|
|
160
|
+
"testName": node.name,
|
|
161
|
+
"pattern": pattern,
|
|
162
|
+
"message": MESSAGES[pattern],
|
|
163
|
+
"severity": SEVERITY[pattern],
|
|
164
|
+
}
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
return findings
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def main(argv: Optional[List[str]] = None) -> int:
|
|
171
|
+
parser = argparse.ArgumentParser(description="Static test quality checks for Python")
|
|
172
|
+
parser.add_argument("--file", required=True, help="Python test file")
|
|
173
|
+
args = parser.parse_args(argv)
|
|
174
|
+
|
|
175
|
+
with open(args.file, "r", encoding="utf-8") as handle:
|
|
176
|
+
source = handle.read()
|
|
177
|
+
|
|
178
|
+
json.dump(quick_scan(source, args.file), sys.stdout, ensure_ascii=False)
|
|
179
|
+
sys.stdout.write("\n")
|
|
180
|
+
return 0
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
if __name__ == "__main__":
|
|
184
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from scripts.py.mutate import mutate_source
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class MutateSourceTests(unittest.TestCase):
|
|
7
|
+
def test_expected_operators_on_changed_line(self):
|
|
8
|
+
source = "def is_positive(n):\n return n > 0\n"
|
|
9
|
+
|
|
10
|
+
mutants = mutate_source(source, filename="calc.py", lines={2})
|
|
11
|
+
|
|
12
|
+
operators = sorted(m["operator"] for m in mutants)
|
|
13
|
+
self.assertEqual(operators, ["0 -> 1", "> -> >=", "return -> None"])
|
|
14
|
+
self.assertTrue(all(m["line"] == 2 for m in mutants))
|
|
15
|
+
self.assertTrue(any("n >= 0" in m["mutatedSource"] for m in mutants))
|
|
16
|
+
self.assertTrue(any("return None" in m["mutatedSource"] for m in mutants))
|
|
17
|
+
|
|
18
|
+
def test_logical_and_arithmetic(self):
|
|
19
|
+
source = (
|
|
20
|
+
"def calc(a, b):\n"
|
|
21
|
+
" if a > 0 and b > 0:\n"
|
|
22
|
+
" return a + b\n"
|
|
23
|
+
" return a * b\n"
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
mutants = mutate_source(source, filename="calc.py", lines={2, 3})
|
|
27
|
+
operators = [m["operator"] for m in mutants]
|
|
28
|
+
|
|
29
|
+
self.assertIn("and -> or", operators)
|
|
30
|
+
self.assertIn("+ -> -", operators)
|
|
31
|
+
self.assertTrue(all(m["line"] in {2, 3} for m in mutants))
|
|
32
|
+
|
|
33
|
+
def test_literals_and_negation(self):
|
|
34
|
+
source = (
|
|
35
|
+
"def label(flag):\n"
|
|
36
|
+
" if flag:\n"
|
|
37
|
+
" return 'yes' if True else 'no'\n"
|
|
38
|
+
)
|
|
39
|
+
|
|
40
|
+
mutants = mutate_source(source, filename="label.py")
|
|
41
|
+
operators = [m["operator"] for m in mutants]
|
|
42
|
+
|
|
43
|
+
self.assertTrue(any(op.startswith("string ") for op in operators))
|
|
44
|
+
self.assertIn("True -> False", operators)
|
|
45
|
+
self.assertIn("condition -> negated", operators)
|
|
46
|
+
|
|
47
|
+
def test_ignore_marker(self):
|
|
48
|
+
source = "def f(n):\n # lie-detector-ignore\n return n > 0\n"
|
|
49
|
+
|
|
50
|
+
mutants = mutate_source(source, filename="f.py", lines={3})
|
|
51
|
+
|
|
52
|
+
self.assertTrue(all(m["line"] != 3 for m in mutants))
|
|
53
|
+
|
|
54
|
+
def test_does_not_mutate_import_paths(self):
|
|
55
|
+
source = "import os\nfrom x import y\n\ndef f():\n return 1\n"
|
|
56
|
+
|
|
57
|
+
mutants = mutate_source(source, filename="f.py", lines={1, 2})
|
|
58
|
+
|
|
59
|
+
self.assertEqual(mutants, [])
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
if __name__ == "__main__":
|
|
63
|
+
unittest.main()
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import unittest
|
|
2
|
+
|
|
3
|
+
from scripts.py.quick import quick_scan
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class QuickScanTests(unittest.TestCase):
|
|
7
|
+
def test_catches_tautology_and_no_assertion(self):
|
|
8
|
+
source = (
|
|
9
|
+
"def test_tautology():\n"
|
|
10
|
+
" assert True\n"
|
|
11
|
+
"\n"
|
|
12
|
+
"def test_no_assertion():\n"
|
|
13
|
+
" add(1, 2)\n"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
findings = quick_scan(source, filename="test_quick.py")
|
|
17
|
+
patterns = {finding["pattern"] for finding in findings}
|
|
18
|
+
|
|
19
|
+
self.assertEqual(patterns, {"tautology", "no-assertion"})
|
|
20
|
+
|
|
21
|
+
def test_good_tests_are_not_flagged(self):
|
|
22
|
+
source = (
|
|
23
|
+
"def test_add():\n"
|
|
24
|
+
" assert add(2, 3) == 5\n"
|
|
25
|
+
"\n"
|
|
26
|
+
"def test_raises():\n"
|
|
27
|
+
" with pytest.raises(ValueError):\n"
|
|
28
|
+
" fail()\n"
|
|
29
|
+
"\n"
|
|
30
|
+
"def test_multiple():\n"
|
|
31
|
+
" assert x == 1\n"
|
|
32
|
+
" assert y == 2\n"
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
self.assertEqual(quick_scan(source, filename="test_good.py"), [])
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == "__main__":
|
|
39
|
+
unittest.main()
|