smelt-cli 0.2.0__py3-none-win_amd64.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 (133) hide show
  1. smelt/__init__.py +6 -0
  2. smelt/__main__.py +5 -0
  3. smelt/analysis/__init__.py +45 -0
  4. smelt/analysis/annotations.py +105 -0
  5. smelt/analysis/cache.py +168 -0
  6. smelt/analysis/context.py +147 -0
  7. smelt/analysis/contracts.py +210 -0
  8. smelt/analysis/coverage.py +377 -0
  9. smelt/analysis/definition_blocks.py +569 -0
  10. smelt/analysis/enum_values.py +217 -0
  11. smelt/analysis/errors.py +11 -0
  12. smelt/analysis/exports.py +166 -0
  13. smelt/analysis/files.py +279 -0
  14. smelt/analysis/function_usage.py +123 -0
  15. smelt/analysis/graphs.py +77 -0
  16. smelt/analysis/identity.py +64 -0
  17. smelt/analysis/import_cache.py +98 -0
  18. smelt/analysis/imports.py +452 -0
  19. smelt/analysis/literals.py +17 -0
  20. smelt/analysis/member_state.py +108 -0
  21. smelt/analysis/members.py +975 -0
  22. smelt/analysis/ordering.py +399 -0
  23. smelt/analysis/ordering_rewrite.py +232 -0
  24. smelt/analysis/package_exports.py +58 -0
  25. smelt/analysis/parsing.py +126 -0
  26. smelt/analysis/python_version.py +164 -0
  27. smelt/analysis/retained.py +84 -0
  28. smelt/analysis/syntax.py +109 -0
  29. smelt/analysis/test_awaits.py +91 -0
  30. smelt/analysis/test_cases.py +84 -0
  31. smelt/analysis/test_deadlines.py +90 -0
  32. smelt/analysis/test_outcomes.py +71 -0
  33. smelt/analysis/test_subprocesses.py +107 -0
  34. smelt/analysis/test_syntax.py +1425 -0
  35. smelt/analysis/test_timing.py +76 -0
  36. smelt/analysis/type_dispatch.py +193 -0
  37. smelt/analysis/workspace.py +146 -0
  38. smelt/cli/__init__.py +3 -0
  39. smelt/cli/app.py +300 -0
  40. smelt/cli/commands/__init__.py +62 -0
  41. smelt/cli/commands/adopt.py +274 -0
  42. smelt/cli/commands/check.py +151 -0
  43. smelt/cli/commands/discover.py +51 -0
  44. smelt/cli/commands/info.py +112 -0
  45. smelt/cli/session.py +163 -0
  46. smelt/cli/session_slots.py +43 -0
  47. smelt/cli/support.py +90 -0
  48. smelt/config/__init__.py +36 -0
  49. smelt/config/discovery.py +93 -0
  50. smelt/config/errors.py +51 -0
  51. smelt/config/loader.py +282 -0
  52. smelt/config/models.py +717 -0
  53. smelt/config/patterns.py +47 -0
  54. smelt/config/schema.py +23 -0
  55. smelt/config/source.py +56 -0
  56. smelt/config/validation.py +180 -0
  57. smelt/diagnostics/__init__.py +0 -0
  58. smelt/diagnostics/debt.py +226 -0
  59. smelt/diagnostics/dedupe.py +41 -0
  60. smelt/diagnostics/groups.py +109 -0
  61. smelt/diagnostics/render/__init__.py +0 -0
  62. smelt/diagnostics/render/machine.py +237 -0
  63. smelt/diagnostics/render/text.py +321 -0
  64. smelt/diagnostics/report.py +104 -0
  65. smelt/diagnostics/suppressions.py +80 -0
  66. smelt/diagnostics/violation.py +120 -0
  67. smelt/docs.py +98 -0
  68. smelt/engine/__init__.py +0 -0
  69. smelt/engine/briefing.py +630 -0
  70. smelt/engine/cache.py +65 -0
  71. smelt/engine/changes.py +260 -0
  72. smelt/engine/check.py +724 -0
  73. smelt/engine/coverage.py +151 -0
  74. smelt/engine/evaluation.py +291 -0
  75. smelt/engine/file_checks.py +94 -0
  76. smelt/engine/git_source.py +140 -0
  77. smelt/engine/inference.py +854 -0
  78. smelt/engine/mirror_inference.py +95 -0
  79. smelt/engine/native_git.py +190 -0
  80. smelt/engine/ordering_fixes.py +132 -0
  81. smelt/engine/paths.py +163 -0
  82. smelt/engine/result_cache.py +208 -0
  83. smelt/engine/rule_settings.py +164 -0
  84. smelt/engine/schema.py +58 -0
  85. smelt/engine/staged.py +75 -0
  86. smelt/engine/workspace.py +5 -0
  87. smelt/model/__init__.py +9 -0
  88. smelt/model/architecture.py +234 -0
  89. smelt/py.typed +0 -0
  90. smelt/rules/__init__.py +0 -0
  91. smelt/rules/activation.py +129 -0
  92. smelt/rules/base.py +131 -0
  93. smelt/rules/catalog.json +600 -0
  94. smelt/rules/common.py +164 -0
  95. smelt/rules/dependencies/__init__.py +0 -0
  96. smelt/rules/dependencies/composition_root.py +86 -0
  97. smelt/rules/dependencies/cycles.py +329 -0
  98. smelt/rules/dependencies/fanout.py +81 -0
  99. smelt/rules/dependencies/features.py +165 -0
  100. smelt/rules/dependencies/interfaces.py +84 -0
  101. smelt/rules/dependencies/layers.py +138 -0
  102. smelt/rules/dependencies/third_party.py +132 -0
  103. smelt/rules/member_names.py +13 -0
  104. smelt/rules/meta.py +74 -0
  105. smelt/rules/registry.py +132 -0
  106. smelt/rules/structure/__init__.py +0 -0
  107. smelt/rules/structure/assignments.py +114 -0
  108. smelt/rules/structure/contracts.py +71 -0
  109. smelt/rules/structure/coverage.py +100 -0
  110. smelt/rules/structure/enum_values.py +50 -0
  111. smelt/rules/structure/headers.py +143 -0
  112. smelt/rules/structure/import_style.py +145 -0
  113. smelt/rules/structure/layout.py +202 -0
  114. smelt/rules/structure/members.py +116 -0
  115. smelt/rules/structure/naming.py +132 -0
  116. smelt/rules/structure/ordering.py +83 -0
  117. smelt/rules/structure/package_imports.py +117 -0
  118. smelt/rules/structure/type_dispatch.py +79 -0
  119. smelt/rules/testing/__init__.py +0 -0
  120. smelt/rules/testing/awaits.py +46 -0
  121. smelt/rules/testing/cases.py +47 -0
  122. smelt/rules/testing/location.py +537 -0
  123. smelt/rules/testing/mocking.py +140 -0
  124. smelt/rules/testing/outcomes.py +119 -0
  125. smelt/rules/testing/private_access.py +93 -0
  126. smelt/rules/testing/public_attributes.py +62 -0
  127. smelt/rules/testing/public_functions.py +52 -0
  128. smelt/rules/testing/timing.py +62 -0
  129. smelt_cli-0.2.0.data/scripts/smelt.exe +0 -0
  130. smelt_cli-0.2.0.dist-info/METADATA +103 -0
  131. smelt_cli-0.2.0.dist-info/RECORD +133 -0
  132. smelt_cli-0.2.0.dist-info/WHEEL +4 -0
  133. smelt_cli-0.2.0.dist-info/sboms/smelt-cli.cyclonedx.json +5462 -0
