caught 0.3.0__py3-none-any.whl

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.
caught/checks.py ADDED
@@ -0,0 +1,700 @@
1
+ """Static checks that compare test, config and source files before and after a session.
2
+
3
+ Every check takes two snapshots, ``before`` and ``after``, each mapping a repo-relative POSIX path
4
+ to the file's text. A path missing from a snapshot means the file did not exist then.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ import configparser
11
+ import copy
12
+ import difflib
13
+ import re
14
+ import tomllib
15
+ from collections import Counter
16
+ from collections.abc import Iterator, Mapping
17
+ from dataclasses import dataclass
18
+ from fnmatch import fnmatch
19
+ from pathlib import PurePosixPath
20
+
21
+ Snapshot = Mapping[str, str]
22
+
23
+ CONFIG_FILES = {
24
+ "pytest.ini",
25
+ "pytest.toml",
26
+ ".pytest.toml",
27
+ "tox.ini",
28
+ "setup.cfg",
29
+ "pyproject.toml",
30
+ }
31
+ INI_SECTIONS = {"pytest.ini": "pytest", "tox.ini": "pytest", "setup.cfg": "tool:pytest"}
32
+
33
+ # Order in which findings lead the one-line reason.
34
+ PRIORITY = [
35
+ "assertion",
36
+ "skip",
37
+ "outcome_hook",
38
+ "masking",
39
+ "test_env",
40
+ "special_case",
41
+ "test_edit",
42
+ "config",
43
+ "rerun",
44
+ "regression",
45
+ ]
46
+ # Text files that run tests, where a masked exit code hides failures.
47
+ COMMAND_FILES = {"Makefile", "makefile", "GNUmakefile", "justfile", "tox.ini"}
48
+ COMMAND_SUFFIXES = {".sh", ".bash", ".mk", ".yml", ".yaml", ".toml", ".cfg", ".json", ".ps1"}
49
+
50
+
51
+ @dataclass(frozen=True)
52
+ class Finding:
53
+ check: str
54
+ path: str
55
+ line: int | None
56
+ message: str
57
+
58
+
59
+ def is_test_module(path: str) -> bool:
60
+ """A file pytest collects by default."""
61
+ name = PurePosixPath(path).name
62
+ return fnmatch(name, "test_*.py") or fnmatch(name, "*_test.py")
63
+
64
+
65
+ def is_test_file(path: str) -> bool:
66
+ """A test module, or a helper module that lives in a tests directory."""
67
+ p = PurePosixPath(path)
68
+ if p.suffix != ".py" or p.name == "conftest.py":
69
+ return False
70
+ return is_test_module(path) or any(part in ("test", "tests") for part in p.parts[:-1])
71
+
72
+
73
+ def is_config_file(path: str) -> bool:
74
+ name = PurePosixPath(path).name
75
+ return name == "conftest.py" or name in CONFIG_FILES
76
+
77
+
78
+ def is_command_file(path: str) -> bool:
79
+ p = PurePosixPath(path)
80
+ return p.name in COMMAND_FILES or p.suffix in COMMAND_SUFFIXES
81
+
82
+
83
+ def run_checks(before: Snapshot, after: Snapshot) -> list[Finding]:
84
+ findings: list[Finding] = []
85
+ for path in sorted(set(before) | set(after)):
86
+ old, new = before.get(path), after.get(path)
87
+ if old == new:
88
+ continue
89
+ if is_config_file(path):
90
+ findings += check_config(path, old, new)
91
+ elif is_test_file(path):
92
+ findings += check_test_file(path, old, new)
93
+ if path.endswith(".py") and new is not None:
94
+ findings += check_source(path, old, new)
95
+ elif is_command_file(path) and new is not None:
96
+ findings += check_masking(path, old or "", new)
97
+ findings += check_special_cases(before, after)
98
+ return findings
99
+
100
+
101
+ # Check 4: conftest.py and pytest options.
102
+
103
+
104
+ def _pytest_options(path: str, text: str) -> object:
105
+ name = PurePosixPath(path).name
106
+ try:
107
+ if name == "pyproject.toml":
108
+ data = tomllib.loads(text)
109
+ plugins = data.get("project", {}).get("entry-points", {}).get("pytest11")
110
+ return {"options": data.get("tool", {}).get("pytest"), "plugins": plugins}
111
+ if name in INI_SECTIONS:
112
+ parser = configparser.ConfigParser(interpolation=None)
113
+ parser.read_string(text)
114
+ section = INI_SECTIONS[name]
115
+ return dict(parser[section]) if parser.has_section(section) else None
116
+ except (tomllib.TOMLDecodeError, configparser.Error):
117
+ pass # An unparsable config still counts as changed if its text changed.
118
+ return text
119
+
120
+
121
+ def check_config(path: str, old: str | None, new: str | None) -> list[Finding]:
122
+ if PurePosixPath(path).name == "conftest.py":
123
+ verb = "added" if old is None else "deleted" if new is None else "changed"
124
+ return [Finding("config", path, None, f"{path} was {verb}")]
125
+ old_opts = None if old is None else _pytest_options(path, old)
126
+ new_opts = None if new is None else _pytest_options(path, new)
127
+ if old_opts == new_opts:
128
+ return []
129
+ return [Finding("config", path, None, f"the pytest options in {path} changed")]
130
+
131
+
132
+ # Checks 1-3: edits to existing tests.
133
+
134
+
135
+ def _parse(text: str | None) -> ast.Module | None:
136
+ if text is None:
137
+ return None
138
+ try:
139
+ return ast.parse(text)
140
+ except (SyntaxError, RecursionError): # RecursionError: nesting deeper than the parser allows
141
+ return None
142
+
143
+
144
+ def _dotted(node: ast.AST) -> str:
145
+ """`a.b.c` for a name, attribute or call chain; `.b.c` when the chain starts elsewhere."""
146
+ parts = []
147
+ while True: # a loop, not recursion: a chain can be thousands of links long
148
+ if isinstance(node, ast.Call):
149
+ node = node.func
150
+ elif isinstance(node, ast.Attribute):
151
+ parts.append(node.attr)
152
+ node = node.value
153
+ else:
154
+ break
155
+ head = node.id if isinstance(node, ast.Name) else ""
156
+ return head + "".join(f".{part}" for part in reversed(parts))
157
+
158
+
159
+ def _items(tree: ast.Module) -> dict[str, ast.stmt]:
160
+ """Top-level functions, class methods, class headers and other statements, keyed for diffing.
161
+
162
+ Imports are left out: adding or dropping one is not a change to what a test checks.
163
+ """
164
+ items: dict[str, ast.stmt] = {}
165
+ for node in tree.body:
166
+ if isinstance(node, ast.Import | ast.ImportFrom):
167
+ continue
168
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef):
169
+ items[node.name] = node
170
+ elif isinstance(node, ast.ClassDef):
171
+ header = copy.copy(node)
172
+ header.body = [
173
+ s for s in node.body if not isinstance(s, ast.FunctionDef | ast.AsyncFunctionDef)
174
+ ]
175
+ items[f"class {node.name}"] = header
176
+ for sub in node.body:
177
+ if isinstance(sub, ast.FunctionDef | ast.AsyncFunctionDef):
178
+ items[f"{node.name}.{sub.name}"] = sub
179
+ else:
180
+ items[f"statement {ast.dump(node)}"] = node
181
+ return items
182
+
183
+
184
+ def _asserts(fn: ast.AST) -> list[ast.Assert | ast.Call]:
185
+ nodes: list[ast.Assert | ast.Call] = []
186
+ for n in ast.walk(fn):
187
+ if isinstance(n, ast.Assert) or (
188
+ isinstance(n, ast.Call) and _dotted(n.func).rsplit(".", 1)[-1].startswith("assert")
189
+ ):
190
+ nodes.append(n)
191
+ return sorted(nodes, key=lambda n: (n.lineno, n.col_offset))
192
+
193
+
194
+ class _BlankConstants(ast.NodeTransformer):
195
+ def visit_Constant(self, node: ast.Constant) -> ast.Constant:
196
+ return ast.Constant(value=None)
197
+
198
+
199
+ def _shape(node: ast.AST) -> str:
200
+ return ast.dump(_BlankConstants().visit(copy.deepcopy(node)))
201
+
202
+
203
+ def _code(node: ast.AST) -> str:
204
+ """One line of source for a node, short enough for a block reason."""
205
+ text = " ".join(ast.unparse(node).split())
206
+ return text if len(text) <= 80 else text[:77] + "..."
207
+
208
+
209
+ def _assertion_changes(path: str, name: str, old: ast.stmt, new: ast.stmt) -> list[Finding]:
210
+ old_asserts, new_asserts = _asserts(old), _asserts(new)
211
+ matcher = difflib.SequenceMatcher(
212
+ a=[ast.dump(n) for n in old_asserts], b=[ast.dump(n) for n in new_asserts], autojunk=False
213
+ )
214
+ findings = []
215
+ for op, i1, i2, j1, j2 in matcher.get_opcodes():
216
+ if op in ("equal", "insert"):
217
+ continue
218
+ removed = old_asserts[i1:i2]
219
+ if op == "replace":
220
+ for a, b in zip(removed, new_asserts[j1:j2], strict=False):
221
+ what = "expected value" if _shape(a) == _shape(b) else "assertion"
222
+ message = (
223
+ f"the {what} in {path} line {b.lineno} changed from `{_code(a)}` "
224
+ f"to `{_code(b)}`"
225
+ )
226
+ findings.append(Finding("assertion", path, b.lineno, message))
227
+ removed = removed[j2 - j1 :]
228
+ for a in removed:
229
+ findings.append(
230
+ Finding(
231
+ "assertion",
232
+ path,
233
+ a.lineno,
234
+ f"{name} in {path} lost `{_code(a)}` (line {a.lineno} before)",
235
+ )
236
+ )
237
+ return findings
238
+
239
+
240
+ def _is_skip_name(name: str) -> str | None:
241
+ last = name.rsplit(".", 1)[-1]
242
+ if last in ("skip", "skipif", "skipIf", "skipUnless", "skipTest", "importorskip", "SkipTest"):
243
+ return "skip"
244
+ if last in ("xfail", "expectedFailure"):
245
+ return "xfail"
246
+ return None
247
+
248
+
249
+ def _contains_assert(nodes: list[ast.stmt]) -> bool:
250
+ return any(_asserts(n) for n in nodes)
251
+
252
+
253
+ def _evasions(fn: ast.FunctionDef | ast.AsyncFunctionDef) -> Iterator[tuple[str, int]]:
254
+ """Ways a test stops testing: skip or xfail, emptied body, early return, swallowed asserts."""
255
+ for deco in fn.decorator_list:
256
+ kind = _is_skip_name(_dotted(deco))
257
+ if kind:
258
+ yield kind, deco.lineno
259
+ for node in ast.walk(fn):
260
+ if isinstance(node, ast.Call) and node not in fn.decorator_list:
261
+ kind = _is_skip_name(_dotted(node.func))
262
+ if kind:
263
+ yield kind, node.lineno
264
+ if isinstance(node, ast.Raise) and node.exc and not isinstance(node.exc, ast.Call):
265
+ kind = _is_skip_name(_dotted(node.exc))
266
+ if kind:
267
+ yield kind, node.lineno
268
+ if isinstance(node, ast.Try) and node.handlers and _contains_assert(node.body):
269
+ yield "try", node.lineno
270
+ body = fn.body
271
+ if body and isinstance(body[0], ast.Expr) and isinstance(body[0].value, ast.Constant):
272
+ body = body[1:] # docstring
273
+ if all(
274
+ isinstance(s, ast.Pass)
275
+ or (isinstance(s, ast.Expr) and isinstance(s.value, ast.Constant) and s.value.value is ...)
276
+ for s in body
277
+ ):
278
+ yield "empty", fn.lineno
279
+ elif isinstance(body[0], ast.Return):
280
+ yield "return", body[0].lineno
281
+
282
+
283
+ def _evasion_message(kind: str, name: str, path: str, line: int) -> str:
284
+ return {
285
+ "skip": f"a skip was added to {name} in {path} line {line}",
286
+ "xfail": f"an xfail was added to {name} in {path} line {line}",
287
+ "try": f"an assert in {path} line {line} is now wrapped in try/except",
288
+ "empty": f"{name} in {path} line {line} was emptied to pass",
289
+ "return": f"{name} in {path} line {line} now returns before its assertions",
290
+ }[kind]
291
+
292
+
293
+ def _skip_names(node: ast.AST) -> list[str]:
294
+ return [
295
+ k for n in ast.walk(node) if isinstance(n, ast.Attribute) and (k := _is_skip_name(n.attr))
296
+ ]
297
+
298
+
299
+ def _added_evasions(path: str, name: str, old: ast.stmt | None, new: ast.stmt) -> list[Finding]:
300
+ if isinstance(new, ast.FunctionDef | ast.AsyncFunctionDef):
301
+ old_list = (
302
+ list(_evasions(old)) if isinstance(old, ast.FunctionDef | ast.AsyncFunctionDef) else []
303
+ )
304
+ new_list = list(_evasions(new))
305
+ else: # class headers and module statements, such as `pytestmark = pytest.mark.skip`
306
+ old_list = [(k, 0) for k in _skip_names(old)] if old is not None else []
307
+ new_list = [(k, new.lineno) for k in _skip_names(new)]
308
+ extra = Counter(k for k, _ in new_list) - Counter(k for k, _ in old_list)
309
+ findings = []
310
+ for kind, count in extra.items():
311
+ lines = [line for k, line in new_list if k == kind][-count:]
312
+ line = lines[0]
313
+ findings.append(Finding("skip", path, line, _evasion_message(kind, name, path, line)))
314
+ return findings
315
+
316
+
317
+ def _only_additions(old: ast.stmt, new: ast.stmt) -> bool:
318
+ """True when `new` is `old` with statements added to its body, such as extra assertions."""
319
+ functions = ast.FunctionDef | ast.AsyncFunctionDef
320
+ if not isinstance(old, functions) or not isinstance(new, functions):
321
+ return False
322
+ if type(old) is not type(new):
323
+ return False
324
+ old_header, new_header = copy.copy(old), copy.copy(new)
325
+ old_header.body = new_header.body = []
326
+ if ast.dump(old_header) != ast.dump(new_header):
327
+ return False
328
+ matcher = difflib.SequenceMatcher(
329
+ a=[ast.dump(s) for s in old.body], b=[ast.dump(s) for s in new.body], autojunk=False
330
+ )
331
+ return all(op in ("equal", "insert") for op, *_ in matcher.get_opcodes())
332
+
333
+
334
+ ASSERT_LINE = re.compile(r"(assert\b|self\.assert\w*\()")
335
+
336
+
337
+ def _line_changes(path: str, old: str, new: str) -> list[Finding]:
338
+ """Changed or removed lines of a test file that does not parse before or after the change."""
339
+ old_lines, new_lines = old.splitlines(), new.splitlines()
340
+ matcher = difflib.SequenceMatcher(a=old_lines, b=new_lines, autojunk=False)
341
+ findings = []
342
+ for op, i1, i2, j1, j2 in matcher.get_opcodes():
343
+ if op in ("equal", "insert"):
344
+ continue
345
+ for k, line in enumerate(old_lines[i1:i2]):
346
+ before = " ".join(line.split())[:80]
347
+ replaced = op == "replace" and j1 + k < j2
348
+ after = " ".join(new_lines[j1 + k].split())[:80] if replaced else ""
349
+ if replaced and (ASSERT_LINE.match(before) or ASSERT_LINE.match(after)):
350
+ line_no = j1 + k + 1
351
+ message = (
352
+ f"the assertion in {path} line {line_no} changed from `{before}` to `{after}`"
353
+ )
354
+ findings.append(Finding("assertion", path, line_no, message))
355
+ elif ASSERT_LINE.match(before):
356
+ message = f"{path} lost `{before}` (line {i1 + k + 1} before)"
357
+ findings.append(Finding("assertion", path, i1 + k + 1, message))
358
+ else:
359
+ line_no = j1 + k + 1 if replaced else i1 + k + 1
360
+ findings.append(
361
+ Finding("test_edit", path, line_no, f"{path} line {line_no} was edited")
362
+ )
363
+ return findings
364
+
365
+
366
+ def check_test_file(path: str, old: str | None, new: str | None) -> list[Finding]:
367
+ if old is None:
368
+ return [] # a new test file only adds tests
369
+ if new is None:
370
+ return [Finding("test_edit", path, None, f"{path} was deleted")]
371
+ old_tree, new_tree = _parse(old), _parse(new)
372
+ if old_tree is None or new_tree is None:
373
+ return _line_changes(path, old, new)
374
+ old_items, new_items = _items(old_tree), _items(new_tree)
375
+ findings: list[Finding] = []
376
+ for key, new_node in new_items.items():
377
+ old_node = old_items.get(key)
378
+ if old_node is not None and ast.dump(old_node) == ast.dump(new_node):
379
+ continue
380
+ if old_node is None and not key.startswith("statement "):
381
+ continue # a new test or test class
382
+ specific = _added_evasions(path, key, old_node, new_node)
383
+ if old_node is not None:
384
+ specific += _assertion_changes(path, key, old_node, new_node)
385
+ if not specific and not _only_additions(old_node, new_node):
386
+ specific = [
387
+ Finding(
388
+ "test_edit",
389
+ path,
390
+ new_node.lineno,
391
+ f"{key} in {path} line {new_node.lineno} was edited",
392
+ )
393
+ ]
394
+ findings += specific
395
+ for key, old_node in old_items.items():
396
+ if key in new_items:
397
+ continue
398
+ if key.startswith("statement "):
399
+ message = f"the statement at {path} line {old_node.lineno} was changed or removed"
400
+ else:
401
+ message = f"{key} was removed from {path}"
402
+ findings.append(Finding("test_edit", path, old_node.lineno, message))
403
+ return findings
404
+
405
+
406
+ # Check 5: literals copied from tests into new source branches.
407
+
408
+ # Statements in a branch body, at any depth, that hand back a value: a hard-coded answer.
409
+ _OUTPUTS = (ast.Return, ast.Assign, ast.AugAssign, ast.AnnAssign, ast.Expr, ast.Raise)
410
+ # String methods a branch can use to pick out a test input by a feature of it.
411
+ STRING_TESTS = {"startswith", "endswith", "find", "index", "count", "match", "fullmatch", "search"}
412
+ _LITERAL_NODES = (ast.Constant, ast.Tuple, ast.List, ast.Set, ast.Dict, ast.UnaryOp)
413
+
414
+
415
+ def _literal(node: ast.AST) -> str | None:
416
+ if not isinstance(node, _LITERAL_NODES):
417
+ return None
418
+ try:
419
+ return repr(ast.literal_eval(node))
420
+ except (ValueError, TypeError, SyntaxError, MemoryError, RecursionError):
421
+ return None
422
+
423
+
424
+ def _is_trivial(node: ast.AST) -> bool:
425
+ value = ast.literal_eval(node)
426
+ if value is None or isinstance(value, bool):
427
+ return True
428
+ if isinstance(value, int | float):
429
+ return -1 <= value <= 2
430
+ if isinstance(value, str):
431
+ return len(value) <= 1 # a one-character string is as common as a small number
432
+ return len(value) == 0 if hasattr(value, "__len__") else False
433
+
434
+
435
+ def _literals(node: ast.AST) -> set[str]:
436
+ return {lit for n in ast.walk(node) if (lit := _literal(n)) is not None}
437
+
438
+
439
+ def _test_groups(snapshot: Snapshot) -> Iterator[tuple[str, str, set[str]]]:
440
+ """Literals used together in each test function (or `check` function) of each test module."""
441
+ for path, text in snapshot.items():
442
+ tree = _parse(text) if is_test_file(path) else None
443
+ if tree is None:
444
+ continue
445
+ for node in ast.walk(tree):
446
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef) and (
447
+ node.name.startswith("test") or node.name == "check"
448
+ ):
449
+ yield path, node.name, _literals(node)
450
+
451
+
452
+ def _bound_literals(tree: ast.Module) -> dict[str, ast.expr]:
453
+ """Names assigned a literal anywhere in the module, such as `known = {(1, 2), (3, 4)}`."""
454
+ return {
455
+ target.id: node.value
456
+ for node in ast.walk(tree)
457
+ if isinstance(node, ast.Assign) and _literal(node.value) is not None
458
+ for target in node.targets
459
+ if isinstance(target, ast.Name)
460
+ }
461
+
462
+
463
+ def _branch_conditions(
464
+ tree: ast.Module,
465
+ ) -> Iterator[tuple[ast.AST, ast.expr, list[ast.stmt], int]]:
466
+ """(key node, condition literal, branch body, line) for each equality branch in a file."""
467
+ bound = _bound_literals(tree)
468
+ for n in ast.walk(tree):
469
+ if isinstance(n, ast.If | ast.IfExp):
470
+ body: list[ast.stmt] = n.body if isinstance(n, ast.If) else [ast.Expr(n.body)]
471
+ for cmp in ast.walk(n.test):
472
+ operands: list[ast.expr]
473
+ if isinstance(cmp, ast.Compare) and all(
474
+ isinstance(op, ast.Eq | ast.Is | ast.In) for op in cmp.ops
475
+ ):
476
+ operands = [cmp.left, *cmp.comparators]
477
+ elif (
478
+ isinstance(cmp, ast.Call)
479
+ and isinstance(cmp.func, ast.Attribute)
480
+ and cmp.func.attr in STRING_TESTS
481
+ ):
482
+ operands = cmp.args # a feature of the input, like text.endswith("''")
483
+ else:
484
+ continue
485
+ for operand in operands:
486
+ if isinstance(operand, ast.Name):
487
+ operand = bound.get(operand.id, operand)
488
+ if _literal(operand) is None:
489
+ continue
490
+ # The literal and every constant in it, so a set of test-input tuples counts.
491
+ constants = [c for c in ast.walk(operand) if isinstance(c, ast.Constant)]
492
+ for lit in [operand, *constants]:
493
+ yield n.test, lit, body, cmp.lineno
494
+ elif (
495
+ isinstance(n, ast.match_case)
496
+ and isinstance(n.pattern, ast.MatchValue)
497
+ and _literal(n.pattern.value) is not None # not a name, like `case Color.RED:`
498
+ ):
499
+ yield n.pattern, n.pattern.value, n.body, n.pattern.lineno
500
+
501
+
502
+ def check_special_cases(before: Snapshot, after: Snapshot) -> list[Finding]:
503
+ groups = list(_test_groups(after)) + list(_test_groups(before))
504
+ findings = []
505
+ for path in sorted(after):
506
+ if not path.endswith(".py") or is_test_file(path) or is_config_file(path):
507
+ continue
508
+ if before.get(path) == after[path]:
509
+ continue
510
+ new_tree = _parse(after[path])
511
+ if new_tree is None:
512
+ continue
513
+ old_tree = _parse(before.get(path))
514
+ seen = {ast.dump(k) for k, *_ in _branch_conditions(old_tree)} if old_tree else set()
515
+ flagged: set[int] = set()
516
+ for key, lit_node, body, line in _branch_conditions(new_tree):
517
+ if line in flagged or ast.dump(key) in seen or _is_trivial(lit_node):
518
+ continue
519
+ condition = _literal(lit_node)
520
+ outputs = [n for s in body for n in ast.walk(s) if isinstance(n, _OUTPUTS)]
521
+ returned = set().union(*map(_literals, outputs)) - {condition}
522
+ for test_path, test_name, literals in groups:
523
+ if condition in literals and returned & literals:
524
+ shown = condition if len(condition) <= 30 else condition[:27] + "..."
525
+ findings.append(
526
+ Finding(
527
+ "special_case",
528
+ path,
529
+ line,
530
+ f"{path} line {line} special-cases {shown}, "
531
+ f"an input from {test_path}::{test_name}",
532
+ )
533
+ )
534
+ flagged.add(line)
535
+ break
536
+ return findings
537
+
538
+
539
+ # Checks 6-8: source that detects tests, outcome-rewriting hooks and masked test commands. Each
540
+ # counts occurrences before and after and reports the ones the change added.
541
+
542
+ TEST_MODULES = {"pytest", "_pytest", "unittest"}
543
+ PYTEST_VAR = re.compile(r"PYTEST_[A-Z_]+")
544
+ ENVIRON = {"os.environ", "environ"}
545
+ ENV_READS = {"os.environ.get", "os.getenv", "environ.get", "getenv"}
546
+ # Hooks that can change a test's result, or which tests run, after the fact.
547
+ OUTCOME_HOOKS = {
548
+ "pytest_runtest_makereport",
549
+ "pytest_report_teststatus",
550
+ "pytest_runtest_logreport",
551
+ "pytest_runtest_call",
552
+ "pytest_runtest_protocol",
553
+ "pytest_pyfunc_call",
554
+ "pytest_collection_modifyitems",
555
+ "pytest_deselected",
556
+ "pytest_sessionfinish",
557
+ "pytest_runtest_setup",
558
+ "pytest_ignore_collect",
559
+ "pytest_collect_file",
560
+ "pytest_unconfigure",
561
+ }
562
+ TOOLING = {"setup.py", "noxfile.py", "conftest.py"}
563
+ # A test runner in command position: `pytest`, `python -m pytest`, `tox`, `make test` and so on,
564
+ # but not `pytest-cov` or `pip install tox`.
565
+ RUNNER = re.compile(
566
+ r"(?:^|[\s;&|(-])(?:python3?\s+-m\s+)?(?:py\.?test|unittest|tox|nox)(?=\s|$)"
567
+ r"|\bmake\s+test\b|\b(?:npm|yarn|pnpm)\s+(?:run\s+)?test\b|\bgo\s+test\b|\bcargo\s+test\b"
568
+ )
569
+ NOT_A_RUN = re.compile(r"\b(?:install|uninstall|kill|pkill)\b")
570
+ MASK = re.compile(r"\|\|\s*(?:true|:|exit\s+0|echo)\b|;\s*(?:true|exit\s+0|echo)\b|\|\s*tee\b")
571
+ MAKE_IGNORE = re.compile(r"^\t-") # a Makefile recipe line whose failure make ignores
572
+ TOX_IGNORE = re.compile(r"^\s*ignore_outcome\s*=\s*true\b", re.I)
573
+
574
+
575
+ def _strings(node: ast.AST) -> list[str]:
576
+ return [
577
+ n.value for n in ast.walk(node) if isinstance(n, ast.Constant) and isinstance(n.value, str)
578
+ ]
579
+
580
+
581
+ def _test_env(tree: ast.Module) -> set[tuple[str, int]]:
582
+ """(label, line) for each place the code asks whether it is running under pytest or unittest.
583
+
584
+ Only strong signals: a test module looked up in sys.modules, a PYTEST_* environment variable
585
+ read, a test runner named in sys.argv. A project's own TESTING setting is not one of them.
586
+ """
587
+ found = set()
588
+ for node in ast.walk(tree):
589
+ if isinstance(node, ast.Compare):
590
+ operands = {_dotted(o) for o in [node.left, *node.comparators]}
591
+ strings = set(_strings(node))
592
+ if "sys.modules" in operands and TEST_MODULES & strings:
593
+ found.add(("a test module in sys.modules", node.lineno))
594
+ for name in sorted(t for t in strings if PYTEST_VAR.fullmatch(t)):
595
+ if operands & ENVIRON:
596
+ found.add((f"the {name} environment variable", node.lineno))
597
+ key: ast.expr | None = None
598
+ if isinstance(node, ast.Call) and node.args:
599
+ if _dotted(node.func) == "sys.modules.get":
600
+ if isinstance(node.args[0], ast.Constant) and node.args[0].value in TEST_MODULES:
601
+ found.add(("a test module in sys.modules", node.lineno))
602
+ elif _dotted(node.func) in ENV_READS:
603
+ key = node.args[0]
604
+ if isinstance(node, ast.Subscript) and _dotted(node.value) in ENVIRON:
605
+ key = node.slice
606
+ if (
607
+ isinstance(key, ast.Constant)
608
+ and isinstance(key.value, str)
609
+ and PYTEST_VAR.fullmatch(key.value)
610
+ ):
611
+ found.add((f"the {key.value} environment variable", key.lineno))
612
+ argv = {
613
+ n.lineno
614
+ for n in ast.walk(tree)
615
+ if isinstance(n, ast.Attribute) and _dotted(n) == "sys.argv"
616
+ }
617
+ runner = {
618
+ n.lineno
619
+ for n in ast.walk(tree)
620
+ if isinstance(n, ast.Constant)
621
+ and isinstance(n.value, str)
622
+ and re.search(r"py\.?test|unittest", n.value)
623
+ }
624
+ found |= {("a test runner in sys.argv", line) for line in argv & runner}
625
+ return found
626
+
627
+
628
+ def _outcome_hooks(tree: ast.Module) -> set[tuple[str, int]]:
629
+ """Hook functions defined, or bound by assignment such as `pytest_runtest_call = _run`."""
630
+ found = set()
631
+ for n in ast.walk(tree):
632
+ if isinstance(n, ast.FunctionDef | ast.AsyncFunctionDef) and n.name in OUTCOME_HOOKS:
633
+ found.add((n.name, n.lineno))
634
+ if isinstance(n, ast.Assign):
635
+ for target in n.targets:
636
+ if isinstance(target, ast.Name) and target.id in OUTCOME_HOOKS:
637
+ found.add((target.id, n.lineno))
638
+ return found
639
+
640
+
641
+ def _added(old: set[tuple[str, int]], new: set[tuple[str, int]]) -> list[tuple[str, int]]:
642
+ """The (label, line) occurrences in `new` beyond those `old` already had, per label."""
643
+ extra = Counter(label for label, _ in new) - Counter(label for label, _ in old)
644
+ return [
645
+ (label, sorted(line for other, line in new if other == label)[-count])
646
+ for label, count in sorted(extra.items())
647
+ ]
648
+
649
+
650
+ def check_source(path: str, old: str | None, new: str) -> list[Finding]:
651
+ new_tree = _parse(new)
652
+ if new_tree is None:
653
+ return []
654
+ old_tree = _parse(old) or ast.Module(body=[], type_ignores=[])
655
+ if is_test_file(path):
656
+ return [] # pytest loads no hooks from test modules, and the test checks cover them
657
+ findings = [
658
+ Finding(
659
+ "outcome_hook",
660
+ path,
661
+ line,
662
+ f"{path} line {line} defines {name}, a pytest hook that can rewrite test outcomes",
663
+ )
664
+ for name, line in _added(_outcome_hooks(old_tree), _outcome_hooks(new_tree))
665
+ ]
666
+ if PurePosixPath(path).name in TOOLING:
667
+ return findings
668
+ for label, line in _added(_test_env(old_tree), _test_env(new_tree)):
669
+ message = f"{path} line {line} checks whether it is under test ({label})"
670
+ findings.append(Finding("test_env", path, line, message))
671
+ return findings
672
+
673
+
674
+ def _masked(path: str, text: str) -> list[tuple[int, str]]:
675
+ """(line number, line) for each line that runs tests but throws away their exit code."""
676
+ name = PurePosixPath(path).name
677
+ makefile = name in COMMAND_FILES - {"tox.ini"} or name.endswith(".mk")
678
+ found = []
679
+ for number, line in enumerate(text.splitlines(), 1):
680
+ runs_tests = RUNNER.search(line) and not NOT_A_RUN.search(line)
681
+ masked = MASK.search(line) or (makefile and MAKE_IGNORE.match(line))
682
+ if (runs_tests and masked) or (name == "tox.ini" and TOX_IGNORE.match(line)):
683
+ found.append((number, line.strip()))
684
+ return found
685
+
686
+
687
+ def check_masking(path: str, old: str, new: str) -> list[Finding]:
688
+ """Masked test commands the change added, like `pytest || true` or tox's ignore_outcome."""
689
+ before, after = _masked(path, old), _masked(path, new)
690
+ seen = {line for _, line in before}
691
+ added = [(n, line) for n, line in after if line not in seen][: max(0, len(after) - len(before))]
692
+ return [
693
+ Finding(
694
+ "masking",
695
+ path,
696
+ number,
697
+ f"{path} line {number} hides the exit code of a test command: `{line}`",
698
+ )
699
+ for number, line in added
700
+ ]