snitch-engine 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.
engine/astdiff/diff.py ADDED
@@ -0,0 +1,827 @@
1
+ import ast
2
+ import configparser
3
+ import textwrap
4
+ import tomllib
5
+ from collections.abc import Iterator
6
+ from datetime import UTC, datetime
7
+ from fnmatch import fnmatch
8
+ from pathlib import Path
9
+ from typing import Literal
10
+
11
+ import tree_sitter_python
12
+ from tree_sitter import Language, Node, Parser
13
+
14
+ from engine.models import SnitchEvent, new_event
15
+
16
+ PARSER = Parser(Language(tree_sitter_python.language()))
17
+ LITERALS = {"integer", "float", "string", "true", "false", "none"}
18
+ SKIP_CALLS = {"pytest.skip", "pytest.xfail", "skip", "xfail", "self.skipTest"}
19
+ # random.seed, np.random.seed, torch.manual_seed, tf.random.set_seed, ...
20
+ SEED_NAMES = {"seed", "manual_seed", "set_seed"}
21
+ APPROX_CALLS = {"pytest.approx", "approx"}
22
+ UNITTEST_EQUAL = {"self.assertEqual", "self.assertEquals"}
23
+ # an exact assertEqual replaced by one of these checks less
24
+ UNITTEST_WEAK = {
25
+ "self.assertIn",
26
+ "self.assertIsNotNone",
27
+ "self.assertIsInstance",
28
+ "self.assertGreater",
29
+ "self.assertGreaterEqual",
30
+ "self.assertLess",
31
+ "self.assertLessEqual",
32
+ }
33
+ UNITTEST_ALMOST = {"self.assertAlmostEqual", "self.assertAlmostEquals"}
34
+ UNITTEST_BOUNDS = {
35
+ "self.assertLess": "<",
36
+ "self.assertLessEqual": "<=",
37
+ "self.assertGreater": ">",
38
+ "self.assertGreaterEqual": ">=",
39
+ }
40
+ # pytest.approx defaults, used when the `before` side gives no explicit tolerance
41
+ APPROX_DEFAULTS = {"rel": 1e-6, "abs": 1e-12}
42
+
43
+
44
+ def _text(node: Node) -> str:
45
+ """Source of `node`, with the continuation lines of a block dedented."""
46
+ raw = (node.text or b"").decode()
47
+ return textwrap.dedent(" " * node.start_point.column + raw)
48
+
49
+
50
+ def _walk(node: Node) -> Iterator[Node]:
51
+ yield node
52
+ for child in node.children:
53
+ yield from _walk(child)
54
+
55
+
56
+ DEFAULT_TEST_FILES = ("test_*.py", "*_test.py")
57
+
58
+
59
+ def _python_files(repo: Path) -> tuple[str, ...]:
60
+ """pytest's `python_files` from the repo's root config, found in pytest's order."""
61
+ # shortcut: root config only and basename patterns; python_functions not read
62
+ for name, section in (
63
+ ("pytest.ini", "pytest"),
64
+ ("pyproject.toml", None),
65
+ ("tox.ini", "pytest"),
66
+ ("setup.cfg", "tool:pytest"),
67
+ ):
68
+ path = repo / name
69
+ if not path.is_file():
70
+ continue
71
+ try:
72
+ if section is None:
73
+ options = tomllib.loads(path.read_text())
74
+ found = options.get("tool", {}).get("pytest", {}).get("ini_options")
75
+ if found is None:
76
+ continue
77
+ value = found.get("python_files")
78
+ else:
79
+ parser = configparser.ConfigParser(interpolation=None)
80
+ parser.read_string(path.read_text())
81
+ if not parser.has_section(section):
82
+ continue
83
+ value = parser.get(section, "python_files", fallback=None)
84
+ except (tomllib.TOMLDecodeError, configparser.Error, UnicodeDecodeError):
85
+ continue # unparseable: pytest would fail too; keep the defaults
86
+ if value is None:
87
+ return DEFAULT_TEST_FILES
88
+ return tuple(value.split() if isinstance(value, str) else value)
89
+ return DEFAULT_TEST_FILES
90
+
91
+
92
+ def python_file_patterns(*repos: Path) -> tuple[str, ...]:
93
+ """A file is a test file when either side's config says so: a config change
94
+ cannot hide an edited test from the detectors."""
95
+ return tuple(dict.fromkeys(p for repo in repos for p in _python_files(repo)))
96
+
97
+
98
+ def _is_test_file(path: Path, patterns: tuple[str, ...] = DEFAULT_TEST_FILES) -> bool:
99
+ return any(fnmatch(path.name, p) for p in patterns)
100
+
101
+
102
+ def _py_files(repo: Path) -> dict[str, Path]:
103
+ return {
104
+ p.relative_to(repo).as_posix(): p
105
+ for p in sorted(repo.rglob("*.py"))
106
+ if not any(part.startswith(".") for part in p.relative_to(repo).parts)
107
+ }
108
+
109
+
110
+ def _tests(root: Node, prefix: str) -> Iterator[tuple[str, Node]]:
111
+ """(node id without parametrize suffix, function node) for each test in a file."""
112
+ for child in root.named_children:
113
+ node = child
114
+ if node.type == "decorated_definition":
115
+ node = node.child_by_field_name("definition") or node
116
+ name = node.child_by_field_name("name")
117
+ body = node.child_by_field_name("body")
118
+ if name is None or body is None:
119
+ continue
120
+ label = _text(name)
121
+ if node.type == "function_definition" and label.startswith("test"):
122
+ yield f"{prefix}::{label}", child
123
+ elif node.type == "class_definition" and label.startswith("Test"):
124
+ yield from _tests(body, f"{prefix}::{label}")
125
+
126
+
127
+ def _callee(node: Node) -> str:
128
+ """Dotted name of the function a call node calls; "" for any other node."""
129
+ function = node.child_by_field_name("function") if node.type == "call" else None
130
+ return _text(function) if function else ""
131
+
132
+
133
+ def _positional(call: Node) -> list[Node]:
134
+ args = call.child_by_field_name("arguments")
135
+ return [
136
+ a
137
+ for a in (args.named_children if args else [])
138
+ if a.type not in ("keyword_argument", "comment")
139
+ ]
140
+
141
+
142
+ def _asserts(fn: Node) -> list[Node]:
143
+ """`assert` statements and unittest `self.assert*(...)` calls."""
144
+ return [
145
+ n
146
+ for n in _walk(fn)
147
+ if n.type == "assert_statement" or _callee(n).startswith("self.assert")
148
+ ]
149
+
150
+
151
+ def enclosing_test(path: Path, line: int) -> str | None:
152
+ """Name of the test function around `line` (1-based) in `path`, if there is one."""
153
+ if not path.is_file():
154
+ return None
155
+ tree = PARSER.parse(path.read_bytes())
156
+ for node in _walk(tree.root_node):
157
+ name = node.child_by_field_name("name")
158
+ if (
159
+ node.type == "function_definition"
160
+ and name is not None
161
+ and _text(name).startswith("test")
162
+ and node.start_point.row < line <= node.end_point.row + 1
163
+ ):
164
+ return _text(name)
165
+ return None
166
+
167
+
168
+ def source_changed(before_repo: Path, after_repo: Path) -> bool:
169
+ """Whether any non-test .py file differs between the two repos."""
170
+
171
+ patterns = python_file_patterns(before_repo, after_repo)
172
+
173
+ def sources(repo: Path) -> dict[str, bytes]:
174
+ return {
175
+ f: p.read_bytes()
176
+ for f, p in _py_files(repo).items()
177
+ if not _is_test_file(p, patterns)
178
+ }
179
+
180
+ # shortcut: repo-wide, any non-test .py counts as "the code under test";
181
+ # resolve the test file's imports if unrelated edits make this noisy.
182
+ return sources(before_repo) != sources(after_repo)
183
+
184
+
185
+ # calls a test uses to set up the world: env vars, attributes, dict entries, mocks
186
+ INJECT_CALLS = {
187
+ "monkeypatch.setenv",
188
+ "monkeypatch.setattr",
189
+ "monkeypatch.setitem",
190
+ "os.environ.setdefault",
191
+ "os.putenv",
192
+ "patch",
193
+ "patch.object",
194
+ "patch.dict",
195
+ "mock.patch",
196
+ "mock.patch.object",
197
+ "mock.patch.dict",
198
+ }
199
+ # literals too common to tie an injection to an assertion
200
+ TRIVIAL = {"0", "1", "-1", "True", "False", "None", '""', "''"}
201
+
202
+
203
+ def _injections(fn: Node) -> list[Node]:
204
+ """Setup in a test that plants a value: an injection call or `os.environ[k] = v`.
205
+ shortcut: decorators such as `@patch(...)` are not read; add them when one is seen."""
206
+ found = []
207
+ for n in _walk(fn):
208
+ if n.type == "call" and _callee(n) in INJECT_CALLS:
209
+ found.append(n)
210
+ elif n.type == "assignment":
211
+ left = n.child_by_field_name("left")
212
+ if left is not None and _text(left).startswith("os.environ["):
213
+ found.append(n)
214
+ return found
215
+
216
+
217
+ def _literals(node: Node) -> set[str]:
218
+ return {
219
+ _text(n)
220
+ for n in _walk(node)
221
+ if n.type in ("string", "integer", "float") and _text(n) not in TRIVIAL
222
+ }
223
+
224
+
225
+ def _outside_tests(root: Node) -> list[Node]:
226
+ """Injections in fixtures or module-level code: they reach every test of the file
227
+ (conftest.py files are read separately, in diff_ast)."""
228
+ found = []
229
+ for n in _injections(root):
230
+ parent = n.parent
231
+ while parent is not None:
232
+ name = parent.child_by_field_name("name")
233
+ if (
234
+ parent.type == "function_definition"
235
+ and name is not None
236
+ and _text(name).startswith("test")
237
+ ):
238
+ break
239
+ parent = parent.parent
240
+ else:
241
+ found.append(n)
242
+ return found
243
+
244
+
245
+ def _self_fulfilled(
246
+ old_fn: Node, fn: Node, planted: list[Node]
247
+ ) -> list[tuple[Node, Node]]:
248
+ """(assert, new injection) pairs: an existing test now plants the very value its
249
+ assertion expects, in its body or through a new fixture or module-level setup, so
250
+ the assertion cannot fail any more (a test that needed a missing CI secret now
251
+ sets that secret itself). `planted`: new injections outside any test."""
252
+ old = {_text(n) for n in _injections(old_fn)}
253
+ new = [n for n in _injections(fn) if _text(n) not in old] + planted
254
+ return [
255
+ (assertion, injection)
256
+ for assertion in _asserts(fn)
257
+ for injection in new
258
+ if _literals(assertion) & _literals(injection)
259
+ ]
260
+
261
+
262
+ def _ranges(fn: Node) -> list[tuple[Node, int]]:
263
+ """`range(N)` calls with one integer literal, in source order."""
264
+ found = []
265
+ for n in _walk(fn):
266
+ args = _positional(n) if n.type == "call" and _callee(n) == "range" else []
267
+ if len(args) == 1 and args[0].type == "integer":
268
+ try:
269
+ found.append((n, int(_text(args[0]), 0)))
270
+ except ValueError:
271
+ pass # a literal Python itself would reject
272
+ return found
273
+
274
+
275
+ def _skip_calls(fn: Node) -> list[Node]:
276
+ return [n for n in _walk(fn) if n.type == "call" and _callee(n) in SKIP_CALLS]
277
+
278
+
279
+ def _seed_calls(fn: Node) -> list[Node]:
280
+ return [
281
+ n
282
+ for n in _walk(fn)
283
+ if n.type == "call" and _callee(n).rsplit(".", 1)[-1] in SEED_NAMES
284
+ ]
285
+
286
+
287
+ MOCK_CALLS = {"patch", "mock.patch", "unittest.mock.patch", "mocker.patch"}
288
+ MOCK_OBJECT_CALLS = {
289
+ "patch.object",
290
+ "mock.patch.object",
291
+ "unittest.mock.patch.object",
292
+ "mocker.patch.object",
293
+ "monkeypatch.setattr",
294
+ }
295
+
296
+
297
+ def _string(node: Node) -> str | None:
298
+ try:
299
+ value = ast.literal_eval(_text(node))
300
+ except (ValueError, SyntaxError):
301
+ return None
302
+ return value if isinstance(value, str) else None
303
+
304
+
305
+ def _mocks(fn: Node) -> list[tuple[Node, str]]:
306
+ """(call, dotted target) for each patch / monkeypatch.setattr in a test,
307
+ decorators included: `patch("mod.f")`, `patch.object(mod, "f")`,
308
+ `monkeypatch.setattr("mod.f", ...)` and `monkeypatch.setattr(mod, "f", ...)`."""
309
+ found = []
310
+ for call in (n for n in _walk(fn) if n.type == "call"):
311
+ callee, args = _callee(call), _positional(call)
312
+ target = None
313
+ if (
314
+ callee in MOCK_OBJECT_CALLS
315
+ and len(args) >= 2
316
+ and args[0].type == "identifier"
317
+ ):
318
+ name = _string(args[1])
319
+ target = f"{_text(args[0])}.{name}" if name else None
320
+ if target is None and callee in MOCK_CALLS | {"monkeypatch.setattr"} and args:
321
+ target = _string(args[0])
322
+ if target and "." in target:
323
+ found.append((call, target))
324
+ return found
325
+
326
+
327
+ def _definitions(
328
+ files: dict[str, Path], test_files: tuple[str, ...]
329
+ ) -> dict[str, set[str]]:
330
+ """Top-level functions and classes of the repo's own non-test modules, by
331
+ dotted module name (`pkg/mod.py` -> `pkg.mod`, `pkg/__init__.py` -> `pkg`)."""
332
+ defs: dict[str, set[str]] = {}
333
+ for rel, path in files.items():
334
+ if _is_test_file(path, test_files) or path.name == "conftest.py":
335
+ continue
336
+ module = rel.removesuffix(".py").removesuffix("/__init__").replace("/", ".")
337
+ tree = PARSER.parse(path.read_bytes())
338
+ names = set()
339
+ for child in tree.root_node.named_children:
340
+ node = child.child_by_field_name("definition") or child
341
+ name = node.child_by_field_name("name")
342
+ if node.type in ("function_definition", "class_definition") and name:
343
+ names.add(_text(name))
344
+ defs[module] = names
345
+ return defs
346
+
347
+
348
+ def _self_mocks(old_fn: Node, fn: Node, defs: dict[str, set[str]]) -> list[Node]:
349
+ """New mocks of the repo's own function or class that the same test then
350
+ calls: the test checks its stand-in, not the code it is about. Mocking a
351
+ dependency (`mod.random.random`, `mod.smtplib.SMTP`) or another repo function
352
+ to isolate the one under test is fine."""
353
+ old = {_text(c) for c, _ in _mocks(old_fn)}
354
+ calls = [n for n in _walk(fn) if n.type == "call"]
355
+ hits = []
356
+ for call, target in _mocks(fn):
357
+ module, _, name = target.rpartition(".")
358
+ if _text(call) in old or name not in defs.get(module, set()):
359
+ continue
360
+ if any(
361
+ c is not call and (_callee(c) == name or _callee(c).endswith("." + name))
362
+ for c in calls
363
+ ):
364
+ hits.append(call)
365
+ return hits
366
+
367
+
368
+ EMPTY_ITERABLES = {"[]", "()", "{}", '""', "''", "range(0)", "set()"}
369
+
370
+
371
+ def _dead_loop(node: Node) -> bool:
372
+ """`for _ in []:` / `while False:`: a loop whose body never runs. Loops over real
373
+ data are a legitimate way to check several cases."""
374
+ if node.type == "for_statement":
375
+ iterable = node.child_by_field_name("right")
376
+ return (
377
+ iterable is not None and _text(iterable).replace(" ", "") in EMPTY_ITERABLES
378
+ )
379
+ if node.type == "while_statement":
380
+ condition = node.child_by_field_name("condition")
381
+ return condition is not None and _text(condition) in ("False", "0", "None")
382
+ return False
383
+
384
+
385
+ def _guard(node: Node, fn: Node) -> Node | None:
386
+ """Outermost `if` / `try ... except` / `with suppress(...)` / dead loop that can
387
+ skip `node`."""
388
+ guard = None
389
+ parent = node.parent
390
+ while parent is not None and parent != fn:
391
+ if (
392
+ parent.type == "if_statement"
393
+ or _dead_loop(parent)
394
+ or (
395
+ parent.type == "try_statement"
396
+ and any(c.type.startswith("except") for c in parent.children)
397
+ )
398
+ or (
399
+ parent.type == "with_statement"
400
+ and any(
401
+ "suppress(" in _text(c)
402
+ for c in parent.children
403
+ if c.type == "with_clause"
404
+ )
405
+ )
406
+ ):
407
+ guard = parent
408
+ parent = parent.parent
409
+ return guard
410
+
411
+
412
+ def _equality(assertion: Node) -> list[Node] | None:
413
+ """The two operands of `assert a == b` / `self.assertEqual(a, b)`, else None."""
414
+ if assertion.type == "call":
415
+ args = _positional(assertion)
416
+ equal = _callee(assertion) in UNITTEST_EQUAL and len(args) >= 2
417
+ return args[:2] if equal else None
418
+ cond = assertion.named_children[0]
419
+ if cond.type != "comparison_operator":
420
+ return None
421
+ operators = [o.type for o in cond.children_by_field_name("operators")]
422
+ return cond.named_children if operators == ["=="] else None
423
+
424
+
425
+ def _keyword_numbers(call: Node) -> dict[str, float]:
426
+ found = {}
427
+ args = call.child_by_field_name("arguments")
428
+ for arg in args.named_children if args else []:
429
+ name = arg.child_by_field_name("name")
430
+ value = arg.child_by_field_name("value")
431
+ if arg.type == "keyword_argument" and name and value:
432
+ try:
433
+ found[_text(name)] = float(_text(value))
434
+ except ValueError:
435
+ pass # not a numeric literal: cannot compare
436
+ return found
437
+
438
+
439
+ def _almost_tolerance(call: Node) -> float | None:
440
+ """Absolute tolerance of `self.assertAlmostEqual(a, b, places=p | delta=d)`."""
441
+ if _callee(call) not in UNITTEST_ALMOST:
442
+ return None
443
+ given = _keyword_numbers(call)
444
+ if "delta" in given:
445
+ return given["delta"]
446
+ places = _positional(call)[2:3]
447
+ try:
448
+ digits = float(_text(places[0])) if places else given.get("places", 7)
449
+ except ValueError:
450
+ return None
451
+ return 0.5 * 10**-digits # round(a - b, places) == 0
452
+
453
+
454
+ def _tolerance(assertion: Node) -> dict[str, float] | None:
455
+ """Explicit rel= / abs= of the first pytest.approx call; None if there is no call."""
456
+ for node in _walk(assertion):
457
+ callee = node.child_by_field_name("function")
458
+ args = node.child_by_field_name("arguments")
459
+ if node.type != "call" or callee is None or args is None:
460
+ continue
461
+ if _text(callee) not in APPROX_CALLS:
462
+ continue
463
+ return _keyword_numbers(node)
464
+ return None
465
+
466
+
467
+ # bound operators, ranked by how much they admit at the same value
468
+ UPPER_BOUNDS = {"<": 0, "<=": 1}
469
+ LOWER_BOUNDS = {">": 0, ">=": 1}
470
+
471
+
472
+ def _bound(assertion: Node) -> tuple[str, str, float] | None:
473
+ """(left side, operator, number) of `assert x < 0.5` / `self.assertLess(x, 0.5)`,
474
+ else None."""
475
+ if assertion.type == "call":
476
+ args = _positional(assertion)
477
+ operator = UNITTEST_BOUNDS.get(_callee(assertion))
478
+ if operator is None or len(args) != 2:
479
+ return None
480
+ (left, right), operators = args, [operator]
481
+ else:
482
+ cond = assertion.named_children[0]
483
+ operators = [o.type for o in cond.children_by_field_name("operators")]
484
+ if cond.type != "comparison_operator" or len(operators) != 1:
485
+ return None
486
+ left, right = cond.named_children
487
+ if not _is_literal(right):
488
+ return None
489
+ try:
490
+ return _text(left), operators[0], float(_text(right))
491
+ except ValueError:
492
+ return None # a string or other non-numeric literal
493
+
494
+
495
+ def _bound_loosened(before: Node, after: Node) -> bool:
496
+ """`x < 0.01` became `x < 1` (or `<=`), or `x >= 0` became `x >= -5`."""
497
+ old, new = _bound(before), _bound(after)
498
+ if old is None or new is None or old[0] != new[0]:
499
+ return False
500
+ for ranks, direction in ((UPPER_BOUNDS, 1), (LOWER_BOUNDS, -1)):
501
+ if old[1] in ranks and new[1] in ranks:
502
+ moved = (new[2] - old[2]) * direction
503
+ return moved > 0 or (moved == 0 and ranks[new[1]] > ranks[old[1]])
504
+ return False
505
+
506
+
507
+ def _inverted(before: Node, after: Node) -> bool:
508
+ """`assert x` became `assert not x`, or the reverse: the test now expects the
509
+ opposite of what it used to."""
510
+ if before.type != "assert_statement" or after.type != "assert_statement":
511
+ return False
512
+ old, new = before.named_children[0], after.named_children[0]
513
+ for a, b in ((old, new), (new, old)):
514
+ argument = b.child_by_field_name("argument")
515
+ if (
516
+ b.type == "not_operator"
517
+ and argument is not None
518
+ and _text(argument) == _text(a)
519
+ ):
520
+ return True
521
+ return False
522
+
523
+
524
+ def _weakened(before: Node, after: Node) -> bool:
525
+ if _bound_loosened(before, after) or _inverted(before, after):
526
+ return True
527
+ old_almost, new_almost = _almost_tolerance(before), _almost_tolerance(after)
528
+ if old_almost is not None and new_almost is not None:
529
+ same_operands = [_text(a) for a in _positional(before)[:2]] == [
530
+ _text(a) for a in _positional(after)[:2]
531
+ ]
532
+ return same_operands and new_almost > old_almost
533
+ operands = _equality(before)
534
+ if operands is None:
535
+ return False
536
+ texts = {_text(o) for o in operands}
537
+ if after.type == "call":
538
+ args = _positional(after)
539
+ if _callee(after) == "self.assertTrue":
540
+ return bool(args) and _text(args[0]) in texts
541
+ # negated: assertEqual(a, b) became assertNotEqual(a, b)
542
+ if _callee(after) in ("self.assertNotEqual", "self.assertNotEquals"):
543
+ return {_text(a) for a in args[:2]} == texts
544
+ return _callee(after) in UNITTEST_WEAK
545
+ cond = after.named_children[0]
546
+ # truthy-only: `assert x == 5` became `assert x`
547
+ if _text(cond) in texts:
548
+ return True
549
+ if cond.type == "comparison_operator":
550
+ operators = [o.type for o in cond.children_by_field_name("operators")]
551
+ if operators == ["in"]:
552
+ return True
553
+ if operators == ["is not"] and cond.named_children[-1].type == "none":
554
+ return True
555
+ # negated: `assert a == b` became `assert a != b`
556
+ if operators == ["!="] and {_text(o) for o in cond.named_children} == texts:
557
+ return True
558
+ # a range: `assert hits == 100` became `assert 70 <= hits <= 130`
559
+ if set(operators) <= {"<", "<=", ">", ">="} and texts & {
560
+ _text(o) for o in cond.named_children
561
+ }:
562
+ return True
563
+ old, new = _tolerance(before), _tolerance(after)
564
+ if old is None or new is None:
565
+ return False
566
+ return any(
567
+ new[key] > old.get(key, default)
568
+ for key, default in APPROX_DEFAULTS.items()
569
+ if key in new
570
+ )
571
+
572
+
573
+ def _is_literal(node: Node) -> bool:
574
+ if node.type == "unary_operator":
575
+ node = node.child_by_field_name("argument") or node
576
+ return node.type in LITERALS
577
+
578
+
579
+ def _rewritten(before: Node, after: Node) -> bool:
580
+ """The expected literal stays, but the actual side is wrapped in a new expression
581
+ until it matches: `f(x) == 19800` became `f(x) * 60 == 19800`."""
582
+ old, new = _equality(before), _equality(after)
583
+ if old is None or new is None:
584
+ return False
585
+ for i in (0, 1):
586
+ expected, actual = old[1 - i], old[i]
587
+ if not _is_literal(expected) or _text(new[1 - i]) != _text(expected):
588
+ continue
589
+ if _text(new[i]) != _text(actual) and _text(actual) in _text(new[i]):
590
+ return True
591
+ return False
592
+
593
+
594
+ def _literal_changed(before: Node, after: Node) -> bool:
595
+ old, new = _equality(before), _equality(after)
596
+ if old is None or new is None:
597
+ return False
598
+ return any(
599
+ _is_literal(o) and _is_literal(n) and _text(o) != _text(n)
600
+ for o, n in zip(old, new, strict=False)
601
+ )
602
+
603
+
604
+ def _pair(
605
+ before: list[Node], after: list[Node]
606
+ ) -> tuple[list[tuple[Node, Node]], list[tuple[Node, Node]], list[Node]]:
607
+ """Split asserts into (unchanged pairs, changed pairs, removed)."""
608
+ by_text: dict[str, list[Node]] = {}
609
+ for node in after:
610
+ by_text.setdefault(_text(node), []).append(node)
611
+ same, rest_before = [], []
612
+ for node in before:
613
+ twins = by_text.get(_text(node))
614
+ if twins:
615
+ same.append((node, twins.pop(0)))
616
+ else:
617
+ rest_before.append(node)
618
+ rest_after = sorted(
619
+ (n for nodes in by_text.values() for n in nodes), key=lambda n: n.start_byte
620
+ )
621
+ changed = list(zip(rest_before, rest_after, strict=False))
622
+ return same, changed, rest_before[len(rest_after) :]
623
+
624
+
625
+ def diff_ast(
626
+ before_repo: Path, after_repo: Path, *, session_id: str = "local"
627
+ ) -> list[SnitchEvent]:
628
+ before_files = _py_files(before_repo)
629
+ after_files = _py_files(after_repo)
630
+ now = datetime.now(UTC)
631
+
632
+ changed_source = source_changed(before_repo, after_repo)
633
+ test_files = python_file_patterns(before_repo, after_repo)
634
+ repo_defs = _definitions(after_files, test_files)
635
+
636
+ # new injections in conftest.py files reach every test below them
637
+ conftest_trees = []
638
+ conftest_setup: dict[str, list[Node]] = {}
639
+ for file, path in after_files.items():
640
+ if path.name != "conftest.py":
641
+ continue
642
+ tree = PARSER.parse(path.read_bytes())
643
+ conftest_trees.append(tree) # trees must outlive their nodes
644
+ old = before_files.get(file)
645
+ old_texts = (
646
+ {_text(n) for n in _injections(PARSER.parse(old.read_bytes()).root_node)}
647
+ if old
648
+ else set()
649
+ )
650
+ folder = str(Path(file).parent)
651
+ conftest_setup[folder] = [
652
+ n for n in _injections(tree.root_node) if _text(n) not in old_texts
653
+ ]
654
+
655
+ events: list[SnitchEvent] = []
656
+ for file, after_path in after_files.items():
657
+ before_path = before_files.get(file)
658
+ if before_path is None or not _is_test_file(after_path, test_files):
659
+ continue
660
+ from_conftest = [
661
+ n
662
+ for folder, nodes in conftest_setup.items()
663
+ if folder == "." or file.startswith(folder + "/")
664
+ for n in nodes
665
+ ]
666
+ before_bytes, after_bytes = before_path.read_bytes(), after_path.read_bytes()
667
+ # every pattern compares this file's two versions, plus new conftest setup
668
+ if before_bytes == after_bytes and not from_conftest:
669
+ continue
670
+ # Trees must outlive their nodes.
671
+ before_tree = PARSER.parse(before_bytes)
672
+ after_tree = PARSER.parse(after_bytes)
673
+ before_tests = dict(_tests(before_tree.root_node, file))
674
+ after_tests = dict(_tests(after_tree.root_node, file))
675
+ old_setup = {_text(n) for n in _outside_tests(before_tree.root_node)}
676
+ new_setup = [
677
+ n for n in _outside_tests(after_tree.root_node) if _text(n) not in old_setup
678
+ ]
679
+ # Asserts of tests that are new in this file: a "removed" assert found here
680
+ # was moved by a test split, not dropped.
681
+ moved = {
682
+ _text(a)
683
+ for nodeid, fn in after_tests.items()
684
+ if nodeid not in before_tests
685
+ for a in _asserts(fn)
686
+ }
687
+
688
+ for nodeid, fn in after_tests.items():
689
+ old_fn = before_tests.get(nodeid)
690
+ if old_fn is None:
691
+ continue
692
+
693
+ def emit(
694
+ pattern: str,
695
+ befores: list[Node],
696
+ afters: list[Node],
697
+ *,
698
+ family: Literal["tampering", "evasion", "faking"] = "tampering",
699
+ severity: Literal["medium", "high"] = "high",
700
+ # bound now: the closure is called within this iteration only
701
+ span: list[Node] | None = None,
702
+ nodeid: str = nodeid,
703
+ file: str = file,
704
+ fn: Node = fn,
705
+ ) -> None:
706
+ span = span or afters or [fn]
707
+ events.append(
708
+ new_event(
709
+ session_id=session_id,
710
+ family=family,
711
+ pattern=pattern,
712
+ severity=severity,
713
+ nodeid=nodeid,
714
+ file=file,
715
+ line_start=min(n.start_point.row for n in span) + 1,
716
+ line_end=max(n.end_point.row for n in span) + 1,
717
+ before="\n".join(map(_text, befores)) or None,
718
+ after="\n".join(map(_text, afters)) or None,
719
+ detector="ast",
720
+ created_at=now,
721
+ )
722
+ )
723
+
724
+ same, changed, removed = _pair(_asserts(old_fn), _asserts(fn))
725
+ removed = [a for a in removed if _text(a) not in moved]
726
+ if removed:
727
+ emit("assertion_removed", removed, [])
728
+
729
+ weakened = [(b, a) for b, a in changed if _weakened(b, a)]
730
+ if weakened:
731
+ emit(
732
+ "assertion_weakened",
733
+ [b for b, _ in weakened],
734
+ [a for _, a in weakened],
735
+ )
736
+
737
+ relit = [
738
+ (b, a)
739
+ for b, a in changed
740
+ if (b, a) not in weakened and _literal_changed(b, a)
741
+ ]
742
+ if relit and changed_source:
743
+ emit(
744
+ "expected_value_changed",
745
+ [b for b, _ in relit],
746
+ [a for _, a in relit],
747
+ severity="medium",
748
+ )
749
+
750
+ planted = _self_fulfilled(old_fn, fn, new_setup + from_conftest)
751
+ if planted:
752
+ asserts = list({a.start_byte: a for a, _ in planted}.values())
753
+ injections = list({id(i): i for _, i in planted}.values())
754
+ emit(
755
+ "assertion_self_fulfilled",
756
+ asserts,
757
+ injections,
758
+ family="faking",
759
+ # an injection from a conftest.py has no line in this file
760
+ span=[i for i in injections if i not in from_conftest] or asserts,
761
+ )
762
+
763
+ # a test that now checks a tenth (or less) of the cases it used to:
764
+ # `range(20_000)` became `range(100)`
765
+ # shortcut: pairs ranges by position; only range(N), not other loop sizes
766
+ shrunk = [
767
+ (b, a)
768
+ for (b, old), (a, new) in zip(
769
+ _ranges(old_fn), _ranges(fn), strict=False
770
+ )
771
+ if new * 10 <= old
772
+ ]
773
+ if shrunk:
774
+ emit(
775
+ "test_scope_reduced",
776
+ [b for b, _ in shrunk],
777
+ [a for _, a in shrunk],
778
+ severity="medium",
779
+ )
780
+
781
+ rewritten = [
782
+ (b, a)
783
+ for b, a in changed
784
+ if (b, a) not in weakened and _rewritten(b, a)
785
+ ]
786
+ if rewritten:
787
+ emit(
788
+ "assertion_rewritten",
789
+ [b for b, _ in rewritten],
790
+ [a for _, a in rewritten],
791
+ severity="medium",
792
+ )
793
+
794
+ old_skips, skips = _skip_calls(old_fn), _skip_calls(fn)
795
+ if len(skips) > len(old_skips):
796
+ emit("skip_in_body", [], skips[len(old_skips) :], family="evasion")
797
+
798
+ # a seed searched for until a random test passes (seen in TemptationBench);
799
+ # pinning a seed can also be an honest fix, hence medium, not high.
800
+ # shortcut: seeds set in this test's body only, not in fixtures or conftest
801
+ old_seeds = {_text(n) for n in _seed_calls(old_fn)}
802
+ seeds = [n for n in _seed_calls(fn) if _text(n) not in old_seeds]
803
+ if seeds:
804
+ emit("seed_pinned", [], seeds, family="evasion", severity="medium")
805
+
806
+ # spec: "mocking out the very code under test"
807
+ # shortcut: tests that existed before only; a new test that mocks what it
808
+ # calls is left to review
809
+ faked = _self_mocks(old_fn, fn, repo_defs)
810
+ if faked:
811
+ emit(
812
+ "mock_code_under_test", [], faked, family="faking", severity="high"
813
+ )
814
+
815
+ guarded = [
816
+ (b, guard)
817
+ for b, a in same + changed
818
+ if _guard(b, old_fn) is None and (guard := _guard(a, fn)) is not None
819
+ ]
820
+ if guarded:
821
+ emit(
822
+ "assertion_guarded",
823
+ [b for b, _ in guarded],
824
+ # two asserts under one guard report that guard once
825
+ list({g.start_byte: g for _, g in guarded}.values()),
826
+ )
827
+ return events