@@ -0,0 +1,1425 @@
1
+ """Scoped syntactic test evidence; no imports or execution of analyzed tests."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import hashlib
7
+ import json
8
+ from collections.abc import Mapping
9
+ from copy import copy
10
+ from dataclasses import dataclass, field, replace
11
+ from functools import partial
12
+ from typing import TYPE_CHECKING
13
+
14
+ from pydantic import TypeAdapter
15
+
16
+ from smelt.analysis.exports import namespace_of, resolve_dotted
17
+ from smelt.analysis.literals import nonempty_literal
18
+ from smelt.analysis.parsing import resolve_relative
19
+ from smelt.analysis.test_deadlines import async_deadline
20
+ from smelt.analysis.test_subprocesses import (
21
+ checked_python_assertions,
22
+ child_status_propagates,
23
+ )
24
+ from smelt.config.patterns import path_matches
25
+
26
+ if TYPE_CHECKING:
27
+ from collections.abc import Callable, Iterator, Sequence
28
+
29
+ from smelt.analysis.cache import FactCache
30
+ from smelt.analysis.files import FileIndex
31
+ from smelt.analysis.parsing import AstCache
32
+ from smelt.analysis.syntax import SyntaxIndex
33
+
34
+ type Function = ast.FunctionDef | ast.AsyncFunctionDef
35
+
36
+ _MOCKER_FIXTURES = frozenset(
37
+ {"mocker", "class_mocker", "module_mocker", "package_mocker", "session_mocker"}
38
+ )
39
+ _MOCK_ROOTS = ("unittest.mock.", "pytest_mock.MockerFixture.")
40
+ _MOCK_OPERATIONS = frozenset(
41
+ {
42
+ "Mock",
43
+ "MagicMock",
44
+ "AsyncMock",
45
+ "NonCallableMock",
46
+ "NonCallableMagicMock",
47
+ "PropertyMock",
48
+ "mock_open",
49
+ "create_autospec",
50
+ "patch",
51
+ "spy",
52
+ "stub",
53
+ "async_stub",
54
+ }
55
+ )
56
+ _MOCK_TYPES = frozenset(
57
+ root + name for root in _MOCK_ROOTS for name in _MOCK_OPERATIONS - {"patch", "spy"}
58
+ )
59
+ _MOCK_ASSERTIONS = frozenset(
60
+ {
61
+ "assert_called",
62
+ "assert_called_once",
63
+ "assert_called_with",
64
+ "assert_called_once_with",
65
+ "assert_any_call",
66
+ "assert_has_calls",
67
+ "assert_not_called",
68
+ "assert_awaited",
69
+ "assert_awaited_once",
70
+ "assert_awaited_with",
71
+ "assert_awaited_once_with",
72
+ "assert_any_await",
73
+ "assert_has_awaits",
74
+ "assert_not_awaited",
75
+ }
76
+ )
77
+ _MONKEYPATCH = "pytest.MonkeyPatch"
78
+ _MAX_RANGE_ARGS = 3
79
+ _CONSTRUCTORS = frozenset(
80
+ {
81
+ _MONKEYPATCH,
82
+ "asyncio.Event",
83
+ "asyncio.locks.Event",
84
+ "asyncio.Task",
85
+ "asyncio.Future",
86
+ "threading.Event",
87
+ "subprocess.Popen",
88
+ }
89
+ )
90
+ _FACTORY_TYPES = {
91
+ "asyncio.get_running_loop": "asyncio.AbstractEventLoop",
92
+ "asyncio.get_event_loop": "asyncio.AbstractEventLoop",
93
+ "asyncio.create_task": "asyncio.Task",
94
+ "asyncio.ensure_future": "asyncio.Future",
95
+ }
96
+ _ASYNC_FACTORY_TYPES = {
97
+ "asyncio.create_subprocess_exec": "asyncio.subprocess.Process",
98
+ "asyncio.create_subprocess_shell": "asyncio.subprocess.Process",
99
+ }
100
+
101
+
102
+ @dataclass(frozen=True)
103
+ class _Binding:
104
+ qualified: str
105
+ kind: str = "symbol"
106
+ provenance: str = "import"
107
+ items: tuple[_Binding | None, ...] | None = None
108
+ mock_spec: str | None = None
109
+ async_callable: str | None = None
110
+ mock_origin: str | None = field(default=None, compare=False)
111
+ mutable: bool = False
112
+ text: str | None = None
113
+
114
+
115
+ _BINDINGS = TypeAdapter(dict[str, _Binding])
116
+ _ASYNC_SPECS = TypeAdapter(dict[str, frozenset[str]])
117
+
118
+
119
+ def _annotation(node: ast.AST, env: Mapping[str, _Binding]) -> str | None:
120
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
121
+ try:
122
+ return _annotation(ast.parse(node.value, mode="eval").body, env)
123
+ except SyntaxError:
124
+ return None
125
+ if isinstance(node, ast.Name):
126
+ binding = env.get(node.id)
127
+ return binding.qualified if binding else None
128
+ if isinstance(node, ast.Attribute):
129
+ parent = _annotation(node.value, env)
130
+ return f"{parent}.{node.attr}" if parent else None
131
+ return None
132
+
133
+
134
+ def _instance(qualified: str, provenance: str) -> _Binding:
135
+ return _Binding(
136
+ qualified,
137
+ "mock" if qualified in _MOCK_TYPES else "instance",
138
+ provenance,
139
+ async_callable=qualified
140
+ if qualified
141
+ in {root + name for root in _MOCK_ROOTS for name in ("AsyncMock", "async_stub")}
142
+ else None,
143
+ )
144
+
145
+
146
+ def _fixture_binding(node: ast.AST, env: Mapping[str, _Binding]) -> _Binding | None:
147
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
148
+ try:
149
+ return _fixture_binding(ast.parse(node.value, mode="eval").body, env)
150
+ except SyntaxError:
151
+ return None
152
+ if isinstance(node, ast.Subscript):
153
+ origin = _annotation(node.value, env)
154
+ arguments = (
155
+ node.slice.elts if isinstance(node.slice, ast.Tuple) else [node.slice]
156
+ )
157
+ if origin in {
158
+ "typing.Iterator",
159
+ "typing.Generator",
160
+ "typing.AsyncIterator",
161
+ "typing.AsyncGenerator",
162
+ "collections.abc.Iterator",
163
+ "collections.abc.Generator",
164
+ "collections.abc.AsyncIterator",
165
+ "collections.abc.AsyncGenerator",
166
+ }:
167
+ return _fixture_binding(arguments[0], env) if arguments else None
168
+ if origin in {"builtins.tuple", "typing.Tuple"}:
169
+ return _Binding(
170
+ "",
171
+ "nonempty",
172
+ "fixture-return",
173
+ tuple(_fixture_binding(arg, env) for arg in arguments),
174
+ )
175
+ qualified = _annotation(node, env)
176
+ return _instance(qualified, "fixture-return") if qualified else None
177
+
178
+
179
+ def _inferred_fixture(binding: _Binding) -> _Binding:
180
+ return replace(
181
+ binding,
182
+ provenance="fixture-inferred",
183
+ items=tuple(_inferred_fixture(item) if item else None for item in binding.items)
184
+ if binding.items is not None
185
+ else None,
186
+ )
187
+
188
+
189
+ def _class_async_methods(tree: ast.Module, module: str) -> dict[str, frozenset[str]]:
190
+ decorators = {"staticmethod", "classmethod"}
191
+ for node in tree.body:
192
+ if isinstance(node, ast.ImportFrom) and node.module == "abc":
193
+ decorators.update(
194
+ alias.asname or alias.name
195
+ for alias in node.names
196
+ if alias.name == "abstractmethod"
197
+ )
198
+ elif isinstance(node, ast.Import):
199
+ decorators.update(
200
+ f"{alias.asname or alias.name}.abstractmethod"
201
+ for alias in node.names
202
+ if alias.name == "abc"
203
+ )
204
+ return {
205
+ f"{module}.{node.name}": frozenset(
206
+ method.name
207
+ for method in node.body
208
+ if isinstance(method, ast.AsyncFunctionDef)
209
+ and all(
210
+ ast.unparse(decorator) in decorators
211
+ for decorator in method.decorator_list
212
+ )
213
+ )
214
+ for node in tree.body
215
+ if isinstance(node, ast.ClassDef)
216
+ }
217
+
218
+
219
+ def _nonempty_range(node: ast.Call) -> bool:
220
+ if node.keywords or not node.args or len(node.args) > _MAX_RANGE_ARGS:
221
+ return False
222
+ values: list[int] = []
223
+ for arg in node.args:
224
+ sign = 1
225
+ value = arg
226
+ if isinstance(value, ast.UnaryOp) and isinstance(value.op, ast.USub):
227
+ sign, value = -1, value.operand
228
+ if (
229
+ not isinstance(value, ast.Constant)
230
+ or not isinstance(value.value, int)
231
+ or isinstance(value.value, bool)
232
+ ):
233
+ return False
234
+ values.append(sign * value.value)
235
+ try:
236
+ sequence = range(*values)
237
+ except ValueError:
238
+ return False
239
+ return (
240
+ sequence.start < sequence.stop
241
+ if sequence.step > 0
242
+ else sequence.start > sequence.stop
243
+ )
244
+
245
+
246
+ @dataclass(frozen=True)
247
+ class TestCall:
248
+ node: ast.Call
249
+ qualified: str
250
+ provenance: str = "import"
251
+ mock_receiver: bool = False
252
+
253
+ @property
254
+ def patch(self) -> bool:
255
+ return self.qualified in {
256
+ f"{_MONKEYPATCH}.setattr",
257
+ f"{_MONKEYPATCH}.delattr",
258
+ } or self.qualified in {
259
+ root + suffix
260
+ for root in _MOCK_ROOTS
261
+ for suffix in ("patch", "patch.object", "patch.dict", "patch.multiple")
262
+ }
263
+
264
+ @property
265
+ def mock(self) -> bool:
266
+ return self.patch or any(
267
+ self.qualified == root + name
268
+ for root in _MOCK_ROOTS
269
+ for name in _MOCK_OPERATIONS
270
+ )
271
+
272
+ @property
273
+ def family(self) -> str:
274
+ if self.qualified.startswith(f"{_MONKEYPATCH}."):
275
+ return "pytest.MonkeyPatch"
276
+ if self.qualified.startswith("pytest_mock."):
277
+ return "pytest-mock"
278
+ return "unittest.mock"
279
+
280
+ @property
281
+ def interaction_assertion(self) -> bool:
282
+ return (
283
+ self.mock_receiver and self.qualified.rsplit(".", 1)[-1] in _MOCK_ASSERTIONS
284
+ )
285
+
286
+ @property
287
+ def string_target(self) -> bool:
288
+ if not self.patch or self.qualified.endswith(".object"):
289
+ return False
290
+ if self.qualified.startswith(f"{_MONKEYPATCH}."):
291
+ # setattr("pkg.name", replacement) vs setattr(obj, "name", replacement).
292
+ positional = 2 if self.qualified.endswith(".setattr") else 1
293
+ if len(self.node.args) > positional or any(
294
+ kw.arg == "name" for kw in self.node.keywords
295
+ ):
296
+ return False
297
+ target = (
298
+ self.node.args[0]
299
+ if self.node.args
300
+ else next(
301
+ (
302
+ kw.value
303
+ for kw in self.node.keywords
304
+ if kw.arg in {"target", "in_dict"}
305
+ ),
306
+ None,
307
+ )
308
+ )
309
+ return isinstance(target, ast.Constant) and isinstance(target.value, str)
310
+
311
+
312
+ @dataclass
313
+ class MockObservation:
314
+ node: ast.Call | ast.Attribute
315
+ origin: str
316
+ receiver: str
317
+ kind: str
318
+ async_callable: str
319
+ provenance: str
320
+
321
+
322
+ @dataclass
323
+ class TestFunction:
324
+ node: Function
325
+ name: str
326
+ calls: list[TestCall] = field(default_factory=list)
327
+ assertions: list[ast.Assert] = field(default_factory=list)
328
+ clock_replacements: list[ast.Attribute | ast.Call] = field(default_factory=list)
329
+ awaited_tasks: list[tuple[ast.Await, str, str]] = field(default_factory=list)
330
+ nonempty_iterables: set[ast.expr] = field(default_factory=set)
331
+ mock_observations: list[MockObservation] = field(default_factory=list)
332
+ child_assertions: list[ast.Call] = field(default_factory=list)
333
+
334
+ def has_assertion(self, helpers: list[str]) -> bool:
335
+ return bool(self.outcome_evidence(helpers))
336
+
337
+ def outcome_evidence(self, helpers: list[str]) -> list[ast.Assert | ast.Call]:
338
+ evidence: list[ast.Assert | ast.Call] = [
339
+ node
340
+ for node in self.assertions
341
+ if not (isinstance(node.test, ast.Constant) and node.test.value is True)
342
+ ]
343
+ parents = {
344
+ child: node
345
+ for node in ast.walk(self.node)
346
+ for child in ast.iter_child_nodes(node)
347
+ }
348
+ evidence.extend(
349
+ call.node
350
+ for call in self.calls
351
+ if (
352
+ call.qualified in helpers
353
+ or (
354
+ call.qualified
355
+ in {"pytest.raises", "pytest.warns", "pytest.deprecated_call"}
356
+ and (
357
+ isinstance(parents.get(call.node), ast.withitem)
358
+ or len(call.node.args)
359
+ > (0 if call.qualified == "pytest.deprecated_call" else 1)
360
+ )
361
+ )
362
+ or call.qualified.startswith("unittest.TestCase.assert")
363
+ or call.interaction_assertion
364
+ )
365
+ )
366
+ calls = {call.node: call.qualified for call in self.calls}
367
+ evidence.extend(
368
+ call.node
369
+ for call in self.calls
370
+ if (
371
+ call.qualified in {"asyncio.Event.wait", "asyncio.locks.Event.wait"}
372
+ and (deadline := async_deadline(call.node, calls, parents)).awaited
373
+ and deadline.raises_on_timeout
374
+ )
375
+ )
376
+ evidence.extend(
377
+ call
378
+ for call in self.child_assertions
379
+ if child_status_propagates(call, parents)
380
+ )
381
+ return evidence
382
+
383
+
384
+ def _patch_result(node: ast.Call, qualified: str) -> _Binding | None:
385
+ new_position = 2 if qualified.endswith(".object") else 1
386
+ if len(node.args) > new_position or any(
387
+ kw.arg in {"new", "new_callable"} or kw.arg is None for kw in node.keywords
388
+ ):
389
+ return None
390
+ return _instance("unittest.mock.MagicMock", "patch-result")
391
+
392
+
393
+ @dataclass
394
+ class TestModule:
395
+ path: str
396
+ imports: list[tuple[ast.Import | ast.ImportFrom, str]] = field(default_factory=list)
397
+ attributes: list[tuple[ast.Attribute, str]] = field(default_factory=list)
398
+ calls: list[TestCall] = field(default_factory=list)
399
+ tests: list[TestFunction] = field(default_factory=list)
400
+ instance_attributes: list[tuple[ast.Attribute, str, str]] = field(
401
+ default_factory=list
402
+ )
403
+
404
+
405
+ def _names(node: ast.AST) -> set[str]:
406
+ return {
407
+ child.id
408
+ for child in ast.walk(node)
409
+ if isinstance(child, ast.Name) and isinstance(child.ctx, ast.Store | ast.Del)
410
+ }
411
+
412
+
413
+ def _locals(nodes: Sequence[ast.AST]) -> set[str]:
414
+ names: set[str] = set()
415
+ for node in nodes:
416
+ if isinstance(node, ast.ExceptHandler) and node.name:
417
+ names.add(node.name)
418
+ if isinstance(node, ast.FunctionDef | ast.AsyncFunctionDef | ast.ClassDef):
419
+ names.add(node.name)
420
+ continue
421
+ if isinstance(node, ast.Import | ast.ImportFrom):
422
+ names.update(
423
+ alias.asname or alias.name.split(".")[0] for alias in node.names
424
+ )
425
+ elif not isinstance(
426
+ node,
427
+ ast.Lambda | ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp,
428
+ ):
429
+ names.update(
430
+ child.id
431
+ for child in ast.iter_child_nodes(node)
432
+ if isinstance(child, ast.Name)
433
+ and isinstance(child.ctx, ast.Store | ast.Del)
434
+ )
435
+ for child in ast.iter_child_nodes(node):
436
+ if isinstance(child, ast.stmt):
437
+ names.update(_locals([child]))
438
+ elif not isinstance(child, ast.expr_context):
439
+ names.update(_expression_bindings(child))
440
+ return names
441
+
442
+
443
+ def _expression_bindings(node: ast.AST) -> set[str]:
444
+ if isinstance(node, ast.MatchAs | ast.MatchStar) and node.name:
445
+ return {node.name}
446
+ if isinstance(
447
+ node, ast.Lambda | ast.ListComp | ast.SetComp | ast.DictComp | ast.GeneratorExp
448
+ ):
449
+ return set()
450
+ return (
451
+ {node.id}
452
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store | ast.Del)
453
+ else set()
454
+ ) | set().union(
455
+ *(_expression_bindings(child) for child in ast.iter_child_nodes(node))
456
+ )
457
+
458
+
459
+ class _Visitor(ast.NodeVisitor):
460
+ def __init__(
461
+ self,
462
+ module: TestModule,
463
+ constructors: frozenset[str],
464
+ fixtures: Mapping[str, _Binding],
465
+ async_specs: Mapping[str, frozenset[str]],
466
+ ) -> None:
467
+ self.result = module
468
+ self.env: dict[str, _Binding] = {
469
+ name: _Binding(f"builtins.{name}") for name in ("all", "range", "tuple")
470
+ }
471
+ self.module_env = self.env
472
+ self.constructors = constructors
473
+ self.fixtures = fixtures
474
+ self.async_specs = async_specs
475
+ self.defined_fixtures: dict[str, _Binding] = {}
476
+ self.fixture_outputs: list[_Binding | None] | None = None
477
+ self.fixture_yielded = False
478
+ self.test: TestFunction | None = None
479
+ self.function_depth = 0
480
+ self.class_name: str | None = None
481
+ self.unittest = False
482
+
483
+ def qualified(self, node: ast.AST) -> str | None:
484
+ binding = self.binding(node)
485
+ return binding.qualified if binding else None
486
+
487
+ def binding(self, node: ast.AST) -> _Binding | None:
488
+ if isinstance(node, ast.Name):
489
+ return self.env.get(node.id)
490
+ if isinstance(node, ast.Call | ast.Await):
491
+ return self.value_binding(node)
492
+ if isinstance(node, ast.Attribute):
493
+ parent = self.binding(node.value)
494
+ if parent and parent.kind != "member":
495
+ return _Binding(
496
+ f"{parent.qualified}.{node.attr}",
497
+ "mock"
498
+ if parent.kind == "mock"
499
+ else "member"
500
+ if parent.kind == "instance"
501
+ else "symbol",
502
+ parent.provenance,
503
+ async_callable=f"{parent.mock_spec}.{node.attr}"
504
+ if parent.mock_spec
505
+ and node.attr in self.async_specs.get(parent.mock_spec, ())
506
+ else None,
507
+ mock_origin=f"{parent.mock_origin}.{node.attr}"
508
+ if parent.mock_origin
509
+ else None,
510
+ )
511
+ return None
512
+
513
+ def value_binding(self, node: ast.AST, *, context: bool = False) -> _Binding | None:
514
+ if isinstance(node, ast.Await):
515
+ qualified = (
516
+ self.qualified(node.value.func)
517
+ if isinstance(node.value, ast.Call)
518
+ else None
519
+ )
520
+ return (
521
+ _instance(_ASYNC_FACTORY_TYPES[qualified], "awaited-factory")
522
+ if qualified in _ASYNC_FACTORY_TYPES
523
+ else None
524
+ )
525
+ if (
526
+ isinstance(node, ast.Tuple)
527
+ and node.elts
528
+ and not any(isinstance(item, ast.Starred) for item in node.elts)
529
+ ):
530
+ return _Binding(
531
+ "",
532
+ "nonempty",
533
+ "literal",
534
+ tuple(self.value_binding(item) for item in node.elts),
535
+ )
536
+ if (
537
+ isinstance(node, ast.List | ast.Set | ast.Dict)
538
+ and self.test
539
+ and nonempty_literal(node)
540
+ ):
541
+ return _Binding("", "nonempty", "literal", mutable=True)
542
+ if isinstance(node, ast.Tuple | ast.Constant) and nonempty_literal(node):
543
+ return _Binding(
544
+ "",
545
+ "nonempty",
546
+ "literal",
547
+ text=node.value
548
+ if isinstance(node, ast.Constant) and isinstance(node.value, str)
549
+ else None,
550
+ )
551
+ if isinstance(node, ast.Call):
552
+ return self.call_result(node, context=context)
553
+ return self.binding(node)
554
+
555
+ def call_result(self, node: ast.Call, *, context: bool) -> _Binding | None:
556
+ qualified = self.qualified(node.func)
557
+ if qualified == "builtins.range":
558
+ return (
559
+ _Binding("", "nonempty", "literal-range")
560
+ if _nonempty_range(node)
561
+ else None
562
+ )
563
+ if qualified in self.constructors | _MOCK_TYPES | _CONSTRUCTORS:
564
+ binding = _instance(qualified, "constructor")
565
+ if binding.kind == "mock":
566
+ spec = next(
567
+ (
568
+ kw.value
569
+ for kw in node.keywords
570
+ if kw.arg in {"spec", "spec_set"}
571
+ and not isinstance(kw.value, ast.Constant)
572
+ ),
573
+ node.args[0] if node.args else None,
574
+ )
575
+ binding = replace(
576
+ binding,
577
+ mock_spec=self.qualified(spec) if spec else None,
578
+ mock_origin=f"{self.result.path}:{node.lineno}:{node.col_offset}",
579
+ )
580
+ return binding
581
+ if qualified in _FACTORY_TYPES:
582
+ return _instance(_FACTORY_TYPES[qualified], "known-factory")
583
+ if qualified == f"{_MONKEYPATCH}.context":
584
+ return _instance(_MONKEYPATCH, "context")
585
+ if (
586
+ qualified
587
+ and TestCall(node, qualified).patch
588
+ and not qualified.endswith((".dict", ".multiple"))
589
+ and not qualified.startswith(f"{_MONKEYPATCH}.")
590
+ and (context or qualified.startswith("pytest_mock."))
591
+ ):
592
+ return _patch_result(node, qualified)
593
+ return None
594
+
595
+ def visit_Import(self, node: ast.Import) -> None:
596
+ for alias in node.names:
597
+ self.env[alias.asname or alias.name.split(".")[0]] = _Binding(
598
+ alias.name if alias.asname else alias.name.split(".")[0]
599
+ )
600
+ self.result.imports.append((node, alias.name))
601
+
602
+ def visit_ImportFrom(self, node: ast.ImportFrom) -> None:
603
+ module = self.result.path.removesuffix(".py").replace("/", ".")
604
+ base = resolve_relative(
605
+ module, is_package=False, level=node.level, target=node.module
606
+ )
607
+ for alias in node.names:
608
+ if alias.name == "*":
609
+ self.env.clear()
610
+ continue
611
+ qualified = f"{base}.{alias.name}" if base else alias.name
612
+ self.env[alias.asname or alias.name] = _Binding(qualified)
613
+ self.result.imports.append((node, qualified))
614
+
615
+ def visit_ClassDef(self, node: ast.ClassDef) -> None:
616
+ outer, class_name, unittest = self.env, self.class_name, self.unittest
617
+ for expression in [
618
+ *node.decorator_list,
619
+ *node.bases,
620
+ *(kw.value for kw in node.keywords),
621
+ ]:
622
+ self.visit(expression)
623
+ self.unittest = any(
624
+ self.qualified(base)
625
+ in {"unittest.TestCase", "unittest.IsolatedAsyncioTestCase"}
626
+ for base in node.bases
627
+ )
628
+ self.class_name = node.name
629
+ self.env = dict(outer)
630
+ for statement in node.body:
631
+ self.visit(statement)
632
+ self.env = outer
633
+ self.class_name = class_name
634
+ self.unittest = unittest
635
+ self.env.pop(node.name, None)
636
+ qualified = (
637
+ f"{self.result.path.removesuffix('.py').replace('/', '.')}.{node.name}"
638
+ )
639
+ if qualified in self.async_specs:
640
+ self.env[node.name] = _Binding(qualified)
641
+
642
+ def visit_FunctionDef(self, node: Function) -> None:
643
+ outer, test = self.env, self.test
644
+ outer_outputs = self.fixture_outputs
645
+ outer_yielded = self.fixture_yielded
646
+ fixture = any(
647
+ self.qualified(
648
+ decorator.func if isinstance(decorator, ast.Call) else decorator
649
+ )
650
+ in {"pytest.fixture", "pytest_asyncio.fixture"}
651
+ for decorator in node.decorator_list
652
+ )
653
+ collected = (
654
+ self.function_depth == 0
655
+ and node.name.startswith("test_")
656
+ and (
657
+ self.class_name is None
658
+ or self.class_name.startswith("Test")
659
+ or self.unittest
660
+ )
661
+ )
662
+ self.test = (
663
+ TestFunction(
664
+ node, f"{self.class_name}.{node.name}" if self.class_name else node.name
665
+ )
666
+ if collected
667
+ else None
668
+ )
669
+ if self.test:
670
+ self.result.tests.append(self.test)
671
+ for expression in [
672
+ *node.decorator_list,
673
+ *node.args.defaults,
674
+ *(value for value in node.args.kw_defaults if value is not None),
675
+ ]:
676
+ self.visit(expression)
677
+ self.env = dict(
678
+ self.module_env if self.class_name and self.function_depth == 0 else outer
679
+ )
680
+ for name in _locals(node.body):
681
+ self.env.pop(name, None)
682
+ arguments = [*node.args.posonlyargs, *node.args.args, *node.args.kwonlyargs]
683
+ arguments += [
684
+ arg for arg in (node.args.vararg, node.args.kwarg) if arg is not None
685
+ ]
686
+ for arg in arguments:
687
+ self.env.pop(arg.arg, None)
688
+ class_fixture = f"{self.class_name}.{arg.arg}"
689
+ fixture_key = class_fixture if class_fixture in self.fixtures else arg.arg
690
+ annotation = (
691
+ _annotation(arg.annotation, self.env) if arg.annotation else None
692
+ )
693
+ if (
694
+ self.function_depth == 0
695
+ and (collected or fixture)
696
+ and fixture_key in self.fixtures
697
+ ):
698
+ self.env[arg.arg] = self.fixtures[fixture_key]
699
+ if annotation:
700
+ existing = self.env.get(arg.arg)
701
+ self.env[arg.arg] = (
702
+ existing
703
+ if existing and existing.qualified == annotation
704
+ else _instance(annotation, "annotation")
705
+ )
706
+ binding = self.env.get(arg.arg)
707
+ if binding and binding.kind == "mock" and binding.mock_origin is None:
708
+ self.env[arg.arg] = replace(
709
+ binding,
710
+ mock_origin=f"{self.result.path}:{node.lineno}:{arg.arg}",
711
+ )
712
+ if self.function_depth == 0 and (
713
+ (
714
+ arg.arg in _MOCKER_FIXTURES
715
+ and (collected or fixture)
716
+ and fixture_key not in self.fixtures
717
+ and annotation is None
718
+ )
719
+ or (
720
+ arg.annotation is not None
721
+ and self.qualified(arg.annotation) == "pytest_mock.MockerFixture"
722
+ )
723
+ ):
724
+ self.env[arg.arg] = _Binding(
725
+ "pytest_mock.MockerFixture", provenance="fixture"
726
+ )
727
+ if (
728
+ self.function_depth == 0
729
+ and arg.arg == "monkeypatch"
730
+ and (collected or fixture)
731
+ and fixture_key not in self.fixtures
732
+ and annotation is None
733
+ ):
734
+ self.env[arg.arg] = _instance(_MONKEYPATCH, "fixture")
735
+ if self.unittest and node.args.args:
736
+ self.env[node.args.args[0].arg] = _instance(
737
+ "unittest.TestCase", "unittest-self"
738
+ )
739
+ self.fixture_outputs = [] if fixture else None
740
+ self.fixture_yielded = False
741
+ self.function_depth += 1
742
+ for statement in node.body:
743
+ self.visit(statement)
744
+ self.function_depth -= 1
745
+ if fixture:
746
+ self.record_fixture(node, outer)
747
+ self.env = outer
748
+ self.test = test
749
+ self.fixture_outputs = outer_outputs
750
+ self.fixture_yielded = outer_yielded
751
+ self.env.pop(node.name, None)
752
+
753
+ def record_fixture(self, node: Function, env: Mapping[str, _Binding]) -> None:
754
+ if self.function_depth != 0:
755
+ return
756
+ binding = _fixture_binding(node.returns, env) if node.returns else None
757
+ outputs = self.fixture_outputs
758
+ if (
759
+ outputs
760
+ and outputs[0] is not None
761
+ and all(output == outputs[0] for output in outputs)
762
+ and (self.fixture_yielded or isinstance(node.body[-1], ast.Return))
763
+ ):
764
+ inferred = _inferred_fixture(outputs[0])
765
+ if not node.returns:
766
+ binding = inferred
767
+ elif (
768
+ binding
769
+ and binding.kind == "mock"
770
+ and binding.qualified == inferred.qualified
771
+ ):
772
+ binding = replace(inferred, provenance="fixture-return")
773
+ fixture_name = node.name
774
+ for decorator in node.decorator_list:
775
+ if isinstance(decorator, ast.Call):
776
+ for keyword in decorator.keywords:
777
+ if (
778
+ keyword.arg == "name"
779
+ and isinstance(keyword.value, ast.Constant)
780
+ and isinstance(keyword.value.value, str)
781
+ ):
782
+ fixture_name = keyword.value.value
783
+ fixture_key = (
784
+ f"{self.class_name}.{fixture_name}" if self.class_name else fixture_name
785
+ )
786
+ self.defined_fixtures[fixture_key] = binding or _Binding(
787
+ "", provenance="unknown-fixture"
788
+ )
789
+
790
+ def visit_AsyncFunctionDef(self, node: ast.AsyncFunctionDef) -> None:
791
+ self.visit_FunctionDef(node)
792
+
793
+ def visit_Call(self, node: ast.Call) -> None:
794
+ binding = self.binding(node.func)
795
+ if binding:
796
+ call = TestCall(
797
+ node, binding.qualified, binding.provenance, binding.kind == "mock"
798
+ )
799
+ self.result.calls.append(call)
800
+ if self.test:
801
+ self.test.calls.append(call)
802
+ if checked_python_assertions(
803
+ node, binding.qualified, self.qualified, self._literal_text
804
+ ):
805
+ self.test.child_assertions.append(node)
806
+ result = self.value_binding(node)
807
+ if result and result.kind == "nonempty":
808
+ self.test.nonempty_iterables.add(node)
809
+ if (
810
+ binding.qualified == f"{_MONKEYPATCH}.setattr"
811
+ and len(node.args) > 1
812
+ and self.qualified(node.args[0]) == "asyncio.AbstractEventLoop"
813
+ and isinstance(node.args[1], ast.Constant)
814
+ and node.args[1].value == "time"
815
+ ):
816
+ self.test.clock_replacements.append(node)
817
+ if isinstance(node.func, ast.Attribute):
818
+ name = node.func.attr
819
+ if name in _MOCK_ASSERTIONS and name != "assert_not_called":
820
+ self.record_mock_observation(
821
+ node,
822
+ node.func.value,
823
+ "await" if "await" in name else "call",
824
+ )
825
+ self.generic_visit(node)
826
+
827
+ # Unknown calls can mutate an escaped local collection, including through
828
+ # a closure or alias. Evidence at earlier reads remains valid; subsequent
829
+ # reads must establish cardinality again.
830
+ self._forget_mutable_iterables()
831
+
832
+ def record_mock_observation(
833
+ self, node: ast.Call | ast.Attribute, receiver: ast.expr, kind: str
834
+ ) -> None:
835
+ binding = self.binding(receiver)
836
+ if self.test and binding and binding.async_callable and binding.mock_origin:
837
+ self.test.mock_observations.append(
838
+ MockObservation(
839
+ node,
840
+ binding.mock_origin,
841
+ ast.unparse(receiver),
842
+ kind,
843
+ binding.async_callable,
844
+ binding.provenance,
845
+ )
846
+ )
847
+
848
+ def visit_Name(self, node: ast.Name) -> None:
849
+ binding = self.env.get(node.id)
850
+ if (
851
+ self.test
852
+ and isinstance(node.ctx, ast.Load)
853
+ and binding
854
+ and binding.kind == "nonempty"
855
+ ):
856
+ self.test.nonempty_iterables.add(node)
857
+
858
+ def visit_Attribute(self, node: ast.Attribute) -> None:
859
+ qualified = self.qualified(node)
860
+ receiver = self.binding(node.value)
861
+ if (
862
+ qualified == "asyncio.AbstractEventLoop.time"
863
+ and isinstance(node.ctx, ast.Store)
864
+ and self.test
865
+ ):
866
+ self.test.clock_replacements.append(node)
867
+ if qualified and receiver and receiver.kind == "instance":
868
+ if isinstance(node.ctx, ast.Load):
869
+ self.result.instance_attributes.append(
870
+ (node, qualified, receiver.provenance)
871
+ )
872
+ elif qualified:
873
+ self.result.attributes.append((node, qualified))
874
+ if isinstance(node.ctx, ast.Load):
875
+ if node.attr in {"called", "call_count", "call_args", "call_args_list"}:
876
+ self.record_mock_observation(node, node.value, "call")
877
+ elif node.attr in {"await_count", "await_args", "await_args_list"}:
878
+ self.record_mock_observation(node, node.value, "await")
879
+ self.generic_visit(node)
880
+
881
+ def visit_Assert(self, node: ast.Assert) -> None:
882
+ if self.test:
883
+ self.test.assertions.append(node)
884
+ self.generic_visit(node)
885
+
886
+ def visit_Await(self, node: ast.Await) -> None:
887
+ binding = self.binding(node.value)
888
+ if (
889
+ self.test
890
+ and binding
891
+ and binding.kind == "instance"
892
+ and binding.qualified in {"asyncio.Task", "asyncio.Future"}
893
+ ):
894
+ self.test.awaited_tasks.append(
895
+ (node, binding.qualified, binding.provenance)
896
+ )
897
+ self.generic_visit(node)
898
+
899
+ def visit_Return(self, node: ast.Return) -> None:
900
+ self.generic_visit(node)
901
+ if self.fixture_outputs is not None:
902
+ self.fixture_outputs.append(
903
+ self.value_binding(node.value) if node.value else None
904
+ )
905
+
906
+ def visit_Yield(self, node: ast.Yield) -> None:
907
+ self.generic_visit(node)
908
+ if self.fixture_outputs is not None:
909
+ self.fixture_yielded = True
910
+ self.fixture_outputs.append(
911
+ self.value_binding(node.value) if node.value else None
912
+ )
913
+
914
+ def visit_YieldFrom(self, node: ast.YieldFrom) -> None:
915
+ self.generic_visit(node)
916
+ if self.fixture_outputs is not None:
917
+ self.fixture_outputs.append(None)
918
+
919
+ def bind_target(self, target: ast.AST, binding: _Binding | None) -> None:
920
+ for name in _names(target):
921
+ self.env.pop(name, None)
922
+ if isinstance(target, ast.Name) and binding:
923
+ self.env[target.id] = (
924
+ replace(
925
+ binding,
926
+ mock_origin=f"{self.result.path}:{target.lineno}:{target.id}",
927
+ )
928
+ if binding.kind == "mock" and binding.mock_origin is None
929
+ else binding
930
+ )
931
+ elif (
932
+ isinstance(target, ast.Tuple | ast.List)
933
+ and binding
934
+ and binding.items is not None
935
+ and len(target.elts) == len(binding.items)
936
+ ):
937
+ for item, value in zip(target.elts, binding.items, strict=True):
938
+ self.bind_target(item, value)
939
+
940
+ def forget_mock_spec(self, target: ast.AST) -> None:
941
+ if not isinstance(target, ast.Attribute):
942
+ return
943
+ receiver = self.binding(target.value)
944
+ if receiver and receiver.mock_spec and receiver.mock_origin:
945
+ for name, binding in list(self.env.items()):
946
+ if binding.mock_origin == receiver.mock_origin:
947
+ self.env[name] = replace(binding, mock_spec=None)
948
+
949
+ def visit_Assign(self, node: ast.Assign) -> None:
950
+ self.visit(node.value)
951
+ binding = self.value_binding(node.value)
952
+ for target in node.targets:
953
+ self.visit(target)
954
+ self.forget_mock_spec(target)
955
+ self.bind_target(target, binding)
956
+ if isinstance(target, ast.Subscript | ast.Attribute):
957
+ self._forget_mutable_iterables()
958
+ if (
959
+ isinstance(target, ast.Attribute)
960
+ and self.qualified(target) == "sys.executable"
961
+ and isinstance(target.value, ast.Name)
962
+ ):
963
+ self.env.pop(target.value.id, None)
964
+
965
+ def visit_AnnAssign(self, node: ast.AnnAssign) -> None:
966
+ self.visit(node.target)
967
+ if node.value:
968
+ self.visit(node.value)
969
+ self.forget_mock_spec(node.target)
970
+ for name in _names(node.target):
971
+ self.env.pop(name, None)
972
+ annotation = _annotation(node.annotation, self.env)
973
+ if isinstance(node.target, ast.Name):
974
+ value = self.value_binding(node.value) if node.value else None
975
+ binding = (
976
+ value
977
+ if value and (value.kind == "nonempty" or value.qualified == annotation)
978
+ else _instance(annotation, "annotation")
979
+ if annotation
980
+ else None
981
+ )
982
+ self.bind_target(node.target, binding)
983
+ elif node.value:
984
+ self._forget_mutable_iterables()
985
+
986
+ def visit_AugAssign(self, node: ast.AugAssign) -> None:
987
+ self.visit(node.value)
988
+ self._forget_mutable_iterables()
989
+ for name in _names(node.target):
990
+ self.env.pop(name, None)
991
+
992
+ def visit_Delete(self, node: ast.Delete) -> None:
993
+ self._forget_mutable_iterables()
994
+ for target in node.targets:
995
+ self.forget_mock_spec(target)
996
+ for name in _names(target):
997
+ self.env.pop(name, None)
998
+
999
+ def visit_If(self, node: ast.If) -> None:
1000
+ self.visit(node.test)
1001
+ self._branches([node.body, node.orelse])
1002
+
1003
+ def visit_For(self, node: ast.For | ast.AsyncFor) -> None:
1004
+ self.visit(node.iter)
1005
+ for name in _names(node.target):
1006
+ self.env.pop(name, None)
1007
+ self._branches([node.body, node.orelse])
1008
+
1009
+ def visit_AsyncFor(self, node: ast.AsyncFor) -> None:
1010
+ self.visit_For(node)
1011
+
1012
+ def visit_While(self, node: ast.While) -> None:
1013
+ self.visit(node.test)
1014
+ self._branches([node.body, node.orelse])
1015
+
1016
+ def visit_With(self, node: ast.With | ast.AsyncWith) -> None:
1017
+ for item in node.items:
1018
+ self.visit(item.context_expr)
1019
+ binding = self.value_binding(item.context_expr, context=True)
1020
+ if item.optional_vars:
1021
+ for name in _names(item.optional_vars):
1022
+ self.env.pop(name, None)
1023
+ if isinstance(item.optional_vars, ast.Name) and binding:
1024
+ self.env[item.optional_vars.id] = binding
1025
+ for statement in node.body:
1026
+ self.visit(statement)
1027
+
1028
+ def visit_AsyncWith(self, node: ast.AsyncWith) -> None:
1029
+ self.visit_With(node)
1030
+
1031
+ def visit_Try(self, node: ast.Try | ast.TryStar) -> None:
1032
+ self._branches(
1033
+ [node.body, *([handler] for handler in node.handlers), node.orelse]
1034
+ )
1035
+ for statement in node.finalbody:
1036
+ self.visit(statement)
1037
+
1038
+ def visit_TryStar(self, node: ast.TryStar) -> None:
1039
+ self.visit_Try(node)
1040
+
1041
+ def visit_ExceptHandler(self, node: ast.ExceptHandler) -> None:
1042
+ if node.type:
1043
+ self.visit(node.type)
1044
+ if node.name:
1045
+ self.env.pop(node.name, None)
1046
+ for statement in node.body:
1047
+ self.visit(statement)
1048
+
1049
+ def visit_NamedExpr(self, node: ast.NamedExpr) -> None:
1050
+ self.visit(node.value)
1051
+ for name in _names(node.target):
1052
+ self.env.pop(name, None)
1053
+
1054
+ def visit_Lambda(self, node: ast.Lambda) -> None:
1055
+ outer, test = self.env, self.test
1056
+ for value in [
1057
+ *node.args.defaults,
1058
+ *(v for v in node.args.kw_defaults if v is not None),
1059
+ ]:
1060
+ self.visit(value)
1061
+ self.env = dict(outer)
1062
+ self.test = None
1063
+ for arg in [
1064
+ *node.args.posonlyargs,
1065
+ *node.args.args,
1066
+ *node.args.kwonlyargs,
1067
+ *[a for a in (node.args.vararg, node.args.kwarg) if a],
1068
+ ]:
1069
+ self.env.pop(arg.arg, None)
1070
+ self.visit(node.body)
1071
+ self.env = outer
1072
+ self.test = test
1073
+
1074
+ def visit_ListComp(
1075
+ self, node: ast.ListComp | ast.SetComp | ast.GeneratorExp | ast.DictComp
1076
+ ) -> None:
1077
+ outer = self.env
1078
+ self.env = dict(outer)
1079
+ for generator in node.generators:
1080
+ self.visit(generator.iter)
1081
+ for name in _names(generator.target):
1082
+ self.env.pop(name, None)
1083
+ for condition in generator.ifs:
1084
+ self.visit(condition)
1085
+ for value in (
1086
+ [node.key, node.value] if isinstance(node, ast.DictComp) else [node.elt]
1087
+ ):
1088
+ self.visit(value)
1089
+ self.env = outer
1090
+
1091
+ self._forget_mutable_iterables()
1092
+
1093
+ def visit_SetComp(self, node: ast.SetComp) -> None:
1094
+ self.visit_ListComp(node)
1095
+
1096
+ def visit_DictComp(self, node: ast.DictComp) -> None:
1097
+ self.visit_ListComp(node)
1098
+
1099
+ def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None:
1100
+ test = self.test
1101
+ # Only the outer iterable is evaluated in this scope at construction.
1102
+ binding = self.value_binding(node.generators[0].iter)
1103
+ if test and binding and binding.kind == "nonempty":
1104
+ test.nonempty_iterables.add(node.generators[0].iter)
1105
+ self.test = None
1106
+ self.visit_ListComp(node)
1107
+ self.test = test
1108
+
1109
+ def visit_Match(self, node: ast.Match) -> None:
1110
+ self.visit(node.subject)
1111
+ outer = self.env
1112
+ for case in node.cases:
1113
+ self.env = dict(outer)
1114
+ for name in _expression_bindings(case.pattern):
1115
+ self.env.pop(name, None)
1116
+ if case.guard:
1117
+ self.visit(case.guard)
1118
+ for statement in case.body:
1119
+ self.visit(statement)
1120
+ self.env = outer
1121
+ self._forget_mutable_iterables()
1122
+ for name in _locals([node]):
1123
+ self.env.pop(name, None)
1124
+
1125
+ def _branches(self, bodies: Sequence[Sequence[ast.AST]]) -> None:
1126
+ outer = self.env
1127
+ for body in bodies:
1128
+ self.env = dict(outer)
1129
+ for statement in body:
1130
+ self.visit(statement)
1131
+ self.env = outer
1132
+ self._forget_mutable_iterables()
1133
+ for name in _locals([statement for body in bodies for statement in body]):
1134
+ self.env.pop(name, None)
1135
+
1136
+ def _forget_mutable_iterables(self) -> None:
1137
+ for name, binding in list(self.env.items()):
1138
+ if binding.mutable:
1139
+ self.env.pop(name)
1140
+
1141
+ def _literal_text(self, node: ast.expr) -> str | None:
1142
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
1143
+ return node.value
1144
+ binding = self.env.get(node.id) if isinstance(node, ast.Name) else None
1145
+ return binding.text if binding else None
1146
+
1147
+
1148
+ def _declared_fixtures(
1149
+ tree: ast.Module,
1150
+ path: str,
1151
+ constructors: frozenset[str],
1152
+ inherited: Mapping[str, _Binding],
1153
+ async_specs: Mapping[str, frozenset[str]],
1154
+ ) -> dict[str, _Binding]:
1155
+ """Annotations or consistent known returns/yields, never fixture execution."""
1156
+ visitor = _Visitor(TestModule(path), constructors, inherited, async_specs)
1157
+ visitor.visit(tree)
1158
+ return visitor.defined_fixtures
1159
+
1160
+
1161
+ def _analyze_test_syntax(
1162
+ tree: ast.Module,
1163
+ path: str,
1164
+ *,
1165
+ constructors: frozenset[str] = frozenset(),
1166
+ fixtures: Mapping[str, _Binding] | None = None,
1167
+ async_specs: Mapping[str, frozenset[str]] | None = None,
1168
+ ) -> TestModule:
1169
+ module = TestModule(path)
1170
+ specs = {
1171
+ **(async_specs or {}),
1172
+ **_class_async_methods(tree, path.removesuffix(".py").replace("/", ".")),
1173
+ }
1174
+ _Visitor(
1175
+ module,
1176
+ constructors,
1177
+ {
1178
+ **(fixtures or {}),
1179
+ **_declared_fixtures(tree, path, constructors, fixtures or {}, specs),
1180
+ },
1181
+ specs,
1182
+ ).visit(tree)
1183
+ return module
1184
+
1185
+
1186
+ def _fixture_facts(
1187
+ asts: AstCache,
1188
+ path: str,
1189
+ constructors: frozenset[str],
1190
+ inherited: dict[str, _Binding],
1191
+ async_specs: dict[str, frozenset[str]],
1192
+ ) -> dict[str, _Binding]:
1193
+ return _declared_fixtures(
1194
+ asts.parse(path), path, constructors, inherited, async_specs
1195
+ )
1196
+
1197
+
1198
+ @dataclass
1199
+ class TestReferences:
1200
+ imports: list[tuple[int, str]]
1201
+ attributes: list[tuple[int, str, bool]]
1202
+ instance_attributes: list[tuple[int, str, bool]]
1203
+
1204
+
1205
+ _REFERENCES = TypeAdapter(TestReferences)
1206
+ _COUNT = TypeAdapter(int)
1207
+
1208
+
1209
+ class _TestModules(Mapping[str, TestModule]):
1210
+ def __init__(
1211
+ self, paths: tuple[str, ...], load: Callable[[str], TestModule]
1212
+ ) -> None:
1213
+ self.paths = dict.fromkeys(paths)
1214
+ self._load = load
1215
+ self._cache: dict[str, TestModule] = {}
1216
+
1217
+ def __len__(self) -> int:
1218
+ return len(self.paths)
1219
+
1220
+ def __iter__(self) -> Iterator[str]:
1221
+ return iter(self.paths)
1222
+
1223
+ def __getitem__(self, path: str) -> TestModule:
1224
+ if path not in self.paths:
1225
+ raise KeyError(path)
1226
+ if path not in self._cache:
1227
+ self._cache[path] = self._load(path)
1228
+ return self._cache[path]
1229
+
1230
+
1231
+ class TestSyntaxIndex:
1232
+ def __init__(
1233
+ self,
1234
+ files: FileIndex,
1235
+ asts: AstCache,
1236
+ *,
1237
+ cache: FactCache | None = None,
1238
+ syntax: SyntaxIndex | None = None,
1239
+ ) -> None:
1240
+ self._cache = cache
1241
+ self._files = files
1242
+ self._inputs: dict[str, object] = {}
1243
+ config = files.config.tests
1244
+
1245
+ # The engine requests this index for selected rules. Evidence is shared
1246
+ # across those rules rather than gated by separate policy switches.
1247
+ def specs(path: str, module: str) -> dict[str, frozenset[str]]:
1248
+ def build() -> dict[str, frozenset[str]]:
1249
+ return _class_async_methods(asts.parse(path), module)
1250
+
1251
+ return (
1252
+ build()
1253
+ if cache is None
1254
+ else cache.get(
1255
+ "test-source-specs",
1256
+ [path, module, files.content_id(path)],
1257
+ _ASYNC_SPECS,
1258
+ build,
1259
+ )
1260
+ )
1261
+
1262
+ source_specs = {
1263
+ qualified: methods
1264
+ for source in files.sources.values()
1265
+ for qualified, methods in specs(source.path, source.module).items()
1266
+ }
1267
+ constructors = frozenset(source_specs)
1268
+ async_specs = dict(source_specs)
1269
+ if source_specs:
1270
+ namespaces = {
1271
+ source.module: syntax.namespace(source.module)
1272
+ if syntax is not None
1273
+ else namespace_of(
1274
+ asts.parse(source.path), source.module, is_package=source.is_package
1275
+ )
1276
+ for source in files.sources.values()
1277
+ }
1278
+ aliases = {
1279
+ f"{module}.{name}": f"{resolved[0]}.{resolved[1]}"
1280
+ for module, namespace in namespaces.items()
1281
+ if namespace is not None
1282
+ for name in namespace.imported
1283
+ if (resolved := resolve_dotted(f"{module}.{name}", namespaces.get))
1284
+ is not None
1285
+ and f"{resolved[0]}.{resolved[1]}" in source_specs
1286
+ }
1287
+ constructors |= frozenset(aliases)
1288
+ async_specs.update(
1289
+ (alias, source_specs[target]) for alias, target in aliases.items()
1290
+ )
1291
+ fixture_scopes: dict[str, dict[str, _Binding]] = {}
1292
+ for path in sorted(files.tests, key=lambda path: (path.count("/"), path)):
1293
+ if not path.endswith("conftest.py") or any(
1294
+ path_matches(pattern, path) for pattern in config.quality_exclude
1295
+ ):
1296
+ continue
1297
+ inherited = {
1298
+ name: binding
1299
+ for scope, bindings in fixture_scopes.items()
1300
+ if path.startswith(scope)
1301
+ for name, binding in bindings.items()
1302
+ }
1303
+ async_specs.update(specs(path, path.removesuffix(".py").replace("/", ".")))
1304
+
1305
+ build_fixtures = partial(
1306
+ _fixture_facts, asts, path, constructors, inherited, async_specs
1307
+ )
1308
+
1309
+ fixture_scopes[path.removesuffix("conftest.py")] = (
1310
+ build_fixtures()
1311
+ if cache is None
1312
+ else cache.get(
1313
+ "test-fixtures",
1314
+ [
1315
+ path,
1316
+ files.content_id(path),
1317
+ sorted(constructors),
1318
+ _BINDINGS.dump_python(inherited, mode="json"),
1319
+ [
1320
+ (name, sorted(methods))
1321
+ for name, methods in sorted(async_specs.items())
1322
+ ],
1323
+ ],
1324
+ _BINDINGS,
1325
+ build_fixtures,
1326
+ )
1327
+ )
1328
+ environment = hashlib.sha256(
1329
+ json.dumps(
1330
+ [
1331
+ sorted(constructors),
1332
+ [
1333
+ (name, sorted(methods))
1334
+ for name, methods in sorted(async_specs.items())
1335
+ ],
1336
+ ],
1337
+ sort_keys=True,
1338
+ ).encode()
1339
+ ).hexdigest()
1340
+ fixtures_by_path: dict[str, dict[str, _Binding]] = {}
1341
+ for path in sorted(files.tests):
1342
+ if any(path_matches(pattern, path) for pattern in config.quality_exclude):
1343
+ continue
1344
+ fixtures = {
1345
+ name: binding
1346
+ for scope in sorted(fixture_scopes, key=len)
1347
+ if path.startswith(scope)
1348
+ for name, binding in fixture_scopes[scope].items()
1349
+ }
1350
+ fixtures_by_path[path] = fixtures
1351
+ self._inputs[path] = [
1352
+ path,
1353
+ files.content_id(path),
1354
+ environment,
1355
+ _BINDINGS.dump_python(fixtures, mode="json"),
1356
+ ]
1357
+
1358
+ def load(path: str) -> TestModule:
1359
+ module = _analyze_test_syntax(
1360
+ asts.parse(path),
1361
+ path,
1362
+ constructors=constructors,
1363
+ fixtures=fixtures_by_path[path],
1364
+ async_specs=async_specs,
1365
+ )
1366
+ if cache is not None:
1367
+ cache.write(
1368
+ cache.key("test-count", self.inputs(path)),
1369
+ len(module.tests),
1370
+ _COUNT,
1371
+ )
1372
+ return module
1373
+
1374
+ self.modules: Mapping[str, TestModule] = _TestModules(
1375
+ tuple(fixtures_by_path), load
1376
+ )
1377
+
1378
+ def inputs(self, path: str) -> object:
1379
+ return self._inputs[path]
1380
+
1381
+ def for_file(self, path: str) -> TestSyntaxIndex:
1382
+ view = copy(self)
1383
+ view.modules = {path: self.modules[path]}
1384
+ return view
1385
+
1386
+ def collected_tests(self) -> int:
1387
+ def count(path: str) -> int:
1388
+ return len(self.modules[path].tests)
1389
+
1390
+ return sum(
1391
+ count(path)
1392
+ if self._cache is None
1393
+ else self._cache.get(
1394
+ "test-count", self.inputs(path), _COUNT, partial(count, path)
1395
+ )
1396
+ for path in self.modules
1397
+ )
1398
+
1399
+ def references(self) -> Iterator[tuple[str, TestReferences]]:
1400
+ def extract(path: str) -> TestReferences:
1401
+ module = self.modules[path]
1402
+ return TestReferences(
1403
+ [(node.lineno, name) for node, name in module.imports],
1404
+ [
1405
+ (node.lineno, name, isinstance(node.ctx, ast.Load))
1406
+ for node, name in module.attributes
1407
+ ],
1408
+ [
1409
+ (node.lineno, name, isinstance(node.ctx, ast.Load))
1410
+ for node, name, _ in module.instance_attributes
1411
+ ],
1412
+ )
1413
+
1414
+ for path in self.modules:
1415
+ cached = (
1416
+ extract(path)
1417
+ if self._cache is None
1418
+ else self._cache.get(
1419
+ "test-references",
1420
+ self.inputs(path),
1421
+ _REFERENCES,
1422
+ partial(extract, path),
1423
+ )
1424
+ )
1425
+ yield path, cached