codeveto 0.1.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.
Files changed (106) hide show
  1. codeveto/__init__.py +3 -0
  2. codeveto/__main__.py +8 -0
  3. codeveto/ai/__init__.py +19 -0
  4. codeveto/ai/harness.py +303 -0
  5. codeveto/ai/packets.py +855 -0
  6. codeveto/ai/policy.py +222 -0
  7. codeveto/ai/prompt.py +101 -0
  8. codeveto/ai/providers/__init__.py +178 -0
  9. codeveto/ai/providers/claude.py +247 -0
  10. codeveto/ai/providers/openai_compat.py +246 -0
  11. codeveto/ai/runner.py +293 -0
  12. codeveto/ai/verify.py +324 -0
  13. codeveto/anchor.py +211 -0
  14. codeveto/cli.py +247 -0
  15. codeveto/cli_explain.py +49 -0
  16. codeveto/cli_hook.py +31 -0
  17. codeveto/cli_init.py +254 -0
  18. codeveto/cli_mcp.py +29 -0
  19. codeveto/cli_packets.py +35 -0
  20. codeveto/cli_publish.py +29 -0
  21. codeveto/cli_review.py +362 -0
  22. codeveto/cli_rules.py +78 -0
  23. codeveto/cli_verify.py +47 -0
  24. codeveto/config.py +1229 -0
  25. codeveto/data/README.md +16 -0
  26. codeveto/data/ai-wire.schema.json +53 -0
  27. codeveto/data/prompts/system.md +57 -0
  28. codeveto/data/report-v1.schema.json +268 -0
  29. codeveto/data/templates/forgejo-codeveto.yml +104 -0
  30. codeveto/data/templates/github-codeveto.yml +18 -0
  31. codeveto/embedded.py +311 -0
  32. codeveto/engine.py +1570 -0
  33. codeveto/git.py +1549 -0
  34. codeveto/globs.py +348 -0
  35. codeveto/integrations/__init__.py +1 -0
  36. codeveto/integrations/hooks.py +327 -0
  37. codeveto/integrations/mcp.py +770 -0
  38. codeveto/integrations/mcp_ai.py +77 -0
  39. codeveto/integrations/prepush.py +222 -0
  40. codeveto/jsonsafe.py +60 -0
  41. codeveto/languages.py +539 -0
  42. codeveto/lexers.py +2560 -0
  43. codeveto/model.py +372 -0
  44. codeveto/publish/__init__.py +28 -0
  45. codeveto/publish/action.py +330 -0
  46. codeveto/publish/common.py +84 -0
  47. codeveto/publish/diff.py +208 -0
  48. codeveto/publish/event.py +241 -0
  49. codeveto/publish/forgejo.py +184 -0
  50. codeveto/publish/github.py +380 -0
  51. codeveto/publish/http.py +263 -0
  52. codeveto/publish/pull.py +218 -0
  53. codeveto/publish/untrusted.py +110 -0
  54. codeveto/py.typed +0 -0
  55. codeveto/redact.py +113 -0
  56. codeveto/render/__init__.py +64 -0
  57. codeveto/render/agent.py +43 -0
  58. codeveto/render/github.py +101 -0
  59. codeveto/render/json.py +23 -0
  60. codeveto/render/markdown.py +208 -0
  61. codeveto/render/safe.py +249 -0
  62. codeveto/render/sarif.py +217 -0
  63. codeveto/render/text.py +210 -0
  64. codeveto/report.py +252 -0
  65. codeveto/rules/__init__.py +84 -0
  66. codeveto/rules/agent.py +2972 -0
  67. codeveto/rules/base.py +1026 -0
  68. codeveto/rules/ci.py +1708 -0
  69. codeveto/rules/config.py +493 -0
  70. codeveto/rules/deps.py +1693 -0
  71. codeveto/rules/docker.py +479 -0
  72. codeveto/rules/examples/__init__.py +148 -0
  73. codeveto/rules/examples/agent.py +839 -0
  74. codeveto/rules/examples/ci.py +1046 -0
  75. codeveto/rules/examples/config.py +191 -0
  76. codeveto/rules/examples/deps.py +369 -0
  77. codeveto/rules/examples/docker.py +157 -0
  78. codeveto/rules/examples/go.py +241 -0
  79. codeveto/rules/examples/hygiene.py +466 -0
  80. codeveto/rules/examples/js.py +462 -0
  81. codeveto/rules/examples/python.py +595 -0
  82. codeveto/rules/examples/rust.py +268 -0
  83. codeveto/rules/examples/secrets.py +561 -0
  84. codeveto/rules/examples/security.py +608 -0
  85. codeveto/rules/examples/shell.py +174 -0
  86. codeveto/rules/examples/sql.py +194 -0
  87. codeveto/rules/examples/tests.py +497 -0
  88. codeveto/rules/go.py +328 -0
  89. codeveto/rules/hygiene.py +1094 -0
  90. codeveto/rules/js.py +768 -0
  91. codeveto/rules/python.py +1642 -0
  92. codeveto/rules/rust.py +209 -0
  93. codeveto/rules/secrets.py +1335 -0
  94. codeveto/rules/security.py +3680 -0
  95. codeveto/rules/shell.py +867 -0
  96. codeveto/rules/sql.py +629 -0
  97. codeveto/rules/tests.py +1404 -0
  98. codeveto/schema.py +384 -0
  99. codeveto/statements.py +607 -0
  100. codeveto/worktree.py +1176 -0
  101. codeveto/yamlish.py +1179 -0
  102. codeveto-0.1.0.dist-info/METADATA +253 -0
  103. codeveto-0.1.0.dist-info/RECORD +106 -0
  104. codeveto-0.1.0.dist-info/WHEEL +4 -0
  105. codeveto-0.1.0.dist-info/entry_points.txt +2 -0
  106. codeveto-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,1404 @@
