quod-probe 0.4.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.
- quod_probe/__init__.py +10 -0
- quod_probe/__main__.py +39 -0
- quod_probe/capture.py +652 -0
- quod_probe/fingerprint.py +232 -0
- quod_probe/imports.py +221 -0
- quod_probe/packages.py +169 -0
- quod_probe/plugin.py +436 -0
- quod_probe-0.4.0.dist-info/METADATA +47 -0
- quod_probe-0.4.0.dist-info/RECORD +11 -0
- quod_probe-0.4.0.dist-info/WHEEL +4 -0
- quod_probe-0.4.0.dist-info/entry_points.txt +2 -0
quod_probe/__init__.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""Quod Python probe: records which code, files and packages each test observes."""
|
|
2
|
+
|
|
3
|
+
__version__ = "0.4.0"
|
|
4
|
+
PROBE_ID = f"python-probe/{__version__}"
|
|
5
|
+
CAPTURE_VERSION = 1
|
|
6
|
+
# Capabilities declared in the capture header. ``py.introspection``: signature
|
|
7
|
+
# and annotation introspection is recorded as a use of the function.
|
|
8
|
+
# ``py.environment``: the header carries environment and invocation
|
|
9
|
+
# fingerprints, and environment variable reads are recorded (ADR 012).
|
|
10
|
+
CAPABILITIES = ("py.environment", "py.introspection")
|
quod_probe/__main__.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""``python -m quod_probe fingerprint [--env NAME]...``
|
|
2
|
+
|
|
3
|
+
Prints this environment's fingerprint as JSON, for ``quod select
|
|
4
|
+
--python``: ``{"environment": {...}, "env": {NAME: hash}}``. ``*`` hashes the
|
|
5
|
+
whole environment.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import argparse
|
|
11
|
+
import json
|
|
12
|
+
import os
|
|
13
|
+
import sys
|
|
14
|
+
|
|
15
|
+
from . import PROBE_ID, fingerprint
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def main(argv: list[str] | None = None) -> int:
|
|
19
|
+
ap = argparse.ArgumentParser(prog="python -m quod_probe")
|
|
20
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
21
|
+
fp = sub.add_parser("fingerprint", help="print the environment fingerprint")
|
|
22
|
+
fp.add_argument("--env", action="append", default=[], metavar="NAME")
|
|
23
|
+
args = ap.parse_args(argv)
|
|
24
|
+
if args.cmd == "fingerprint":
|
|
25
|
+
env = {
|
|
26
|
+
n: fingerprint.environ_hash() if n == "*" else fingerprint.env_value_hash(os.environ.get(n))
|
|
27
|
+
for n in args.env
|
|
28
|
+
}
|
|
29
|
+
json.dump(
|
|
30
|
+
{"probe": PROBE_ID, "environment": fingerprint.environment(), "env": env},
|
|
31
|
+
sys.stdout,
|
|
32
|
+
sort_keys=True,
|
|
33
|
+
)
|
|
34
|
+
sys.stdout.write("\n")
|
|
35
|
+
return 0
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
if __name__ == "__main__":
|
|
39
|
+
raise SystemExit(main())
|
quod_probe/capture.py
ADDED
|
@@ -0,0 +1,652 @@
|
|
|
1
|
+
"""Low-level capture: code execution via sys.monitoring, I/O via audit hooks.
|
|
2
|
+
|
|
3
|
+
Observations go to every *collector* on the active stack. Collectors are
|
|
4
|
+
pushed for a test, for a non-function-scoped fixture's setup, and for a test
|
|
5
|
+
module's import during collection. With the stack empty (plugin start,
|
|
6
|
+
conftest import, session start), observations go to the *root* collector,
|
|
7
|
+
whose changes affect every test (rule R017).
|
|
8
|
+
|
|
9
|
+
Each code object fires ``PY_START`` once and is then disabled. At every test
|
|
10
|
+
boundary, ``sys.monitoring.restart_events()`` re-enables everything, so each
|
|
11
|
+
test pays for one callback per distinct function it runs. This is the
|
|
12
|
+
technique coverage tools use for per-test contexts.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import os
|
|
18
|
+
import site
|
|
19
|
+
import sys
|
|
20
|
+
import sysconfig
|
|
21
|
+
import threading
|
|
22
|
+
from dataclasses import dataclass, field
|
|
23
|
+
from types import CodeType, FunctionType, MethodType
|
|
24
|
+
|
|
25
|
+
from .packages import PackageIndex, PackageInfo
|
|
26
|
+
|
|
27
|
+
FLAG_NETWORK = "network"
|
|
28
|
+
FLAG_SUBPROCESS = "subprocess"
|
|
29
|
+
FLAG_DYNAMIC_IMPORT = "dynamic_import"
|
|
30
|
+
FLAG_C_EXT = "c_ext"
|
|
31
|
+
FLAG_UNTRACED = "untraced"
|
|
32
|
+
|
|
33
|
+
_SUBPROCESS_EVENTS = frozenset(
|
|
34
|
+
{"subprocess.Popen", "os.system", "os.posix_spawn", "os.spawn", "os.exec", "os.startfile", "pty.spawn"}
|
|
35
|
+
)
|
|
36
|
+
_LISTING_EVENTS = frozenset({"os.listdir", "os.scandir", "glob.glob", "os.walk"})
|
|
37
|
+
# Directories holding the test runner's own state, not test inputs.
|
|
38
|
+
_RUNNER_STATE = frozenset({".pytest_cache", "__pycache__"})
|
|
39
|
+
_LOOPBACK_PREFIXES = ("127.", "::1", "localhost", "0:0:0:0:0:0:0:1")
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@dataclass
|
|
43
|
+
class Collector:
|
|
44
|
+
"""A set of observations."""
|
|
45
|
+
|
|
46
|
+
files: set[str] = field(default_factory=set)
|
|
47
|
+
functions: set[tuple[str, str]] = field(default_factory=set)
|
|
48
|
+
packages: set[str] = field(default_factory=set)
|
|
49
|
+
flags: set[str] = field(default_factory=set)
|
|
50
|
+
# Environment variables read from outside the process: name -> value hash.
|
|
51
|
+
# ``*`` is the whole environment (iteration).
|
|
52
|
+
env: dict[str, str] = field(default_factory=dict)
|
|
53
|
+
# Import closures already merged in (``imports.ImportTracker``), by id.
|
|
54
|
+
closures_merged: set[int] = field(default_factory=set, compare=False, repr=False)
|
|
55
|
+
# Cached imports already recorded: (absolute name, fromlist).
|
|
56
|
+
imports_seen: set[tuple] = field(default_factory=set, compare=False, repr=False)
|
|
57
|
+
|
|
58
|
+
def merge(self, other: "Collector") -> None:
|
|
59
|
+
self.files |= other.files
|
|
60
|
+
self.functions |= other.functions
|
|
61
|
+
self.packages |= other.packages
|
|
62
|
+
self.flags |= other.flags
|
|
63
|
+
self.env.update(other.env)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def entity_qualname(co_qualname: str) -> str | None:
|
|
67
|
+
"""Maps a runtime ``co_qualname`` to the entity name ``quod-change`` emits.
|
|
68
|
+
|
|
69
|
+
Lambdas, comprehensions and generator expressions belong to their
|
|
70
|
+
enclosing def or class. ``None`` means module level.
|
|
71
|
+
|
|
72
|
+
>>> entity_qualname("f.<locals>.<lambda>")
|
|
73
|
+
'f'
|
|
74
|
+
>>> entity_qualname("C.m")
|
|
75
|
+
'C.m'
|
|
76
|
+
>>> entity_qualname("<lambda>") is None
|
|
77
|
+
True
|
|
78
|
+
"""
|
|
79
|
+
parts = co_qualname.split(".")
|
|
80
|
+
while parts and parts[-1].startswith("<"):
|
|
81
|
+
parts.pop()
|
|
82
|
+
if parts and parts[-1] == "<locals>":
|
|
83
|
+
parts.pop()
|
|
84
|
+
return ".".join(parts) if parts else None
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class CacheTracker:
|
|
88
|
+
"""Clears ``functools`` caches at every test boundary during recording.
|
|
89
|
+
|
|
90
|
+
A cached function hit from an earlier test executes no Python code, so the
|
|
91
|
+
probe can't see that the test depends on it. A change to the function then
|
|
92
|
+
goes unnoticed, which is unsound. Clearing ``lru_cache``/``cache`` wrappers
|
|
93
|
+
and ``cached_property`` values before each test makes every test recompute,
|
|
94
|
+
and therefore record, what it uses.
|
|
95
|
+
|
|
96
|
+
``functools.lru_cache``, ``functools.cache`` and ``functools.cached_property``
|
|
97
|
+
are replaced by registering equivalents before project code is imported
|
|
98
|
+
(the recorder starts before the initial conftests load). Caches created
|
|
99
|
+
earlier, by already-imported third-party or stdlib modules, aren't tracked.
|
|
100
|
+
Their code is covered by package and interpreter identity instead.
|
|
101
|
+
|
|
102
|
+
Hand-written memo dictionaries aren't tracked. The probe assumes tests
|
|
103
|
+
don't depend on state left behind by other tests except through these
|
|
104
|
+
caches. The post-merge audit is what catches violations.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(self) -> None:
|
|
108
|
+
self._wrappers: list = []
|
|
109
|
+
self._properties: list[tuple[object, str]] = []
|
|
110
|
+
self._orig: tuple | None = None
|
|
111
|
+
|
|
112
|
+
def install(self) -> None:
|
|
113
|
+
import functools
|
|
114
|
+
|
|
115
|
+
if self._orig is not None:
|
|
116
|
+
return
|
|
117
|
+
orig_lru, orig_cache, orig_cp = functools.lru_cache, functools.cache, functools.cached_property
|
|
118
|
+
self._orig = (orig_lru, orig_cache, orig_cp)
|
|
119
|
+
wrappers, properties = self._wrappers, self._properties
|
|
120
|
+
|
|
121
|
+
def lru_cache(maxsize=128, typed=False):
|
|
122
|
+
if callable(maxsize) and not isinstance(maxsize, bool):
|
|
123
|
+
w = orig_lru(maxsize, typed) # used bare: @lru_cache
|
|
124
|
+
wrappers.append(w)
|
|
125
|
+
return w
|
|
126
|
+
deco = orig_lru(maxsize, typed)
|
|
127
|
+
|
|
128
|
+
def register(fn):
|
|
129
|
+
w = deco(fn)
|
|
130
|
+
wrappers.append(w)
|
|
131
|
+
return w
|
|
132
|
+
|
|
133
|
+
return register
|
|
134
|
+
|
|
135
|
+
def cache(user_function):
|
|
136
|
+
return lru_cache(maxsize=None)(user_function)
|
|
137
|
+
|
|
138
|
+
class cached_property(orig_cp): # noqa: N801 - keeps the stdlib name
|
|
139
|
+
def __get__(self, instance, owner=None):
|
|
140
|
+
value = super().__get__(instance, owner)
|
|
141
|
+
if instance is not None:
|
|
142
|
+
properties.append((instance, self.attrname))
|
|
143
|
+
return value
|
|
144
|
+
|
|
145
|
+
cached_property.__module__ = "functools"
|
|
146
|
+
functools.lru_cache, functools.cache, functools.cached_property = lru_cache, cache, cached_property
|
|
147
|
+
|
|
148
|
+
def uninstall(self) -> None:
|
|
149
|
+
import functools
|
|
150
|
+
|
|
151
|
+
if self._orig is not None:
|
|
152
|
+
functools.lru_cache, functools.cache, functools.cached_property = self._orig
|
|
153
|
+
self._orig = None
|
|
154
|
+
|
|
155
|
+
def clear(self) -> None:
|
|
156
|
+
for w in self._wrappers:
|
|
157
|
+
try:
|
|
158
|
+
w.cache_clear()
|
|
159
|
+
except Exception: # noqa: BLE001
|
|
160
|
+
pass
|
|
161
|
+
for instance, name in self._properties:
|
|
162
|
+
try:
|
|
163
|
+
instance.__dict__.pop(name, None)
|
|
164
|
+
except Exception: # noqa: BLE001
|
|
165
|
+
pass
|
|
166
|
+
self._properties.clear()
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
class IntrospectionTracker:
|
|
170
|
+
"""Records signature and annotation introspection as a use of the function.
|
|
171
|
+
|
|
172
|
+
Parameter names, constant defaults and lazy annotations of a ``def`` only
|
|
173
|
+
change the function object, so ``quod-change`` attributes them to the
|
|
174
|
+
function itself (header splitting). Code that *calls* the function is
|
|
175
|
+
recorded by ``PY_START``. Code that only *inspects* it (``inspect.signature``
|
|
176
|
+
to build a CLI or an API schema, ``typing.get_type_hints`` for validation)
|
|
177
|
+
runs none of its code, so it is recorded here instead: the introspected
|
|
178
|
+
function counts as used by the current test, fixture or root scope.
|
|
179
|
+
|
|
180
|
+
``inspect._signature_from_callable`` is the one path behind
|
|
181
|
+
``inspect.signature``, ``Signature.from_callable`` and
|
|
182
|
+
``inspect.getfullargspec``. It is looked up as a module global at call
|
|
183
|
+
time, so the patch also covers callers that imported ``signature`` before
|
|
184
|
+
recording started. ``typing.get_type_hints`` and ``inspect.get_annotations``
|
|
185
|
+
(also ``annotationlib.get_annotations`` on 3.14) are patched as module
|
|
186
|
+
attributes, so references bound before recording started aren't covered.
|
|
187
|
+
Reading ``__annotations__``, ``__defaults__`` or ``__code__`` directly isn't
|
|
188
|
+
recorded. That is a documented assumption.
|
|
189
|
+
"""
|
|
190
|
+
|
|
191
|
+
def __init__(self, note) -> None:
|
|
192
|
+
self._note = note
|
|
193
|
+
self._orig: list[tuple[object, str, object]] = []
|
|
194
|
+
|
|
195
|
+
def install(self) -> None:
|
|
196
|
+
import inspect
|
|
197
|
+
import typing
|
|
198
|
+
|
|
199
|
+
if self._orig:
|
|
200
|
+
return
|
|
201
|
+
note = self._note
|
|
202
|
+
targets = [(inspect, "_signature_from_callable"), (inspect, "get_annotations"), (typing, "get_type_hints")]
|
|
203
|
+
try:
|
|
204
|
+
import annotationlib # Python 3.14+
|
|
205
|
+
|
|
206
|
+
targets.append((annotationlib, "get_annotations"))
|
|
207
|
+
except ImportError:
|
|
208
|
+
pass
|
|
209
|
+
for module, name in targets:
|
|
210
|
+
orig = getattr(module, name, None)
|
|
211
|
+
if orig is None:
|
|
212
|
+
continue
|
|
213
|
+
|
|
214
|
+
wrapper = _noting(orig, note)
|
|
215
|
+
wrapper.__name__ = getattr(orig, "__name__", name)
|
|
216
|
+
wrapper.__qualname__ = getattr(orig, "__qualname__", name)
|
|
217
|
+
wrapper.__doc__ = getattr(orig, "__doc__", None)
|
|
218
|
+
wrapper.__wrapped__ = orig
|
|
219
|
+
self._orig.append((module, name, orig))
|
|
220
|
+
setattr(module, name, wrapper)
|
|
221
|
+
|
|
222
|
+
def uninstall(self) -> None:
|
|
223
|
+
for module, name, orig in reversed(self._orig):
|
|
224
|
+
setattr(module, name, orig)
|
|
225
|
+
self._orig.clear()
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
class EnvTracker:
|
|
229
|
+
"""Records reads of ``os.environ`` as ``env:NAME`` observations.
|
|
230
|
+
|
|
231
|
+
``os._Environ.__getitem__`` is the one path behind ``os.environ[k]``,
|
|
232
|
+
``.get``, ``in`` and ``os.getenv``. Iteration (``keys``, ``items``,
|
|
233
|
+
``copy``, ``dict(os.environ)``, ``len``) depends on the whole environment,
|
|
234
|
+
recorded as ``env:*``: the hash of the environment as it was when
|
|
235
|
+
recording started, the part that comes from outside the process. Writes
|
|
236
|
+
after that are in-process state made by traced code (fixtures,
|
|
237
|
+
``monkeypatch``), not inputs, so later reads of a written key aren't
|
|
238
|
+
recorded. Writes made before recording started are treated as inputs,
|
|
239
|
+
which is conservative. Variables the runner sets for itself
|
|
240
|
+
(``fingerprint.RUNNER_ENV_NAMES``) are never recorded.
|
|
241
|
+
|
|
242
|
+
``monkeypatch.setenv``/``delenv`` read the old value only to restore it
|
|
243
|
+
later, so the key is marked written before that read.
|
|
244
|
+
"""
|
|
245
|
+
|
|
246
|
+
def __init__(self, note) -> None:
|
|
247
|
+
self._note = note
|
|
248
|
+
self.written: set[str] = set()
|
|
249
|
+
self._orig: dict[str, object] = {}
|
|
250
|
+
self._mp: list[tuple[type, str, object]] = []
|
|
251
|
+
|
|
252
|
+
def install(self) -> None:
|
|
253
|
+
if self._orig:
|
|
254
|
+
return
|
|
255
|
+
from .fingerprint import RUNNER_ENV_NAMES, env_key, env_value_hash, environ_hash
|
|
256
|
+
|
|
257
|
+
cls = type(os.environ)
|
|
258
|
+
note, written, environ = self._note, self.written, os.environ
|
|
259
|
+
outer = environ_hash(dict(os.environ))
|
|
260
|
+
orig = {n: cls.__dict__[n] for n in ("__getitem__", "__setitem__", "__delitem__", "__iter__", "__len__")}
|
|
261
|
+
self._orig = orig
|
|
262
|
+
|
|
263
|
+
def __getitem__(self, key):
|
|
264
|
+
if self is environ:
|
|
265
|
+
try:
|
|
266
|
+
k = env_key(key)
|
|
267
|
+
if k not in written and k not in RUNNER_ENV_NAMES:
|
|
268
|
+
try:
|
|
269
|
+
value = orig["__getitem__"](self, key)
|
|
270
|
+
except KeyError:
|
|
271
|
+
note(k, env_value_hash(None))
|
|
272
|
+
raise
|
|
273
|
+
note(k, env_value_hash(value))
|
|
274
|
+
return value
|
|
275
|
+
except KeyError:
|
|
276
|
+
raise
|
|
277
|
+
except Exception: # noqa: BLE001 - never break the test run
|
|
278
|
+
pass
|
|
279
|
+
return orig["__getitem__"](self, key)
|
|
280
|
+
|
|
281
|
+
def __setitem__(self, key, value):
|
|
282
|
+
if self is environ:
|
|
283
|
+
written.add(env_key(key))
|
|
284
|
+
return orig["__setitem__"](self, key, value)
|
|
285
|
+
|
|
286
|
+
def __delitem__(self, key):
|
|
287
|
+
if self is environ:
|
|
288
|
+
written.add(env_key(key))
|
|
289
|
+
return orig["__delitem__"](self, key)
|
|
290
|
+
|
|
291
|
+
def whole(self):
|
|
292
|
+
if self is environ:
|
|
293
|
+
note("*", outer)
|
|
294
|
+
|
|
295
|
+
def __iter__(self):
|
|
296
|
+
whole(self)
|
|
297
|
+
return orig["__iter__"](self)
|
|
298
|
+
|
|
299
|
+
def __len__(self):
|
|
300
|
+
whole(self)
|
|
301
|
+
return orig["__len__"](self)
|
|
302
|
+
|
|
303
|
+
try:
|
|
304
|
+
from _pytest.monkeypatch import MonkeyPatch
|
|
305
|
+
|
|
306
|
+
for meth in ("setenv", "delenv"):
|
|
307
|
+
orig_mp = MonkeyPatch.__dict__[meth]
|
|
308
|
+
self._mp.append((MonkeyPatch, meth, orig_mp))
|
|
309
|
+
setattr(MonkeyPatch, meth, _marking_written(orig_mp, written, env_key))
|
|
310
|
+
except (ImportError, KeyError):
|
|
311
|
+
pass
|
|
312
|
+
|
|
313
|
+
for name, f in (
|
|
314
|
+
("__getitem__", __getitem__),
|
|
315
|
+
("__setitem__", __setitem__),
|
|
316
|
+
("__delitem__", __delitem__),
|
|
317
|
+
("__iter__", __iter__),
|
|
318
|
+
("__len__", __len__),
|
|
319
|
+
):
|
|
320
|
+
setattr(cls, name, f)
|
|
321
|
+
|
|
322
|
+
def uninstall(self) -> None:
|
|
323
|
+
cls = type(os.environ)
|
|
324
|
+
for name, f in self._orig.items():
|
|
325
|
+
setattr(cls, name, f)
|
|
326
|
+
self._orig = {}
|
|
327
|
+
for owner, meth, f in reversed(self._mp):
|
|
328
|
+
setattr(owner, meth, f)
|
|
329
|
+
self._mp.clear()
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _marking_written(orig, written: set[str], env_key):
|
|
333
|
+
def wrapper(self, name, *args, **kwargs):
|
|
334
|
+
try:
|
|
335
|
+
written.add(env_key(str(name)))
|
|
336
|
+
except Exception: # noqa: BLE001
|
|
337
|
+
pass
|
|
338
|
+
return orig(self, name, *args, **kwargs)
|
|
339
|
+
|
|
340
|
+
return wrapper
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _noting(orig, note):
|
|
344
|
+
def wrapper(obj, *args, **kwargs):
|
|
345
|
+
note(obj)
|
|
346
|
+
return orig(obj, *args, **kwargs)
|
|
347
|
+
|
|
348
|
+
return wrapper
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def _introspected_functions(obj) -> list[FunctionType]:
|
|
352
|
+
"""The Python functions whose headers introspecting ``obj`` reads.
|
|
353
|
+
|
|
354
|
+
Only plain attribute lookups that can't run user code are used: no
|
|
355
|
+
``getattr`` on arbitrary objects (mocks and proxies answer anything).
|
|
356
|
+
"""
|
|
357
|
+
import functools
|
|
358
|
+
|
|
359
|
+
out: list[FunctionType] = []
|
|
360
|
+
for _ in range(32):
|
|
361
|
+
if isinstance(obj, MethodType):
|
|
362
|
+
obj = obj.__func__
|
|
363
|
+
elif isinstance(obj, functools.partial):
|
|
364
|
+
obj = obj.func
|
|
365
|
+
elif isinstance(obj, (staticmethod, classmethod)):
|
|
366
|
+
obj = obj.__func__
|
|
367
|
+
else:
|
|
368
|
+
break
|
|
369
|
+
if isinstance(obj, FunctionType):
|
|
370
|
+
out.append(obj)
|
|
371
|
+
# Follow the ``functools.wraps`` chain, as ``inspect.signature`` does.
|
|
372
|
+
seen = {id(obj)}
|
|
373
|
+
w = obj.__dict__.get("__wrapped__")
|
|
374
|
+
while isinstance(w, FunctionType) and id(w) not in seen and len(out) < 32:
|
|
375
|
+
out.append(w)
|
|
376
|
+
seen.add(id(w))
|
|
377
|
+
w = w.__dict__.get("__wrapped__")
|
|
378
|
+
elif isinstance(obj, type):
|
|
379
|
+
# A class's signature comes from ``__new__``/``__init__`` (or a
|
|
380
|
+
# metaclass ``__call__``); its type hints from the class bodies.
|
|
381
|
+
for name in ("__init__", "__new__"):
|
|
382
|
+
for klass in obj.__mro__:
|
|
383
|
+
f = klass.__dict__.get(name)
|
|
384
|
+
if isinstance(f, staticmethod):
|
|
385
|
+
f = f.__func__
|
|
386
|
+
if f is not None:
|
|
387
|
+
if isinstance(f, FunctionType):
|
|
388
|
+
out.append(f)
|
|
389
|
+
break
|
|
390
|
+
call = type(obj).__dict__.get("__call__")
|
|
391
|
+
if isinstance(call, FunctionType):
|
|
392
|
+
out.append(call)
|
|
393
|
+
return out
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def _norm(path: str) -> str:
|
|
397
|
+
return os.path.normcase(os.path.realpath(path))
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
def _pyc_to_source(path: str) -> str:
|
|
401
|
+
"""``pkg/__pycache__/mod.cpython-313.pyc`` → ``pkg/mod.py``."""
|
|
402
|
+
head, tail = os.path.split(path)
|
|
403
|
+
if os.path.basename(head) == "__pycache__" and tail.endswith(".pyc"):
|
|
404
|
+
return os.path.join(os.path.dirname(head), tail.split(".", 1)[0] + ".py")
|
|
405
|
+
return path
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
class Recorder:
|
|
409
|
+
"""Process-wide capture. Only one may be active per process."""
|
|
410
|
+
|
|
411
|
+
_active: "Recorder | None" = None
|
|
412
|
+
_audit_installed = False
|
|
413
|
+
|
|
414
|
+
def __init__(self, repo_root: str) -> None:
|
|
415
|
+
self.repo_root_real = os.path.realpath(repo_root)
|
|
416
|
+
self.repo_root = os.path.normcase(self.repo_root_real)
|
|
417
|
+
self._repo_prefix = self.repo_root.rstrip(os.sep) + os.sep
|
|
418
|
+
self.packages = PackageIndex()
|
|
419
|
+
self.seen_packages: dict[str, PackageInfo] = {}
|
|
420
|
+
self.root = Collector()
|
|
421
|
+
self.stack: list[Collector] = []
|
|
422
|
+
self._lock = threading.RLock()
|
|
423
|
+
self._file_cache: dict[str, tuple | None] = {}
|
|
424
|
+
self._tool_id: int | None = None
|
|
425
|
+
self._site_prefixes = self._site_dirs()
|
|
426
|
+
self._own_dir = _norm(os.path.dirname(__file__)) + os.sep
|
|
427
|
+
self.caches = CacheTracker()
|
|
428
|
+
self.introspection = IntrospectionTracker(self._on_introspect)
|
|
429
|
+
self.environ = EnvTracker(self._on_env)
|
|
430
|
+
from .imports import ImportTracker
|
|
431
|
+
|
|
432
|
+
self.imports = ImportTracker(self)
|
|
433
|
+
|
|
434
|
+
@staticmethod
|
|
435
|
+
def _site_dirs() -> tuple[str, ...]:
|
|
436
|
+
dirs: set[str] = set()
|
|
437
|
+
for key in ("purelib", "platlib"):
|
|
438
|
+
p = sysconfig.get_paths().get(key)
|
|
439
|
+
if p:
|
|
440
|
+
dirs.add(p)
|
|
441
|
+
try:
|
|
442
|
+
dirs.update(site.getsitepackages())
|
|
443
|
+
except AttributeError:
|
|
444
|
+
pass
|
|
445
|
+
user = getattr(site, "getusersitepackages", lambda: None)()
|
|
446
|
+
if user:
|
|
447
|
+
dirs.add(user)
|
|
448
|
+
return tuple(sorted({_norm(d).rstrip(os.sep) + os.sep for d in dirs if d}))
|
|
449
|
+
|
|
450
|
+
# Classification --------------------------------------------------------
|
|
451
|
+
|
|
452
|
+
def classify_path(self, raw: str) -> tuple | None:
|
|
453
|
+
"""Returns ``("file", rel)``, ``("pkg", name)`` or ``None`` (ignored)."""
|
|
454
|
+
cached = self._file_cache.get(raw)
|
|
455
|
+
if cached is not None or raw in self._file_cache:
|
|
456
|
+
return cached
|
|
457
|
+
result: tuple | None = None
|
|
458
|
+
if raw and not raw.startswith("<"):
|
|
459
|
+
p = _norm(_pyc_to_source(raw))
|
|
460
|
+
if p.startswith(self._own_dir):
|
|
461
|
+
result = None
|
|
462
|
+
elif any(p.startswith(s) for s in self._site_prefixes):
|
|
463
|
+
info = self.packages.lookup(p)
|
|
464
|
+
self.seen_packages.setdefault(info.name, info)
|
|
465
|
+
result = ("pkg", info.name, info.native)
|
|
466
|
+
elif p.startswith(self._repo_prefix):
|
|
467
|
+
rel = p[len(self._repo_prefix):].replace(os.sep, "/")
|
|
468
|
+
if not _RUNNER_STATE.isdisjoint(rel.split("/")[:-1]):
|
|
469
|
+
# pytest's cache and bytecode: the runner's own state, absent from a fresh
|
|
470
|
+
# checkout (CI). Source files are recorded through the code that runs.
|
|
471
|
+
self._file_cache[raw] = None
|
|
472
|
+
return None
|
|
473
|
+
# Keep the repository's own spelling of the path (normcase lowercases on Windows).
|
|
474
|
+
actual = os.path.relpath(os.path.realpath(_pyc_to_source(raw)), self.repo_root_real)
|
|
475
|
+
result = ("file", actual.replace(os.sep, "/") if not actual.startswith("..") else rel)
|
|
476
|
+
self._file_cache[raw] = result
|
|
477
|
+
return result
|
|
478
|
+
|
|
479
|
+
def _targets(self) -> list[Collector]:
|
|
480
|
+
return self.stack if self.stack else [self.root]
|
|
481
|
+
|
|
482
|
+
# sys.monitoring -------------------------------------------------------
|
|
483
|
+
|
|
484
|
+
def _on_py_start(self, code: CodeType, _offset: int):
|
|
485
|
+
self._record_code(code)
|
|
486
|
+
return sys.monitoring.DISABLE
|
|
487
|
+
|
|
488
|
+
def _on_introspect(self, obj) -> None:
|
|
489
|
+
try:
|
|
490
|
+
for f in _introspected_functions(obj):
|
|
491
|
+
self._record_code(f.__code__)
|
|
492
|
+
except Exception: # noqa: BLE001 - a probe bug must not break the test run
|
|
493
|
+
self._mark_untraced()
|
|
494
|
+
|
|
495
|
+
def _on_env(self, name: str, value_hash: str) -> None:
|
|
496
|
+
with self._lock:
|
|
497
|
+
for c in self._targets():
|
|
498
|
+
c.env.setdefault(name, value_hash)
|
|
499
|
+
|
|
500
|
+
def _record_code(self, code: CodeType) -> None:
|
|
501
|
+
try:
|
|
502
|
+
cls = self.classify_path(code.co_filename)
|
|
503
|
+
if cls is not None:
|
|
504
|
+
with self._lock:
|
|
505
|
+
targets = self._targets()
|
|
506
|
+
if cls[0] == "file":
|
|
507
|
+
q = entity_qualname(code.co_qualname)
|
|
508
|
+
for c in targets:
|
|
509
|
+
if q is None:
|
|
510
|
+
c.files.add(cls[1])
|
|
511
|
+
else:
|
|
512
|
+
c.functions.add((cls[1], q))
|
|
513
|
+
else:
|
|
514
|
+
for c in targets:
|
|
515
|
+
c.packages.add(cls[1])
|
|
516
|
+
if cls[2]:
|
|
517
|
+
c.flags.add(FLAG_C_EXT)
|
|
518
|
+
except Exception: # noqa: BLE001 - a probe bug must not break the test run
|
|
519
|
+
self._mark_untraced()
|
|
520
|
+
|
|
521
|
+
def _mark_untraced(self) -> None:
|
|
522
|
+
for c in self._targets():
|
|
523
|
+
c.flags.add(FLAG_UNTRACED)
|
|
524
|
+
|
|
525
|
+
# Audit hook -----------------------------------------------------------
|
|
526
|
+
|
|
527
|
+
@staticmethod
|
|
528
|
+
def _audit_trampoline(event: str, args: tuple) -> None:
|
|
529
|
+
rec = Recorder._active
|
|
530
|
+
if rec is not None:
|
|
531
|
+
rec._on_audit(event, args)
|
|
532
|
+
|
|
533
|
+
def _on_audit(self, event: str, args: tuple) -> None:
|
|
534
|
+
try:
|
|
535
|
+
if event == "open":
|
|
536
|
+
path, mode = args[0], args[1]
|
|
537
|
+
if isinstance(path, int) or path is None:
|
|
538
|
+
return
|
|
539
|
+
if isinstance(mode, str) and any(m in mode for m in "wax") and "+" not in mode:
|
|
540
|
+
return # pure writes are outputs, not inputs
|
|
541
|
+
cls = self.classify_path(os.fsdecode(path))
|
|
542
|
+
if cls is not None:
|
|
543
|
+
with self._lock:
|
|
544
|
+
for c in self._targets():
|
|
545
|
+
(c.files if cls[0] == "file" else c.packages).add(cls[1])
|
|
546
|
+
elif event in _SUBPROCESS_EVENTS:
|
|
547
|
+
self._flag(FLAG_SUBPROCESS)
|
|
548
|
+
elif event == "socket.connect":
|
|
549
|
+
addr = args[1] if len(args) > 1 else None
|
|
550
|
+
host = addr[0] if isinstance(addr, tuple) and addr else None
|
|
551
|
+
if isinstance(host, str) and not host.startswith(_LOOPBACK_PREFIXES):
|
|
552
|
+
self._flag(FLAG_NETWORK)
|
|
553
|
+
elif event in _LISTING_EVENTS:
|
|
554
|
+
target = args[0] if args else None
|
|
555
|
+
if target is None:
|
|
556
|
+
target = "."
|
|
557
|
+
if isinstance(target, (str, bytes, os.PathLike)):
|
|
558
|
+
cls = self.classify_path(os.fsdecode(target))
|
|
559
|
+
if cls is not None and cls[0] == "file" and self._listing_by_repo_code():
|
|
560
|
+
self._flag(FLAG_DYNAMIC_IMPORT)
|
|
561
|
+
except Exception: # noqa: BLE001
|
|
562
|
+
self._mark_untraced()
|
|
563
|
+
|
|
564
|
+
def _listing_by_repo_code(self) -> bool:
|
|
565
|
+
"""True if the nearest non-stdlib caller of a directory listing is
|
|
566
|
+
repository code.
|
|
567
|
+
|
|
568
|
+
The import system (``FileFinder``) and libraries such as pytest list
|
|
569
|
+
directories for their own bookkeeping. Imports are already traced
|
|
570
|
+
precisely, so only listings the project's own code performs are
|
|
571
|
+
discovery hazards.
|
|
572
|
+
"""
|
|
573
|
+
f = sys._getframe(2)
|
|
574
|
+
for _ in range(40):
|
|
575
|
+
if f is None:
|
|
576
|
+
return False
|
|
577
|
+
filename = f.f_code.co_filename
|
|
578
|
+
if filename.startswith("<frozen importlib"):
|
|
579
|
+
return False
|
|
580
|
+
cls = self.classify_path(filename)
|
|
581
|
+
if cls is not None:
|
|
582
|
+
return cls[0] == "file"
|
|
583
|
+
f = f.f_back
|
|
584
|
+
return False
|
|
585
|
+
|
|
586
|
+
def _flag(self, flag: str) -> None:
|
|
587
|
+
# Flags describe tests. Root-scope activity (collection itself lists
|
|
588
|
+
# directories) must not flag anything.
|
|
589
|
+
if self.stack:
|
|
590
|
+
with self._lock:
|
|
591
|
+
for c in self.stack:
|
|
592
|
+
c.flags.add(flag)
|
|
593
|
+
|
|
594
|
+
# Lifecycle ------------------------------------------------------------
|
|
595
|
+
|
|
596
|
+
def start(self) -> None:
|
|
597
|
+
if Recorder._active is not None:
|
|
598
|
+
raise RuntimeError("a Quod recorder is already active in this process")
|
|
599
|
+
mon = sys.monitoring
|
|
600
|
+
for tool in (3, 4):
|
|
601
|
+
if mon.get_tool(tool) is None:
|
|
602
|
+
mon.use_tool_id(tool, "quod")
|
|
603
|
+
self._tool_id = tool
|
|
604
|
+
break
|
|
605
|
+
else:
|
|
606
|
+
raise RuntimeError("no free sys.monitoring tool id (3 and 4 are in use)")
|
|
607
|
+
mon.register_callback(self._tool_id, mon.events.PY_START, self._on_py_start)
|
|
608
|
+
mon.set_events(self._tool_id, mon.events.PY_START)
|
|
609
|
+
Recorder._active = self
|
|
610
|
+
self.caches.install()
|
|
611
|
+
self.introspection.install()
|
|
612
|
+
self.environ.install()
|
|
613
|
+
self.imports.install()
|
|
614
|
+
if not Recorder._audit_installed:
|
|
615
|
+
sys.addaudithook(Recorder._audit_trampoline) # cannot be removed; gated by _active
|
|
616
|
+
Recorder._audit_installed = True
|
|
617
|
+
|
|
618
|
+
def stop(self) -> None:
|
|
619
|
+
if self._tool_id is not None:
|
|
620
|
+
mon = sys.monitoring
|
|
621
|
+
mon.set_events(self._tool_id, 0)
|
|
622
|
+
mon.register_callback(self._tool_id, mon.events.PY_START, None)
|
|
623
|
+
mon.free_tool_id(self._tool_id)
|
|
624
|
+
self._tool_id = None
|
|
625
|
+
self.caches.uninstall()
|
|
626
|
+
self.introspection.uninstall()
|
|
627
|
+
self.environ.uninstall()
|
|
628
|
+
self.imports.uninstall()
|
|
629
|
+
Recorder._active = None
|
|
630
|
+
|
|
631
|
+
def boundary(self) -> None:
|
|
632
|
+
"""Starts a test: clears tracked caches so the test recomputes (and
|
|
633
|
+
records) what it uses, then re-enables all disabled code locations."""
|
|
634
|
+
self.caches.clear()
|
|
635
|
+
sys.monitoring.restart_events()
|
|
636
|
+
|
|
637
|
+
def push(self, c: Collector, fresh: bool = False) -> None:
|
|
638
|
+
"""Pushes a collector. With ``fresh``, re-enables every code location
|
|
639
|
+
first, so the collector sees code that already ran earlier in this
|
|
640
|
+
test. Shared (fixture and module) collectors need this: their contents
|
|
641
|
+
are later attributed to other tests."""
|
|
642
|
+
if fresh:
|
|
643
|
+
sys.monitoring.restart_events()
|
|
644
|
+
with self._lock:
|
|
645
|
+
self.stack.append(c)
|
|
646
|
+
|
|
647
|
+
def pop(self, c: Collector) -> None:
|
|
648
|
+
with self._lock:
|
|
649
|
+
if self.stack and self.stack[-1] is c:
|
|
650
|
+
self.stack.pop()
|
|
651
|
+
elif c in self.stack:
|
|
652
|
+
self.stack.remove(c)
|