1
+ """Tests pack (SPEC 6.1): focused, skipped, weakened and missing tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import bisect
7
+ import re
8
+ from collections import Counter
9
+ from collections.abc import Iterator
10
+ from dataclasses import dataclass, field
11
+
12
+ from codeveto import lexers
13
+ from codeveto.lexers import LexResult, LineIndex, StringSpan
14
+ from codeveto.model import FileKind, FileStatus, Side, git_lines
15
+ from codeveto.rules.base import ChangeContext, FileContext, Hit, LineText, rule
16
+ from codeveto.yamlish import to_python
17
+
18
+ TESTED_LANGUAGES = frozenset({"python", "javascript", "typescript", "go", "rust", "java", "kotlin"})
19
+ """Languages whose source changes are expected to come with tests."""
20
+
21
+
22
+ def _has_code(
23
+ masked: str, strings: list[tuple[int, int]], starts: list[int], lo: int, hi: int
24
+ ) -> bool:
25
+ """Is a non-blank character of ``masked[lo:hi]`` outside every string span?"""
26
+ k = max(bisect.bisect_right(starts, lo) - 1, 0)
27
+ pos = lo
28
+ while pos < hi:
29
+ while k < len(strings) and strings[k][1] <= pos:
30
+ k += 1
31
+ if k == len(strings) or strings[k][0] >= hi:
32
+ return bool(masked[pos:hi].strip())
33
+ start, end = strings[k]
34
+ if start > pos and masked[pos:start].strip():
35
+ return True
36
+ pos = max(pos, end)
37
+ k += 1
38
+ return False
39
+
40
+
41
+ def _code_keys(text: str, spans: LexResult, numbers: list[int]) -> list[tuple[int, str]]:
42
+ """``(line, whitespace-free text)`` of the given lines that hold code.
43
+
44
+ A line holds code when a non-blank character of it lies outside every
45
+ comment and every top-level string literal, so comment, docstring and
46
+ blank-line edits do not count.
47
+ """
48
+ masked = lexers.code_only(text, spans)
49
+ strings = [(s.start, s.end) for s in spans.spans if isinstance(s, StringSpan)]
50
+ starts = [s for s, _ in strings]
51
+ comments = [(c.start, c.end) for c in lexers.flatten(spans)[1]]
52
+ comment_starts = [c for c, _ in comments]
53
+ index = LineIndex(text)
54
+ lines = git_lines(text)
55
+ found: list[tuple[int, str]] = []
56
+ for number in numbers:
57
+ if number > len(lines):
58
+ continue
59
+ lo = index.line_start(number)
60
+ hi = lo + len(lines[number - 1])
61
+ if _has_code(masked, strings, starts, lo, hi):
62
+ found.append((number, _key(text, comments, comment_starts, lo, hi)))
63
+ return found
64
+
65
+
66
+ def _key(text: str, comments: list[tuple[int, int]], starts: list[int], lo: int, hi: int) -> str:
67
+ """``text[lo:hi]`` without comments and whitespace (strings kept)."""
68
+ parts: list[str] = []
69
+ pos = lo
70
+ k = max(bisect.bisect_right(starts, lo) - 1, 0)
71
+ while pos < hi and k < len(comments):
72
+ start, end = comments[k]
73
+ k += 1
74
+ if end <= pos:
75
+ continue
76
+ if start >= hi:
77
+ break
78
+ parts.append(text[pos : max(start, pos)])
79
+ pos = max(pos, end)
80
+ parts.append(text[pos:hi])
81
+ return "".join("".join(parts).split())
82
+
83
+
84
+ def changed_code_lines(ctx: FileContext) -> list[int]:
85
+ """Added lines whose code is new: not blank, not only comments or strings.
86
+
87
+ An added code line that matches a removed code line apart from
88
+ whitespace (a re-indent, a moved line) is not a change.
89
+ """
90
+ text = ctx.new_text
91
+ if not text or not ctx.added_lines:
92
+ return []
93
+ added = _code_keys(text, ctx.spans, sorted(ctx.added_lines))
94
+ removed: Counter[str] = Counter()
95
+ old = ctx.old_text
96
+ if old and ctx.removed_lines:
97
+ old_spans = lexers.lex(old, ctx.language, path=ctx.old_path or ctx.path)
98
+ removed.update(key for _, key in _code_keys(old, old_spans, sorted(ctx.removed_lines)))
99
+ result: list[int] = []
100
+ for number, key in added:
101
+ if removed[key] > 0:
102
+ removed[key] -= 1
103
+ else:
104
+ result.append(number)
105
+ return result
106
+
107
+
108
+ @rule(
109
+ id="tests/untested-change",
110
+ severity="warning",
111
+ title="Source changed without a test change",
112
+ scope="change",
113
+ rationale=(
114
+ "Code changed but no test did, so nothing shows that the new behaviour works or "
115
+ "that the old behaviour still does."
116
+ ),
117
+ hint="Add or update a test that exercises the changed code.",
118
+ tags={"tests"},
119
+ )
120
+ def untested_change(ctx: ChangeContext) -> Iterator[Hit]:
121
+ """Source code changed and no test code was added or modified.
122
+
123
+ A code change is a :func:`changed_code_lines` line of a source-class file
124
+ in Python, JavaScript, TypeScript, Go, Rust, Java or Kotlin, outside
125
+ in-file test regions. A test change is such a line in a test-class file,
126
+ or inside a Rust ``#[cfg(test)]`` item or Go test function; deleting test
127
+ files or lines, comment and whitespace edits do not count. Reports once,
128
+ at the first changed code line of the first such source file.
129
+ """
130
+ first: tuple[str, int] | None = None
131
+ count = 0
132
+ for f in ctx.files:
133
+ if f.kind is not FileKind.TEXT:
134
+ continue
135
+ lines = changed_code_lines(f)
136
+ if not lines:
137
+ continue
138
+ if f.file_class == "test" or any(f.in_test_region(n) for n in lines):
139
+ return
140
+ if f.file_class != "source" or f.language not in TESTED_LANGUAGES:
141
+ continue
142
+ code = [n for n in lines if not f.in_test_region(n)]
143
+ if code:
144
+ count += 1
145
+ if first is None:
146
+ first = (f.path, code[0])
147
+ if first is None:
148
+ return
149
+ files = "1 source file" if count == 1 else f"{count} source files"
150
+ yield Hit(first[1], path=first[0], message=f"{files} changed without a test change")
151
+
152
+
153
+ # --- Shared helpers ------------------------------------------------------------------
154
+
155
+ _JS = frozenset({"javascript", "typescript"})
156
+ _JVM = frozenset({"java", "kotlin"})
157
+
158
+
159
+ def _basename(path: str) -> str:
160
+ return path.rsplit("/", 1)[-1]
161
+
162
+
163
+ def _is_cypress(path: str) -> bool:
164
+ return ".cy." in _basename(path) or "/cypress/" in "/" + path
165
+
166
+
167
+ def is_test_file(ctx: FileContext) -> bool:
168
+ """Is the whole file test code?
169
+
170
+ The ``test`` file class, plus JavaScript/TypeScript Cypress specs
171
+ (``*.cy.*`` and files under a ``cypress/`` directory), which the SPEC 5.4
172
+ class table does not list.
173
+ """
174
+ if ctx.file_class == "test":
175
+ return True
176
+ return ctx.file_class == "source" and ctx.language in _JS and _is_cypress(ctx.path)
177
+
178
+
179
+ def _in_test(ctx: FileContext, line: int) -> bool:
180
+ return is_test_file(ctx) or ctx.in_test_region(line)
181
+
182
+
183
+ def _code_windows(ctx: FileContext) -> Iterator[tuple[int, LineText, str]]:
184
+ """``(number, text, masked)`` for each changed new-side line window.
185
+
186
+ ``masked`` is the same window of ``masked_code`` (string and comment
187
+ interiors blanked, delimiters kept), so offsets match ``text``.
188
+ """
189
+ masked_lines = git_lines(ctx.masked_code)
190
+ for number, text in ctx.changed_lines():
191
+ row = masked_lines[number - 1] if number <= len(masked_lines) else ""
192
+ yield number, text, row[text.offset : text.offset + len(text)]
193
+
194
+
195
+ def _is_code(text: str, masked: str, index: int) -> bool:
196
+ """Is ``text[index]`` a code character (not inside a string or comment)?"""
197
+ return 0 <= index < len(masked) and masked[index] == text[index] and not text[index].isspace()
198
+
199
+
200
+ def _mask(text: str, language: str, path: str) -> str:
201
+ return lexers.mask(text, lexers.lex(text, language, path=path))
202
+
203
+
204
+ def _family(language: str) -> str:
205
+ if language in _JS:
206
+ return "js"
207
+ return "jvm" if language in _JVM else language
208
+
209
+
210
+ def _squash(text: str) -> str:
211
+ return " ".join(text.split())
212
+
213
+
214
+ def _found(text: str, m: re.Match[str]) -> str:
215
+ """The matched call name, without the opening bracket and title quote."""
216
+ return _squash(text[m.start() : m.end()].rstrip("(`'\" \t"))
217
+
218
+
219
+ # --- tests/focused-test --------------------------------------------------------------
220
+
221
+ _JS_NAMES = r"(?<![\w$.])(?P<name>it|test|describe|context|suite|specify|bench|fixture)"
222
+ _JS_CHAIN = r"(?P<chain>(?:\.(?:describe|concurrent|sequential|serial|parallel)){0,2})"
223
+ _JS_ONLY = re.compile(_JS_NAMES + _JS_CHAIN + r"\.only(?:\.each)?\s{0,4}[(`]")
224
+ _JS_FOCUS = re.compile(r"(?<![\w$.])(?:fit|fdescribe|fcontext)\s{0,4}\(\s{0,4}[\"'`]")
225
+ _PY_FOCUS = re.compile(r"(?<![\w.])pytest\.mark\.(?:only|focus)\b")
226
+
227
+
228
+ @rule(
229
+ id="tests/focused-test",
230
+ severity="error",
231
+ title="Focused test left in",
232
+ languages={"javascript", "typescript", "python"},
233
+ scope="line",
234
+ rationale=(
235
+ "A focused test (it.only, describe.only, fit, @pytest.mark.only) makes the runner "
236
+ "skip every other test of the file or suite, so CI passes without running them."
237
+ ),
238
+ hint="Remove the .only, the f prefix or the focus marker before merging.",
239
+ tags={"tests"},
240
+ )
241
+ def focused_test(ctx: FileContext) -> Iterator[Hit]:
242
+ """``.only`` calls, ``fit``/``fdescribe`` and pytest focus markers in test files.
243
+
244
+ JavaScript and TypeScript (Mocha, Jest, Vitest, Jasmine, Playwright,
245
+ Cypress, AVA, TestCafe): ``it``, ``test``, ``describe``, ``context``,
246
+ ``suite``, ``specify``, ``bench`` or ``fixture``, optionally chained
247
+ through ``.describe``/``.concurrent``/``.serial``/``.parallel``, then
248
+ ``.only(`` or ``.only.each``; ``fit(``, ``fdescribe(`` and ``fcontext(``
249
+ only with a string title, so a helper or ``model.fit`` stays silent.
250
+ Python has no built-in focus marker: only the ``pytest.mark.only`` and
251
+ ``pytest.mark.focus`` plugin markers count. Only code counts (strings and
252
+ comments are masked), and only in test files (the ``test`` class and
253
+ Cypress specs): a source file that defines or re-exports such names is
254
+ never a hit.
255
+ """
256
+ if not is_test_file(ctx):
257
+ return
258
+ patterns = (_PY_FOCUS,) if ctx.language == "python" else (_JS_ONLY, _JS_FOCUS)
259
+ for number, text, masked in _code_windows(ctx):
260
+ for pattern in patterns:
261
+ for m in pattern.finditer(masked):
262
+ found = _found(text, m)
263
+ yield Hit(
264
+ number,
265
+ column=text.column(m.start()),
266
+ message=f"Focused test: {found}",
267
+ evidence=found,
268
+ )
269
+
270
+
271
+ # --- tests/skipped-test ----------------------------------------------------------------
272
+
273
+ _JS_SKIP = re.compile(
274
+ _JS_NAMES + _JS_CHAIN + r"\.(?P<kind>skip|todo)(?P<each>\.each)?\s{0,4}(?P<open>[(`])"
275
+ )
276
+ _JS_XSKIP = re.compile(
277
+ r"(?<![\w$.])(?:xit|xdescribe|xtest|xcontext|xspecify)\s{0,4}\(\s{0,4}[\"'`]"
278
+ )
279
+ _JS_ALWAYS = re.compile(r"(?:true|1)\b")
280
+ _PY_SKIP = re.compile(
281
+ r"(?<![\w.])(?:pytest\.mark\.skip\b"
282
+ r"|pytest\.mark\.skipif\s{0,4}\(\s{0,4}(?:True|1)\b"
283
+ r"|unittest\.skip\b"
284
+ r"|unittest\.skipIf\s{0,4}\(\s{0,4}(?:True|1)\b"
285
+ r"|unittest\.skipUnless\s{0,4}\(\s{0,4}(?:False|0)\b)"
286
+ )
287
+ _GO_SKIP = re.compile(r"(?<![\w.])(?:t|b|f|tb)\.Skip(?:f|Now)?\s{0,4}\(")
288
+ _RUST_IGNORE = re.compile(r"#\s{0,4}\[\s{0,4}ignore\b")
289
+ _JVM_SKIP = re.compile(r"(?<![\w.$])@(?:Disabled|Ignore)\b")
290
+ _GO_CONDITIONAL = ("if ", "if(", "}", "else", "case ", "default:", "for ", "select ", "switch ")
291
+
292
+
293
+ def _indent(line: str) -> int:
294
+ expanded = line.expandtabs(4)
295
+ return len(expanded) - len(expanded.lstrip())
296
+
297
+
298
+ def _go_unconditional(masked_lines: tuple[str, ...], number: int) -> bool:
299
+ """Is the Go statement on line ``number`` directly in a function body?
300
+
301
+ The nearest earlier non-blank line with less indentation must open a
302
+ ``func`` (or a ``t.Run`` subtest); an ``if``, ``case``, ``for`` or
303
+ ``select`` there, or on the line itself, makes the call conditional.
304
+ """
305
+ line = masked_lines[number - 1]
306
+ if line.strip().startswith(_GO_CONDITIONAL):
307
+ return False
308
+ width = _indent(line)
309
+ for k in range(number - 2, max(number - 1000, 0) - 1, -1):
310
+ row = masked_lines[k]
311
+ if row.strip() and _indent(row) < width:
312
+ head = row.strip()
313
+ return head.startswith("func ") or (".Run(" in head and "func(" in head)
314
+ return False
315
+
316
+
317
+ def _js_skip_conditional(m: re.Match[str], masked: str) -> bool:
318
+ """``test.skip(condition, ...)``: Playwright's conditional skip, not a skipped test."""
319
+ if m.group("kind") != "skip" or m.group("name") != "test" or m.group("chain"):
320
+ return False
321
+ if m.group("each") or m.group("open") == "`":
322
+ return False
323
+ rest = masked[m.end() :].lstrip()
324
+ if not rest or rest[0] in "\"'`)":
325
+ return False
326
+ return _JS_ALWAYS.match(rest) is None
327
+
328
+
329
+ def _python_module_skips(ctx: FileContext) -> Iterator[Hit]:
330
+ """``pytest.skip(...)`` statements at module level: the whole module is skipped."""
331
+ tree = ctx.python_ast
332
+ if tree is None:
333
+ return
334
+ for stmt in tree.body:
335
+ call = stmt.value if isinstance(stmt, ast.Expr) else None
336
+ if (
337
+ isinstance(call, ast.Call)
338
+ and isinstance(call.func, ast.Attribute)
339
+ and call.func.attr == "skip"
340
+ and isinstance(call.func.value, ast.Name)
341
+ and call.func.value.id == "pytest"
342
+ ):
343
+ yield Hit(
344
+ stmt.lineno,
345
+ end_line=stmt.end_lineno,
346
+ message="Skipped test module: pytest.skip at module level",
347
+ evidence="pytest.skip",
348
+ )
349
+
350
+
351
+ def _skip_patterns(language: str) -> tuple[re.Pattern[str], ...]:
352
+ if language in _JS:
353
+ return (_JS_SKIP, _JS_XSKIP)
354
+ return {
355
+ "python": (_PY_SKIP,),
356
+ "go": (_GO_SKIP,),
357
+ "rust": (_RUST_IGNORE,),
358
+ "java": (_JVM_SKIP,),
359
+ "kotlin": (_JVM_SKIP,),
360
+ }.get(language, ())
361
+
362
+
363
+ @rule(
364
+ id="tests/skipped-test",
365
+ severity="warning",
366
+ title="Test skipped",
367
+ languages={"javascript", "typescript", "python", "go", "rust", "java", "kotlin"},
368
+ scope="line",
369
+ rationale=(
370
+ "A skipped test stops guarding the behaviour it covers, and skips added to get a "
371
+ "change through CI are rarely removed again."
372
+ ),
373
+ hint=(
374
+ "Fix the test instead of skipping it, or skip it only under a stated condition "
375
+ "and track the follow-up."
376
+ ),
377
+ tags={"tests"},
378
+ )
379
+ def skipped_test(ctx: FileContext) -> Iterator[Hit]:
380
+ """Unconditional skips added to test code.
381
+
382
+ - JavaScript/TypeScript: ``.skip`` and ``.todo`` on the test functions
383
+ :func:`focused_test` knows, and ``xit``/``xdescribe``/``xtest`` with a
384
+ string title. Playwright's conditional ``test.skip(condition, reason)``
385
+ and ``it.skipIf(...)`` are not hits; ``test.skip()`` and
386
+ ``test.skip(true)`` are.
387
+ - Python: ``pytest.mark.skip``, ``skipif(True)``, ``unittest.skip``,
388
+ ``skipIf(True)``/``skipUnless(False)``, and ``pytest.skip()`` as a
389
+ module-level statement. ``pytest.skip()`` inside a test or fixture is
390
+ usually behind a condition and is not reported.
391
+ - Go: ``t.Skip``/``Skipf``/``SkipNow`` directly in a function body (not
392
+ under ``if``, ``case``, ``for`` or ``select``).
393
+ - Rust: ``#[ignore]``. Java/Kotlin (a refinement): JUnit ``@Disabled``
394
+ and ``@Ignore``.
395
+
396
+ Only test code counts: test-class files, Cypress specs and Rust/Go
397
+ in-file test regions.
398
+ """
399
+ language = ctx.language
400
+ patterns = _skip_patterns(language)
401
+ masked_lines: tuple[str, ...] = ()
402
+ for number, text, masked in _code_windows(ctx):
403
+ if not _in_test(ctx, number):
404
+ continue
405
+ for pattern in patterns:
406
+ for m in pattern.finditer(masked):
407
+ if pattern is _JS_SKIP and _js_skip_conditional(m, masked):
408
+ continue
409
+ if pattern is _GO_SKIP:
410
+ masked_lines = masked_lines or git_lines(ctx.masked_code)
411
+ if not _go_unconditional(masked_lines, number):
412
+ continue
413
+ found = _found(text, m)
414
+ yield Hit(
415
+ number,
416
+ column=text.column(m.start()),
417
+ message=f"Skipped test: {found}",
418
+ evidence=found,
419
+ )
420
+ if language == "python" and is_test_file(ctx) and ctx.added_lines:
421
+ yield from _python_module_skips(ctx)
422
+
423
+
424
+ # --- tests/tautological-assertion --------------------------------------------------------
425
+
426
+ # A side-effect-free operand: a literal, or a dotted name (no calls, no indexing).
427
+ _V = (
428
+ r"(?:true|false|null|undefined|nil|-?\d{1,20}(?:\.\d{1,20})?"
429
+ r"|[A-Za-z_$][\w$]{0,60}(?:\.[A-Za-z_$][\w$]{0,60}){0,5}"
430
+ r"|\"[^\"\\\n]{0,80}\"|'[^'\\\n]{0,80}')"
431
+ )
432
+ _S = r"\s{0,4}"
433
+ _TAUTOLOGIES: dict[str, tuple[re.Pattern[str], ...]] = {
434
+ "js": (
435
+ re.compile(
436
+ rf"(?<![\w$.])expect\({_S}(?P<v>{_V}){_S}\)"
437
+ rf"\.(?:toBe|toEqual|toStrictEqual|to\.equal|to\.eql|to\.deep\.equal)"
438
+ rf"\({_S}(?P=v){_S}\)"
439
+ ),
440
+ re.compile(rf"(?<![\w$.])expect\({_S}(?:true|1){_S}\)\.(?:toBeTruthy\(|to\.be\.true\b)"),
441
+ re.compile(
442
+ rf"(?<![\w$.])expect\({_S}(?:false|0|null){_S}\)\.(?:toBeFalsy\(|to\.be\.false\b)"
443
+ ),
444
+ re.compile(rf"(?<![\w$.])assert(?:\.ok)?\({_S}true{_S}[,)]"),
445
+ re.compile(
446
+ rf"(?<![\w$.])assert\.(?:equal|strictEqual|deepEqual|deepStrictEqual)"
447
+ rf"\({_S}(?P<v>{_V}){_S},{_S}(?P=v){_S}[,)]"
448
+ ),
449
+ ),
450
+ "rust": (
451
+ re.compile(rf"(?<![\w:])(?:debug_)?assert!\({_S}true{_S}[,)]"),
452
+ re.compile(rf"(?<![\w:])(?:debug_)?assert_eq!\({_S}(?P<v>{_V}){_S},{_S}(?P=v){_S}[,)]"),
453
+ ),
454
+ "go": (
455
+ re.compile(rf"(?<![\w.])(?:assert|require)\.True\({_S}\w{{1,20}}{_S},{_S}true{_S}[,)]"),
456
+ re.compile(
457
+ rf"(?<![\w.])(?:assert|require)\.(?:Equal|EqualValues|Exactly)"
458
+ rf"\({_S}\w{{1,20}}{_S},{_S}(?P<v>{_V}){_S},{_S}(?P=v){_S}[,)]"
459
+ ),
460
+ ),
461
+ "jvm": (
462
+ re.compile(rf"(?<![\w$])assertTrue\({_S}true{_S}[,)]"),
463
+ re.compile(rf"(?<![\w$])assertFalse\({_S}false{_S}[,)]"),
464
+ re.compile(rf"(?<![\w$])assertEquals\({_S}(?P<v>{_V}){_S},{_S}(?P=v){_S}[,)]"),
465
+ re.compile(rf"(?<![\w$])assertThat\({_S}(?P<v>{_V}){_S}\)\.isEqualTo\({_S}(?P=v){_S}\)"),
466
+ re.compile(rf"(?<![\w$])assertThat\({_S}true{_S}\)\.isTrue\("),
467
+ ),
468
+ }
469
+ _UNITTEST_SAME = frozenset(
470
+ {
471
+ "assertEqual",
472
+ "assertEquals",
473
+ "assertIs",
474
+ "assertAlmostEqual",
475
+ "assertCountEqual",
476
+ "assertListEqual",
477
+ "assertDictEqual",
478
+ "assertTupleEqual",
479
+ "assertSetEqual",
480
+ "assertSequenceEqual",
481
+ "assertMultiLineEqual",
482
+ "assertGreaterEqual",
483
+ "assertLessEqual",
484
+ }
485
+ )
486
+ _IMPURE = (
487
+ ast.Call,
488
+ ast.Await,
489
+ ast.Yield,
490
+ ast.YieldFrom,
491
+ ast.NamedExpr,
492
+ ast.ListComp,
493
+ ast.SetComp,
494
+ ast.DictComp,
495
+ ast.GeneratorExp,
496
+ ast.Lambda,
497
+ )
498
+
499
+
500
+ def _same(a: ast.expr, b: ast.expr) -> bool:
501
+ """Are ``a`` and ``b`` the same side-effect-free expression?"""
502
+ if any(isinstance(n, _IMPURE) for n in ast.walk(a)):
503
+ return False
504
+ return ast.dump(a) == ast.dump(b)
505
+
506
+
507
+ def _always_true(node: ast.expr) -> str | None:
508
+ """Why ``assert node`` can never fail, or ``None``."""
509
+ if isinstance(node, ast.Constant):
510
+ return "asserts a constant" if node.value else None
511
+ if isinstance(node, ast.Tuple) and node.elts:
512
+ return "asserts a non-empty tuple, which is always true"
513
+ if (
514
+ isinstance(node, ast.Compare)
515
+ and len(node.ops) == 1
516
+ and isinstance(node.ops[0], (ast.Eq, ast.Is, ast.LtE, ast.GtE))
517
+ and _same(node.left, node.comparators[0])
518
+ ):
519
+ return "compares an expression with itself"
520
+ return None
521
+
522
+
523
+ def _unittest_tautology(call: ast.Call) -> str | None:
524
+ func = call.func
525
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", None)
526
+ args = call.args
527
+ if name in _UNITTEST_SAME and len(args) >= 2 and _same(args[0], args[1]):
528
+ return "compares an expression with itself"
529
+ if name == "assertTrue" and args and isinstance(args[0], ast.Constant) and args[0].value:
530
+ return "asserts a constant"
531
+ if (
532
+ name in ("assertFalse", "assertIsNone")
533
+ and args
534
+ and isinstance(args[0], ast.Constant)
535
+ and not args[0].value
536
+ ):
537
+ return "asserts a constant"
538
+ return None
539
+
540
+
541
+ def _python_tautologies(ctx: FileContext) -> Iterator[Hit]:
542
+ tree = ctx.python_ast
543
+ if tree is None:
544
+ return
545
+ for node in ast.walk(tree):
546
+ if isinstance(node, ast.Assert):
547
+ why = _always_true(node.test)
548
+ elif isinstance(node, ast.Call):
549
+ why = _unittest_tautology(node)
550
+ else:
551
+ continue
552
+ if why is not None:
553
+ source = ast.unparse(node.test if isinstance(node, ast.Assert) else node)
554
+ yield Hit(
555
+ node.lineno,
556
+ end_line=node.end_lineno,
557
+ message=f"Assertion {why}",
558
+ evidence=_squash(source)[:200],
559
+ )
560
+
561
+
562
+ @rule(
563
+ id="tests/tautological-assertion",
564
+ severity="warning",
565
+ title="Assertion that cannot fail",
566
+ languages={"javascript", "typescript", "python", "go", "rust", "java", "kotlin"},
567
+ scope="line",
568
+ rationale=(
569
+ "An assertion of a constant or of a value against itself always passes, so the "
570
+ "test proves nothing; it is often a placeholder or a typo for the real check."
571
+ ),
572
+ hint="Assert the actual result against an independent expected value.",
573
+ tags={"tests"},
574
+ )
575
+ def tautological_assertion(ctx: FileContext) -> Iterator[Hit]:
576
+ """Assertions that hold whatever the code under test does.
577
+
578
+ - Python (AST): ``assert True``, ``assert 1``, ``assert "text"``, an
579
+ assert of a non-empty tuple (``assert (x, "message")``), ``assert x ==
580
+ x`` / ``x is x`` with the same side-effect-free operand, and unittest
581
+ ``assertEqual(a, a)`` and friends, ``assertTrue(True)``,
582
+ ``assertFalse(False)``. Operands with calls are never the same (``f()
583
+ == f()`` may test determinism).
584
+ - JavaScript/TypeScript: ``expect(v).toBe(v)`` (also ``toEqual``,
585
+ ``toStrictEqual``, chai ``to.equal``), ``expect(true).toBeTruthy()``,
586
+ ``assert(true)``, ``assert.equal(v, v)``.
587
+ - Rust ``assert!(true)``, ``assert_eq!(v, v)``; Go testify
588
+ ``assert.True(t, true)``, ``assert.Equal(t, v, v)``; Java/Kotlin
589
+ ``assertTrue(true)``, ``assertEquals(v, v)``,
590
+ ``assertThat(v).isEqualTo(v)``.
591
+
592
+ ``v`` is a literal or a dotted name; only code counts and only in test
593
+ code (test files, Cypress specs, Rust/Go in-file test regions).
594
+ """
595
+ if ctx.language == "python":
596
+ if is_test_file(ctx) and ctx.added_lines:
597
+ yield from _python_tautologies(ctx)
598
+ return
599
+ patterns = _TAUTOLOGIES.get(_family(ctx.language), ())
600
+ for number, text, masked in _code_windows(ctx):
601
+ if not _in_test(ctx, number):
602
+ continue
603
+ for pattern in patterns:
604
+ for m in pattern.finditer(text):
605
+ if _is_code(text, masked, m.start()) and _is_code(text, masked, m.end() - 1):
606
+ found = _squash(m.group(0))
607
+ yield Hit(
608
+ number,
609
+ column=text.column(m.start()),
610
+ message="Assertion that cannot fail",
611
+ evidence=found,
612
+ )
613
+
614
+
615
+ # --- tests/test-env-branch ---------------------------------------------------------------
616
+
617
+ _NODE_ENV = (
618
+ r"(?:process\.env(?:\.NODE_ENV|\[\s{0,4}(?P<k>[\"'])NODE_ENV(?P=k)\s{0,4}\])"
619
+ r"|import\.meta\.env\.MODE)"
620
+ )
621
+ _TEST_WORD = r"(?P<q>[\"'`])test(?P=q)"
622
+ _ENV_BRANCHES: dict[str, tuple[re.Pattern[str], ...]] = {
623
+ "js": (
624
+ re.compile(rf"(?<![\w$.]){_NODE_ENV}\s{{0,4}}[!=]==?\s{{0,4}}{_TEST_WORD}"),
625
+ re.compile(rf"{_TEST_WORD}\s{{0,4}}[!=]==?\s{{0,4}}{_NODE_ENV}(?![\w$])"),
626
+ ),
627
+ "python": (
628
+ re.compile(
629
+ r"(?P<q>[\"'])_?pytest(?P=q)\s{0,4}(?:not\s{1,4})?in\s{1,4}sys\.modules(?![\w.])"
630
+ ),
631
+ re.compile(r"(?<![\w.])sys\.modules\.get\(\s{0,4}(?P<q>[\"'])_?pytest(?P=q)"),
632
+ ),
633
+ }
634
+ _PYTEST_ENV = "PYTEST_CURRENT_TEST"
635
+ _SUPPORT_DIRS = frozenset(
636
+ {"testing", "testutils", "test_utils", "test-utils", "fixtures", "mocks", "__mocks__", "e2e"}
637
+ )
638
+ _TOOL_CONFIG = re.compile(
639
+ r"(?:\.config|\.conf|\.setup)\.[cm]?[jt]sx?$|^\.[\w.-]{1,40}rc\.[cm]?[jt]s$"
640
+ r"|^(?:setup|noxfile)\.py$"
641
+ )
642
+
643
+
644
+ def _test_support(path: str) -> bool:
645
+ """Source files whose job is test setup: test helpers and tool configs.
646
+
647
+ A ``test`` in the file name (``testing.py``, ``testUtils.ts``), a
648
+ directory such as ``testing/``, ``fixtures/`` or ``__mocks__/``, or a
649
+ tool config (``babel.config.js``, ``.eslintrc.cjs``, ``jest.setup.ts``,
650
+ ``setup.py``) may branch on the test environment by design.
651
+ """
652
+ parts = path.lower().split("/")
653
+ name = parts[-1]
654
+ return (
655
+ "test" in name
656
+ or any(p in _SUPPORT_DIRS for p in parts[:-1])
657
+ or _TOOL_CONFIG.search(name) is not None
658
+ )
659
+
660
+
661
+ @rule(
662
+ id="tests/test-env-branch",
663
+ severity="warning",
664
+ title="Production code branches on the test environment",
665
+ languages={"javascript", "typescript", "python"},
666
+ classes={"source"},
667
+ scope="line",
668
+ rationale=(
669
+ "Code that behaves differently under test makes the tests exercise a path that "
670
+ "production never takes, and the production path goes untested."
671
+ ),
672
+ hint="Inject the dependency or setting the test needs instead of detecting the test run.",
673
+ tags={"tests"},
674
+ )
675
+ def env_branch(ctx: FileContext) -> Iterator[Hit]:
676
+ """Source code that detects a test run.
677
+
678
+ JavaScript/TypeScript: ``process.env.NODE_ENV`` (or
679
+ ``process.env["NODE_ENV"]``, or Vite's ``import.meta.env.MODE``)
680
+ compared with ``'test'`` in either order, ``==``/``===``/``!=``/``!==``.
681
+ Python: ``"pytest" in sys.modules`` (also ``not in`` and
682
+ ``sys.modules.get("pytest")``) and any string literal that is exactly
683
+ ``PYTEST_CURRENT_TEST`` (the variable pytest sets while a test runs).
684
+ Only source-class files run, and test-support source files (see
685
+ :func:`_test_support`) are left out; matches must start and end in code.
686
+ """
687
+ if _test_support(ctx.path):
688
+ return
689
+ family = _family(ctx.language)
690
+ patterns = _ENV_BRANCHES.get(family, ())
691
+ for number, text, masked in _code_windows(ctx):
692
+ for pattern in patterns:
693
+ for m in pattern.finditer(text):
694
+ if _is_code(text, masked, m.start()) and _is_code(text, masked, m.end() - 1):
695
+ found = _squash(m.group(0))
696
+ yield Hit(
697
+ number,
698
+ column=text.column(m.start()),
699
+ message=f"Branch on the test environment: {found}",
700
+ evidence=found,
701
+ )
702
+ if ctx.language == "python" and ctx.added_lines:
703
+ text = ctx.new_text or ""
704
+ index = ctx.line_index
705
+ for span in ctx.strings():
706
+ if text[span.content_start : span.content_end] == _PYTEST_ENV:
707
+ line = index.line_of(span.start)
708
+ yield Hit(
709
+ line,
710
+ message=f"Branch on the test environment: {_PYTEST_ENV}",
711
+ evidence=_PYTEST_ENV,
712
+ )
713
+
714
+
715
+ # --- tests/sleep-in-test -------------------------------------------------------------------
716
+
717
+ _SLEEPS: dict[str, tuple[re.Pattern[str], ...]] = {
718
+ "python": (
719
+ re.compile(r"(?<![\w.])time\.sleep\s{0,4}\("),
720
+ re.compile(r"(?<![\w.])(?:asyncio|trio|anyio|gevent)\.sleep\s{0,4}\((?!\s{0,4}0\s{0,4}\))"),
721
+ ),
722
+ "js": (
723
+ re.compile(
724
+ r"(?<![\w$.])setTimeout\(\s{0,4}(?:resolve|res|r|done|next|ok)\s{0,4},\s{0,4}\w"
725
+ ),
726
+ re.compile(r"\.waitForTimeout\s{0,4}\("),
727
+ re.compile(r"(?<![\w$.])cy\.wait\(\s{0,4}\d"),
728
+ re.compile(r"(?<![\w$.])await\s{1,4}(?:sleep|delay|wait|timeout)\(\s{0,4}\d"),
729
+ ),
730
+ "jvm": (
731
+ re.compile(r"(?<![\w$])Thread\.sleep\s{0,4}\("),
732
+ re.compile(r"(?<![\w$])TimeUnit\.[A-Z]{1,12}\.sleep\s{0,4}\("),
733
+ ),
734
+ "go": (re.compile(r"(?<![\w.])time\.Sleep\s{0,4}\("),),
735
+ "rust": (
736
+ re.compile(r"(?<![\w])thread::sleep\s{0,4}\("),
737
+ re.compile(r"(?<![\w])(?:tokio::)?time::sleep\s{0,4}\("),
738
+ ),
739
+ }
740
+
741
+
742
+ @rule(
743
+ id="tests/sleep-in-test",
744
+ severity="note",
745
+ title="Fixed sleep in a test",
746
+ languages={"javascript", "typescript", "python", "go", "rust", "java", "kotlin"},
747
+ scope="line",
748
+ rationale=(
749
+ "A fixed sleep makes a test slow and still flaky: it waits too long on a fast "
750
+ "machine and not long enough on a loaded CI runner."
751
+ ),
752
+ hint="Wait for the condition itself (poll with a timeout, an event, fake timers or a "
753
+ "clock you control).",
754
+ tags={"tests", "flaky"},
755
+ )
756
+ def sleep_in_test(ctx: FileContext) -> Iterator[Hit]:
757
+ """Fixed waits in test code.
758
+
759
+ Python ``time.sleep`` and ``asyncio``/``trio``/``anyio``/``gevent``
760
+ ``.sleep`` (``sleep(0)``, a yield to the event loop, is fine);
761
+ JavaScript ``setTimeout(resolve, ...)`` promises, Playwright
762
+ ``waitForTimeout``, Cypress ``cy.wait(<number>)`` and ``await
763
+ sleep(<number>)``-style helpers; Java/Kotlin ``Thread.sleep`` and
764
+ ``TimeUnit.X.sleep``; Go ``time.Sleep``; Rust ``thread::sleep`` and
765
+ ``time::sleep``. Only code in test code counts.
766
+ """
767
+ patterns = _SLEEPS.get(_family(ctx.language), ())
768
+ for number, text, masked in _code_windows(ctx):
769
+ if not _in_test(ctx, number):
770
+ continue
771
+ for pattern in patterns:
772
+ for m in pattern.finditer(masked):
773
+ found = _found(text, m).split("(")[0]
774
+ yield Hit(
775
+ number,
776
+ column=text.column(m.start()),
777
+ message=f"Fixed sleep in a test: {found}",
778
+ evidence=found,
779
+ )
780
+
781
+
782
+ # --- Test shapes: assertions and test functions of one side ----------------------------
783
+
784
+
785
+ @dataclass(frozen=True, slots=True)
786
+ class Shape:
787
+ """The assertions and test functions of one side of a test file."""
788
+
789
+ asserts: tuple[int, ...] = ()
790
+ """Line of each assertion, one entry per assertion."""
791
+ tests: tuple[tuple[str, int], ...] = field(default=())
792
+ """``(name, line)`` of each test function or test case."""
793
+
794
+
795
+ _ASSERTS: dict[str, tuple[re.Pattern[str], ...]] = {
796
+ "js": (
797
+ re.compile(r"(?<![\w$.])expect\s{0,4}\("),
798
+ re.compile(r"(?<![\w$.])assert(?:\.\w{1,30})?\s{0,4}\("),
799
+ re.compile(r"\.should\s{0,4}\("),
800
+ ),
801
+ "go": (
802
+ re.compile(r"(?<![\w.])(?:t|b|tb|f)\.(?:Error|Errorf|Fatal|Fatalf|Fail|FailNow)\s{0,4}\("),
803
+ re.compile(r"(?<![\w.])(?:assert|require)\.[A-Z]\w{0,40}\s{0,4}\("),
804
+ ),
805
+ "rust": (re.compile(r"(?<![\w:])(?:debug_)?assert(?:_eq|_ne|_matches)?!\s{0,4}[(\[{]"),),
806
+ "jvm": (
807
+ re.compile(r"(?<![\w$.])(?:Assert\.|Assertions\.)?assert[A-Z]\w{0,40}\s{0,4}\("),
808
+ re.compile(r"(?<![\w$.])assert\s"),
809
+ re.compile(r"\sshould(?:Be|NotBe|Contain|Throw)\b"),
810
+ ),
811
+ }
812
+ _JS_TEST = re.compile(
813
+ r"(?<![\w$.])(?:it|test|specify)(?:\.(?:only|skip|concurrent|serial|fails|todo)){0,2}"
814
+ r"\s{0,4}\(\s{0,4}(?P<q>[\"'`])"
815
+ )
816
+ _GO_TEST = re.compile(r"func\s{1,4}(?P<n>(?:Test|Benchmark|Fuzz)\w{0,200})\s{0,4}\(")
817
+ _RUST_TEST = re.compile(r"#\s{0,4}\[\s{0,4}(?:[\w:]{1,60}::)?test\b")
818
+ _RUST_FN = re.compile(r"(?<![\w])fn\s{1,4}(?P<n>\w{1,200})")
819
+ _JVM_TEST = re.compile(r"(?<![\w.$])@(?:Test|ParameterizedTest|RepeatedTest)\b")
820
+ _JVM_FN = re.compile(r"(?<![\w$])(?:fun|void)\s{1,4}(?P<n>`[^`\n]{1,200}`|[\w$]{1,200})\s{0,4}\(")
821
+ _LOOKAHEAD = 10
822
+
823
+
824
+ def _python_shape(tree: ast.Module) -> Shape:
825
+ asserts: list[int] = []
826
+ for node in ast.walk(tree):
827
+ if isinstance(node, ast.Assert):
828
+ asserts.append(node.lineno)
829
+ elif isinstance(node, ast.Call):
830
+ func = node.func
831
+ name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
832
+ if name.startswith("assert") or (
833
+ name in ("raises", "warns")
834
+ and isinstance(func, ast.Attribute)
835
+ and isinstance(func.value, ast.Name)
836
+ and func.value.id == "pytest"
837
+ ):
838
+ asserts.append(node.lineno)
839
+ tests: list[tuple[str, int]] = []
840
+
841
+ def visit(body: list[ast.stmt], prefix: str) -> None:
842
+ for stmt in body:
843
+ if isinstance(stmt, (ast.FunctionDef, ast.AsyncFunctionDef)):
844
+ if stmt.name.startswith("test"):
845
+ tests.append((prefix + stmt.name, stmt.lineno))
846
+ elif isinstance(stmt, ast.ClassDef):
847
+ visit(stmt.body, f"{prefix}{stmt.name}.")
848
+
849
+ visit(tree.body, "")
850
+ return Shape(tuple(sorted(asserts)), tuple(tests))
851
+
852
+
853
+ def _test_after(
854
+ masked: tuple[str, ...], text: tuple[str, ...], k: int, pattern: re.Pattern[str]
855
+ ) -> tuple[str, int] | None:
856
+ """The first function ``pattern`` names on line ``k`` (0-based) or the next few."""
857
+ for j in range(k, min(k + _LOOKAHEAD, len(masked))):
858
+ m = pattern.search(masked[j])
859
+ if m is not None:
860
+ named = pattern.search(text[j], m.start())
861
+ name = named.group("n") if named is not None else m.group("n")
862
+ return name, j + 1
863
+ return None
864
+
865
+
866
+ def shape_of(text: str, language: str, path: str, tree: ast.Module | None) -> Shape | None:
867
+ """Assertions and tests of ``text``; ``None`` for another language or a Python parse failure."""
868
+ if language == "python":
869
+ return None if tree is None else _python_shape(tree)
870
+ family = _family(language)
871
+ if family not in _ASSERTS:
872
+ return None
873
+ masked = git_lines(_mask(text, language, path))
874
+ lines = git_lines(text)
875
+ asserts: list[int] = []
876
+ tests: list[tuple[str, int]] = []
877
+ for k, row in enumerate(masked):
878
+ for pattern in _ASSERTS[family]:
879
+ asserts.extend(k + 1 for _ in pattern.finditer(row))
880
+ if family == "js":
881
+ for m in _JS_TEST.finditer(row):
882
+ source = lines[k]
883
+ close = source.find(m.group("q"), m.end())
884
+ title = source[m.end() : close] if close >= 0 else source[m.end() :].strip()
885
+ tests.append((title, k + 1))
886
+ elif family == "go":
887
+ m = _GO_TEST.match(row)
888
+ if m is not None:
889
+ tests.append((m.group("n"), k + 1))
890
+ else:
891
+ marker = _RUST_TEST if family == "rust" else _JVM_TEST
892
+ if marker.search(row):
893
+ found = _test_after(masked, lines, k, _RUST_FN if family == "rust" else _JVM_FN)
894
+ if found is not None:
895
+ tests.append(found)
896
+ return Shape(tuple(asserts), tuple(tests))
897
+
898
+
899
+ def _side_shape(ctx: FileContext, side: Side) -> Shape | None:
900
+ if side is Side.OLD:
901
+ text, tree, path = ctx.old_text, None, ctx.old_path or ctx.path
902
+ if ctx.language == "python" and text:
903
+ tree = ctx.old_python_ast
904
+ else:
905
+ text, path = ctx.new_text, ctx.path
906
+ tree = ctx.python_ast if ctx.language == "python" and text else None
907
+ if not text:
908
+ return Shape()
909
+ return shape_of(text, ctx.language, path, tree)
910
+
911
+
912
+ # --- tests/assertion-removed ---------------------------------------------------------------
913
+
914
+
915
+ @rule(
916
+ id="tests/assertion-removed",
917
+ severity="warning",
918
+ title="Assertions removed from a test file",
919
+ languages={"javascript", "typescript", "python", "go", "rust", "java", "kotlin"},
920
+ scope="file",
921
+ rationale=(
922
+ "Fewer assertions with the same tests means the tests check less than before; "
923
+ "deleting the check that failed is a common way to make a change pass."
924
+ ),
925
+ hint="Keep the assertion, or replace it with an equivalent check, unless the behaviour "
926
+ "it guarded is gone.",
927
+ tags={"tests"},
928
+ )
929
+ def assertion_removed(ctx: FileContext) -> Iterator[Hit]:
930
+ """A modified test file has fewer assertions and no fewer tests than before.
931
+
932
+ Assertions: Python ``assert`` statements, calls of any ``assert*`` name
933
+ (``self.assertEqual``, ``mock.assert_called_once_with``, helpers) and
934
+ ``pytest.raises``/``pytest.warns``; JavaScript ``expect(``,
935
+ ``assert(``/``assert.x(`` and ``.should(``; Go ``t.Error``/``Fatal``
936
+ (and ``f``/``Now`` variants) and testify ``assert.``/``require.``; Rust
937
+ ``assert!``-family macros; Java/Kotlin ``assertX(``, ``assert`` and
938
+ kotest ``shouldBe``. Tests: Python ``test*`` functions and methods,
939
+ JavaScript ``it``/``test`` calls, Go ``Test``/``Benchmark``/``Fuzz``
940
+ functions, Rust ``#[test]`` and JUnit ``@Test`` functions.
941
+
942
+ The whole old and new sides are compared, so a moved assertion is not a
943
+ loss. Fewer tests is the job of ``tests/test-deleted``. Reported once, at
944
+ the first removed line holding an old assertion (old side).
945
+ """
946
+ if ctx.change.status not in (FileStatus.MODIFIED, FileStatus.RENAMED):
947
+ return
948
+ if not is_test_file(ctx) or not ctx.removed_lines or not ctx.old_text or not ctx.new_text:
949
+ return
950
+ old = _side_shape(ctx, Side.OLD)
951
+ new = _side_shape(ctx, Side.NEW)
952
+ if old is None or new is None or not new.tests or len(new.tests) < len(old.tests):
953
+ return
954
+ lost = len(old.asserts) - len(new.asserts)
955
+ if lost <= 0:
956
+ return
957
+ removed = ctx.removed_lines
958
+ line = next((n for n in old.asserts if n in removed), min(removed))
959
+ count = "1 assertion" if lost == 1 else f"{lost} assertions"
960
+ tests = "1 test remains" if len(new.tests) == 1 else f"{len(new.tests)} tests remain"
961
+ yield Hit(
962
+ line,
963
+ side=Side.OLD,
964
+ message=f"{count} removed ({len(old.asserts)} before, {len(new.asserts)} now) "
965
+ f"while {tests}",
966
+ )
967
+
968
+
969
+ # --- tests/test-deleted ----------------------------------------------------------------------
970
+
971
+ _DEF = re.compile(
972
+ r"(?<![\w$])(?:def|class|function|func|fn|fun|interface|struct|enum|trait|type)\s{1,4}"
973
+ r"(?:\([^()\n]{0,80}\)\s{0,4})?(?P<n>[A-Za-z_$][\w$]{0,100})"
974
+ )
975
+ _CONST_FN = re.compile(
976
+ r"(?<![\w$])(?:const|let|var)\s{1,4}(?P<n>[A-Za-z_$][\w$]{0,100})\s{0,4}=\s{0,4}"
977
+ r"(?:async\s{1,4})?(?:function\b|\(|[A-Za-z_$][\w$]{0,40}\s{0,4}=>)"
978
+ )
979
+ _METHOD = re.compile(
980
+ r"(?<![\w$])(?:public|private|protected|internal|static|override)\s[\w<>\[\], ?]{0,120}?"
981
+ r"\s(?P<n>[A-Za-z_$][\w$]{0,100})\s{0,4}\("
982
+ )
983
+ _MIN_NAME = 4
984
+
985
+
986
+ def _norm(name: str) -> str:
987
+ return "".join(c for c in name.lower() if c.isalnum())
988
+
989
+
990
+ def _test_norm(name: str) -> str:
991
+ plain = _norm(name.rsplit(".", 1)[-1])
992
+ return plain.removeprefix("test")
993
+
994
+
995
+ def _stem(path: str) -> str:
996
+ """``test_cart.py``, ``cart_test.go``, ``cart.test.ts`` and ``Cart.spec.js`` give ``cart``."""
997
+ name = _basename(path).split(".", 1)[0].lower()
998
+ name = name.removeprefix("test_").removesuffix("_test").removesuffix("test")
999
+ return _norm(name.removesuffix("spec")) or _norm(name)
1000
+
1001
+
1002
+ def _defs(text: str | None, language: str, path: str) -> set[str]:
1003
+ if not text:
1004
+ return set()
1005
+ names: set[str] = set()
1006
+ for row in git_lines(_mask(text, language, path)):
1007
+ for pattern in (_DEF, _CONST_FN, _METHOD):
1008
+ names.update(_norm(m.group("n")) for m in pattern.finditer(row))
1009
+ return names
1010
+
1011
+
1012
+ def _plain(name: str) -> str:
1013
+ return name.rsplit(".", 1)[-1]
1014
+
1015
+
1016
+ @dataclass(slots=True)
1017
+ class _Deletions:
1018
+ """What the rest of the change says about removed tests."""
1019
+
1020
+ defs: set[str] = field(default_factory=set)
1021
+ stems: set[str] = field(default_factory=set)
1022
+ added_tests: Counter[str] = field(default_factory=Counter)
1023
+ added_names: set[str] = field(default_factory=set)
1024
+
1025
+ def explains(self, name: str) -> bool:
1026
+ """Was test ``name`` moved elsewhere, or its code deleted in this change?"""
1027
+ if self.added_tests[_plain(name)] > 0:
1028
+ self.added_tests[_plain(name)] -= 1
1029
+ return True
1030
+ target = _test_norm(name)
1031
+ return any(len(d) >= _MIN_NAME and d in target for d in self.defs)
1032
+
1033
+
1034
+ def _source_deletions(ctx: ChangeContext) -> _Deletions:
1035
+ found = _Deletions()
1036
+ for f in ctx.files:
1037
+ if f.kind is not FileKind.TEXT or f.language not in TESTED_LANGUAGES:
1038
+ continue
1039
+ if is_test_file(f):
1040
+ continue
1041
+ old_path = f.old_path or f.path
1042
+ if f.change.status is FileStatus.DELETED:
1043
+ found.stems.add(_stem(f.path))
1044
+ if f.old_text and f.removed_lines:
1045
+ found.defs |= _defs(f.old_text, f.language, old_path) - _defs(
1046
+ f.new_text, f.language, f.path
1047
+ )
1048
+ return found
1049
+
1050
+
1051
+ @rule(
1052
+ id="tests/test-deleted",
1053
+ severity="warning",
1054
+ title="Tests deleted",
1055
+ scope="change",
1056
+ rationale=(
1057
+ "Deleting a test while the code it covered stays removes the only check of that "
1058
+ "behaviour; it is also a quick way to silence a failing test."
1059
+ ),
1060
+ hint="Keep or fix the test, or delete the code it covered in the same change.",
1061
+ tags={"tests"},
1062
+ )
1063
+ def deleted_tests(ctx: ChangeContext) -> Iterator[Hit]:
1064
+ """Test files deleted, or tests removed from a test file, while the tested code stays.
1065
+
1066
+ A deleted test-class file counts when it held tests (see
1067
+ :func:`shape_of`); fixture and helper files without tests do not. In a
1068
+ modified or renamed test file, tests count as removed only when the file
1069
+ has fewer tests than before (renamed tests are not deletions). A removed
1070
+ test is explained, and not reported, when the change adds a test of the
1071
+ same name in another file (moved), or deletes a source definition whose
1072
+ name (normalized, at least four characters) is part of the test's name. A
1073
+ deleted test file is also explained by an added test file with the same
1074
+ name or a deleted source file with the same stem (``test_cart.py`` and
1075
+ ``cart.py``). Git renames are never deletions.
1076
+ """
1077
+ tests = [f for f in ctx.files if f.kind is FileKind.TEXT and is_test_file(f) and f.old_text]
1078
+ if not tests:
1079
+ return
1080
+ context = _source_deletions(ctx)
1081
+ shapes: dict[str, tuple[Shape | None, Shape | None]] = {}
1082
+ added_files: set[str] = set()
1083
+ for f in ctx.files:
1084
+ if f.kind is not FileKind.TEXT or not is_test_file(f) or not f.new_text:
1085
+ continue
1086
+ if f.change.status is FileStatus.ADDED:
1087
+ added_files.add(_basename(f.path))
1088
+ old = _side_shape(f, Side.OLD) if f.old_text else Shape()
1089
+ new = _side_shape(f, Side.NEW)
1090
+ shapes[f.path] = (old, new)
1091
+ if old is not None and new is not None:
1092
+ gained = Counter(_plain(n) for n, _ in new.tests)
1093
+ gained.subtract(_plain(n) for n, _ in old.tests)
1094
+ context.added_tests.update({k: v for k, v in gained.items() if v > 0})
1095
+ for f in tests:
1096
+ if f.change.status is FileStatus.DELETED:
1097
+ old = _side_shape(f, Side.OLD)
1098
+ if old is None or not old.tests:
1099
+ continue
1100
+ if _basename(f.path) in added_files or _stem(f.path) in context.stems:
1101
+ continue
1102
+ left = [name for name, _ in old.tests if not context.explains(name)]
1103
+ if left:
1104
+ count = "1 test" if len(left) == 1 else f"{len(left)} tests"
1105
+ yield Hit(None, path=f.path, message=f"Test file deleted with {count}")
1106
+ continue
1107
+ old, new = shapes.get(f.path, (None, None))
1108
+ if old is None or new is None or len(new.tests) >= len(old.tests):
1109
+ continue
1110
+ remaining = Counter(n for n, _ in new.tests)
1111
+ missing: list[tuple[str, int]] = []
1112
+ for name, line in old.tests:
1113
+ if remaining[name] > 0:
1114
+ remaining[name] -= 1
1115
+ else:
1116
+ missing.append((name, line))
1117
+ left = [(n, line) for n, line in missing if not context.explains(n)]
1118
+ removed = f.removed_lines
1119
+ anchor = next((line for _, line in left if line in removed), None)
1120
+ if anchor is None:
1121
+ continue
1122
+ lost = min(len(left), len(old.tests) - len(new.tests))
1123
+ count = "1 test" if lost == 1 else f"{lost} tests"
1124
+ yield Hit(anchor, side=Side.OLD, path=f.path, message=f"{count} removed from this file")
1125
+
1126
+
1127
+ # --- tests/coverage-threshold-lowered -------------------------------------------------------
1128
+
1129
+ _INI_FILES = frozenset({"setup.cfg", ".coveragerc", "tox.ini", "pytest.ini"})
1130
+ _JSON_RC = frozenset({".nycrc", ".nycrc.json", ".c8rc", ".c8rc.json", "jest.config.json"})
1131
+ _YAML_RC = frozenset({".nycrc.yml", ".nycrc.yaml", ".c8rc.yml", ".c8rc.yaml"})
1132
+ _CODECOV = frozenset({"codecov.yml", "codecov.yaml", ".codecov.yml", ".codecov.yaml"})
1133
+ _JS_CONFIG = re.compile(r"^(?:jest|vitest|vite)\.config\.[cm]?[jt]s$")
1134
+ _CLI_LANGUAGES = frozenset({"yaml", "text", "toml", "shell"})
1135
+ _METRICS = frozenset({"branches", "functions", "lines", "statements"})
1136
+ _CHECK = "check-coverage"
1137
+ _FIXTURE_DIRS = frozenset({"tests", "test", "fixtures", "testdata", "__tests__"})
1138
+
1139
+ _NUMBER = r"(?P<v>-?\d{1,6}(?:\.\d{1,6})?)"
1140
+ _INI_FAIL_UNDER = re.compile(rf"^\s{{0,40}}fail_under\s{{0,4}}[=:]\s{{0,4}}{_NUMBER}")
1141
+ _CLI_FAIL_UNDER = re.compile(rf"--(?P<k>cov-fail-under|fail-under)(?:=|\s{{1,4}}){_NUMBER}")
1142
+ _TOML_FAIL_UNDER = re.compile(r"^\s{0,40}fail_under\s{0,4}=")
1143
+ _JS_BLOCK = re.compile(r"(?<![\w$])(?:coverageThreshold|thresholds)\s{0,4}:\s{0,4}\{")
1144
+ _JS_METRIC = re.compile(
1145
+ rf"(?<![\w$])(?P<k>branches|functions|lines|statements)\s{{0,4}}:\s{{0,4}}{_NUMBER}(?![\w.])"
1146
+ )
1147
+
1148
+
1149
+ @dataclass(frozen=True, slots=True)
1150
+ class _Threshold:
1151
+ value: float | None
1152
+ """``None`` when the value is no longer a number (codecov ``auto``)."""
1153
+ line: int | None
1154
+ inverted: bool = False
1155
+ """Higher is weaker (codecov ``threshold``, the allowed drop)."""
1156
+
1157
+
1158
+ _Thresholds = dict[tuple[object, ...], _Threshold]
1159
+
1160
+
1161
+ def _num(value: object) -> float | None:
1162
+ if isinstance(value, bool):
1163
+ return 1.0 if value else 0.0
1164
+ if isinstance(value, (int, float)):
1165
+ return float(value)
1166
+ if isinstance(value, str):
1167
+ try:
1168
+ return float(value.strip().removesuffix("%"))
1169
+ except ValueError:
1170
+ return 1.0 if value.strip() == "true" else 0.0 if value.strip() == "false" else None
1171
+ return None
1172
+
1173
+
1174
+ def _key_line(lines: tuple[str, ...], path: tuple[object, ...]) -> int | None:
1175
+ """Line of the last key of ``path``, finding each key after the previous one.
1176
+
1177
+ Works on JSON and YAML block style: ``"key":``, ``'key':`` or ``key:``.
1178
+ """
1179
+ k = 0
1180
+ for key in path:
1181
+ if not isinstance(key, str):
1182
+ continue
1183
+ pattern = re.compile(r"(?:^|[\s{,])[\"']?" + re.escape(key) + r"[\"']?\s{0,4}:")
1184
+ while k < len(lines) and pattern.search(lines[k]) is None:
1185
+ k += 1
1186
+ if k == len(lines):
1187
+ return None
1188
+ return k + 1
1189
+
1190
+
1191
+ def _collect(
1192
+ data: object, path: tuple[object, ...], lines: tuple[str, ...], out: _Thresholds
1193
+ ) -> None:
1194
+ """Every numeric leaf under ``data`` (a coverageThreshold object)."""
1195
+ if isinstance(data, dict):
1196
+ for key, value in data.items():
1197
+ _collect(value, (*path, str(key)), lines, out)
1198
+ elif not isinstance(data, (list, str)) and _num(data) is not None:
1199
+ out[path] = _Threshold(_num(data), _key_line(lines, path))
1200
+
1201
+
1202
+ def _rc_thresholds(
1203
+ data: object, path: tuple[object, ...], lines: tuple[str, ...], out: _Thresholds
1204
+ ) -> None:
1205
+ """nyc / c8 options: the four metrics and ``check-coverage``."""
1206
+ if not isinstance(data, dict):
1207
+ return
1208
+ for key in sorted(_METRICS | {_CHECK}):
1209
+ if key in data and _num(data[key]) is not None:
1210
+ out[(*path, key)] = _Threshold(_num(data[key]), _key_line(lines, (*path, key)))
1211
+
1212
+
1213
+ def _yaml_data(ctx: FileContext, side: Side) -> object:
1214
+ result = ctx.yaml if side is Side.NEW else ctx.old_yaml
1215
+ if result is None or not result.ok or not result.documents:
1216
+ return None
1217
+ return to_python(result.documents[0].root)
1218
+
1219
+
1220
+ def _line_scan(lines: tuple[str, ...], ini: bool, out: _Thresholds) -> None:
1221
+ seen: Counter[str] = Counter()
1222
+ for number, row in enumerate(lines, start=1):
1223
+ stripped = row.lstrip()
1224
+ if stripped.startswith(("#", ";")) and ini:
1225
+ continue
1226
+ m = _INI_FAIL_UNDER.match(row) if ini else None
1227
+ if m is not None:
1228
+ out[("fail_under", seen["fail_under"])] = _Threshold(float(m.group("v")), number)
1229
+ seen["fail_under"] += 1
1230
+ for m in _CLI_FAIL_UNDER.finditer(row):
1231
+ key = "--" + m.group("k")
1232
+ out[(key, seen[key])] = _Threshold(float(m.group("v")), number)
1233
+ seen[key] += 1
1234
+
1235
+
1236
+ def _js_scan(masked: tuple[str, ...], out: _Thresholds) -> None:
1237
+ """Metric values inside ``coverageThreshold: {...}`` / ``thresholds: {...}`` blocks."""
1238
+ depth = 0
1239
+ region: int | None = None
1240
+ seen: Counter[str] = Counter()
1241
+ for number, row in enumerate(masked, start=1):
1242
+ block = _JS_BLOCK.search(row)
1243
+ start = 0 if region is not None and depth >= region else None
1244
+ if block is not None and region is None:
1245
+ region = depth + row.count("{", 0, block.end()) - row.count("}", 0, block.end())
1246
+ start = block.end() if start is None else start
1247
+ if start is not None:
1248
+ for m in _JS_METRIC.finditer(row, start):
1249
+ key = m.group("k")
1250
+ out[(key, seen[key])] = _Threshold(float(m.group("v")), number)
1251
+ seen[key] += 1
1252
+ depth += row.count("{") - row.count("}")
1253
+ if region is not None and depth < region:
1254
+ region = None
1255
+
1256
+
1257
+ def _thresholds(ctx: FileContext, side: Side) -> _Thresholds | None:
1258
+ """The coverage thresholds one side of ``ctx`` sets; ``None`` if that side is unreadable."""
1259
+ text = ctx.new_text if side is Side.NEW else ctx.old_text
1260
+ out: _Thresholds = {}
1261
+ if not text:
1262
+ return out
1263
+ lines = git_lines(text)
1264
+ path = ctx.path if side is Side.NEW else ctx.old_path or ctx.path
1265
+ name = _basename(path)
1266
+ if name == "pyproject.toml":
1267
+ data = ctx.toml if side is Side.NEW else ctx.old_toml
1268
+ if data is None:
1269
+ return None
1270
+ tool = data.get("tool")
1271
+ coverage = tool.get("coverage") if isinstance(tool, dict) else None
1272
+ report = coverage.get("report") if isinstance(coverage, dict) else None
1273
+ value = report.get("fail_under") if isinstance(report, dict) else None
1274
+ if _num(value) is not None:
1275
+ line = next((n for n, r in enumerate(lines, 1) if _TOML_FAIL_UNDER.match(r)), None)
1276
+ out[("fail_under", 0)] = _Threshold(_num(value), line)
1277
+ _line_scan(lines, False, out)
1278
+ elif name in _INI_FILES:
1279
+ _line_scan(lines, True, out)
1280
+ elif name == "package.json" or name in _JSON_RC or name in _YAML_RC:
1281
+ if name in _YAML_RC:
1282
+ data = _yaml_data(ctx, side)
1283
+ else:
1284
+ data = ctx.json if side is Side.NEW else ctx.old_json
1285
+ if (ctx.json_error if side is Side.NEW else ctx.old_json_error) is not None:
1286
+ return None
1287
+ if not isinstance(data, dict):
1288
+ return out if data is None and name in _YAML_RC else None
1289
+ if name == "package.json":
1290
+ jest = data.get("jest")
1291
+ if isinstance(jest, dict) and "coverageThreshold" in jest:
1292
+ _collect(jest["coverageThreshold"], ("jest", "coverageThreshold"), lines, out)
1293
+ for tool in ("nyc", "c8"):
1294
+ _rc_thresholds(data.get(tool), (tool,), lines, out)
1295
+ elif name == "jest.config.json":
1296
+ _collect(data.get("coverageThreshold"), ("coverageThreshold",), lines, out)
1297
+ else:
1298
+ _rc_thresholds(data, (), lines, out)
1299
+ elif name in _CODECOV:
1300
+ data = _yaml_data(ctx, side)
1301
+ coverage = data.get("coverage") if isinstance(data, dict) else None
1302
+ status = coverage.get("status") if isinstance(coverage, dict) else None
1303
+ if not isinstance(status, dict):
1304
+ return out
1305
+ for kind in ("project", "patch"):
1306
+ checks = status.get(kind)
1307
+ if not isinstance(checks, dict):
1308
+ continue
1309
+ for check, options in checks.items():
1310
+ if not isinstance(options, dict):
1311
+ continue
1312
+ for key in ("target", "threshold"):
1313
+ if key in options:
1314
+ where = ("coverage", "status", kind, check, key)
1315
+ out[where] = _Threshold(
1316
+ _num(options[key]), _key_line(lines, where), key == "threshold"
1317
+ )
1318
+ elif _JS_CONFIG.match(name):
1319
+ language = ctx.language
1320
+ _js_scan(git_lines(_mask(text, language, path)), out)
1321
+ elif ctx.language in _CLI_LANGUAGES:
1322
+ _line_scan(lines, False, out)
1323
+ return out
1324
+
1325
+
1326
+ def _label(key: tuple[object, ...]) -> str:
1327
+ return ".".join(str(k) for k in key if isinstance(k, str))
1328
+
1329
+
1330
+ def _show(value: float | None) -> str:
1331
+ if value is None:
1332
+ return "a non-number"
1333
+ return str(int(value)) if value == int(value) else str(value)
1334
+
1335
+
1336
+ @rule(
1337
+ id="tests/coverage-threshold-lowered",
1338
+ severity="warning",
1339
+ title="Coverage threshold lowered",
1340
+ scope="file",
1341
+ rationale=(
1342
+ "Lowering or removing the coverage gate lets untested code in without anyone "
1343
+ "deciding that on purpose."
1344
+ ),
1345
+ hint="Add tests for the new code instead of lowering the threshold, or explain the "
1346
+ "lower bar in the change description.",
1347
+ tags={"tests", "coverage"},
1348
+ )
1349
+ def coverage_threshold_lowered(ctx: FileContext) -> Iterator[Hit]:
1350
+ """A coverage threshold that the change lowers, removes or switches off.
1351
+
1352
+ Sources: ``fail_under`` in ``pyproject.toml`` (``[tool.coverage.report]``),
1353
+ ``setup.cfg``, ``.coveragerc``, ``tox.ini``; ``--cov-fail-under`` and
1354
+ ``coverage report --fail-under`` in those, in ``pytest.ini`` and in YAML,
1355
+ TOML, shell and text files (workflows, Makefiles); Jest
1356
+ ``coverageThreshold`` (``package.json``, ``jest.config.json``, and
1357
+ ``jest``/``vitest``/``vite`` ``.config.js|ts`` scripts, where Vitest
1358
+ ``thresholds`` count too); nyc and c8 ``branches``/``functions``/
1359
+ ``lines``/``statements`` and ``check-coverage`` (``package.json`` keys,
1360
+ ``.nycrc``, ``.c8rc``); codecov ``coverage.status.project|patch.*.target``
1361
+ and ``threshold``. Old and new values are compared by key (JSON, TOML
1362
+ and YAML are parsed; scripts and INI files are matched by key and
1363
+ occurrence order). Lowered is reported at the new line; removed (also
1364
+ ``auto`` in place of a number, ``check-coverage`` false, or the file
1365
+ deleted) at the old line. For a codecov ``threshold``, the allowed drop,
1366
+ a higher value is the weaker one. Negative Jest thresholds (a maximum of
1367
+ uncovered items) compare the same way: lower is weaker.
1368
+ """
1369
+ if ctx.kind is not FileKind.TEXT or not ctx.old_text:
1370
+ return
1371
+ if ctx.file_class in ("test", "docs", "vendored", "generated", "minified", "lockfile"):
1372
+ return
1373
+ if any(part in _FIXTURE_DIRS for part in ctx.path.split("/")[:-1]):
1374
+ return # a fixture project, not this repository's gate
1375
+ old = _thresholds(ctx, Side.OLD)
1376
+ if not old:
1377
+ return
1378
+ new = _thresholds(ctx, Side.NEW)
1379
+ if new is None:
1380
+ return # the new side does not parse: the config and syntax rules report that
1381
+ for key, before in old.items():
1382
+ if before.value is None:
1383
+ continue
1384
+ label = _label(key)
1385
+ after = new.get(key)
1386
+ if after is None or after.value is None:
1387
+ what = "removed" if after is None else "replaced by a non-number"
1388
+ line = before.line if after is None else after.line
1389
+ side = Side.OLD if after is None else Side.NEW
1390
+ if line is not None:
1391
+ yield Hit(
1392
+ line,
1393
+ side=side,
1394
+ message=f"Coverage threshold {label} {what} (was {_show(before.value)})",
1395
+ )
1396
+ continue
1397
+ weaker = after.value > before.value if before.inverted else after.value < before.value
1398
+ if weaker and after.line is not None:
1399
+ verb = "raised" if before.inverted else "lowered"
1400
+ yield Hit(
1401
+ after.line,
1402
+ message=f"Coverage {'allowed drop' if before.inverted else 'threshold'} "
1403
+ f"{label} {verb} from {_show(before.value)} to {_show(after.value)}",
1404
+ )