coverage 7.11.3__cp314-cp314t-win32.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.
- coverage/__init__.py +40 -0
- coverage/__main__.py +12 -0
- coverage/annotate.py +114 -0
- coverage/bytecode.py +196 -0
- coverage/cmdline.py +1184 -0
- coverage/collector.py +486 -0
- coverage/config.py +731 -0
- coverage/context.py +74 -0
- coverage/control.py +1481 -0
- coverage/core.py +139 -0
- coverage/data.py +227 -0
- coverage/debug.py +669 -0
- coverage/disposition.py +59 -0
- coverage/env.py +135 -0
- coverage/exceptions.py +85 -0
- coverage/execfile.py +329 -0
- coverage/files.py +553 -0
- coverage/html.py +856 -0
- coverage/htmlfiles/coverage_html.js +733 -0
- coverage/htmlfiles/favicon_32.png +0 -0
- coverage/htmlfiles/index.html +164 -0
- coverage/htmlfiles/keybd_closed.png +0 -0
- coverage/htmlfiles/pyfile.html +149 -0
- coverage/htmlfiles/style.css +377 -0
- coverage/htmlfiles/style.scss +824 -0
- coverage/inorout.py +614 -0
- coverage/jsonreport.py +188 -0
- coverage/lcovreport.py +219 -0
- coverage/misc.py +373 -0
- coverage/multiproc.py +120 -0
- coverage/numbits.py +146 -0
- coverage/parser.py +1213 -0
- coverage/patch.py +166 -0
- coverage/phystokens.py +197 -0
- coverage/plugin.py +617 -0
- coverage/plugin_support.py +299 -0
- coverage/py.typed +1 -0
- coverage/python.py +269 -0
- coverage/pytracer.py +369 -0
- coverage/regions.py +127 -0
- coverage/report.py +298 -0
- coverage/report_core.py +117 -0
- coverage/results.py +471 -0
- coverage/sqldata.py +1153 -0
- coverage/sqlitedb.py +239 -0
- coverage/sysmon.py +482 -0
- coverage/templite.py +306 -0
- coverage/tomlconfig.py +210 -0
- coverage/tracer.cp314t-win32.pyd +0 -0
- coverage/tracer.pyi +43 -0
- coverage/types.py +206 -0
- coverage/version.py +35 -0
- coverage/xmlreport.py +264 -0
- coverage-7.11.3.dist-info/METADATA +221 -0
- coverage-7.11.3.dist-info/RECORD +59 -0
- coverage-7.11.3.dist-info/WHEEL +5 -0
- coverage-7.11.3.dist-info/entry_points.txt +4 -0
- coverage-7.11.3.dist-info/licenses/LICENSE.txt +177 -0
- coverage-7.11.3.dist-info/top_level.txt +1 -0
coverage/debug.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
|
|
2
|
+
# For details: https://github.com/coveragepy/coveragepy/blob/main/NOTICE.txt
|
|
3
|
+
|
|
4
|
+
"""Control of and utilities for debugging."""
|
|
5
|
+
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import _thread
|
|
9
|
+
import atexit
|
|
10
|
+
import contextlib
|
|
11
|
+
import datetime
|
|
12
|
+
import functools
|
|
13
|
+
import inspect
|
|
14
|
+
import itertools
|
|
15
|
+
import os
|
|
16
|
+
import pprint
|
|
17
|
+
import re
|
|
18
|
+
import reprlib
|
|
19
|
+
import sys
|
|
20
|
+
import traceback
|
|
21
|
+
import types
|
|
22
|
+
from collections.abc import Iterable, Iterator, Mapping
|
|
23
|
+
from typing import IO, Any, Callable, Final, overload
|
|
24
|
+
|
|
25
|
+
from coverage.misc import human_sorted_items, isolate_module
|
|
26
|
+
from coverage.types import AnyCallable, TWritable
|
|
27
|
+
|
|
28
|
+
os = isolate_module(os)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
# When debugging, it can be helpful to force some options, especially when
|
|
32
|
+
# debugging the configuration mechanisms you usually use to control debugging!
|
|
33
|
+
# This is a list of forced debugging options.
|
|
34
|
+
FORCED_DEBUG: list[str] = []
|
|
35
|
+
FORCED_DEBUG_FILE = None
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class DebugControl:
|
|
39
|
+
"""Control and output for debugging."""
|
|
40
|
+
|
|
41
|
+
show_repr_attr = False # For auto_repr
|
|
42
|
+
|
|
43
|
+
def __init__(
|
|
44
|
+
self,
|
|
45
|
+
options: Iterable[str],
|
|
46
|
+
output: IO[str] | None,
|
|
47
|
+
file_name: str | None = None,
|
|
48
|
+
) -> None:
|
|
49
|
+
"""Configure the options and output file for debugging."""
|
|
50
|
+
self.options = list(options) + FORCED_DEBUG
|
|
51
|
+
self.suppress_callers = False
|
|
52
|
+
|
|
53
|
+
filters = []
|
|
54
|
+
if self.should("process"):
|
|
55
|
+
filters.append(CwdTracker().filter)
|
|
56
|
+
filters.append(ProcessTracker().filter)
|
|
57
|
+
if self.should("pytest"):
|
|
58
|
+
filters.append(PytestTracker().filter)
|
|
59
|
+
if self.should("pid"):
|
|
60
|
+
filters.append(add_pid_and_tid)
|
|
61
|
+
|
|
62
|
+
self.output = DebugOutputFile.get_one(
|
|
63
|
+
output,
|
|
64
|
+
file_name=file_name,
|
|
65
|
+
filters=filters,
|
|
66
|
+
)
|
|
67
|
+
self.raw_output = self.output.outfile
|
|
68
|
+
|
|
69
|
+
def __repr__(self) -> str:
|
|
70
|
+
return f"<DebugControl options={self.options!r} raw_output={self.raw_output!r}>"
|
|
71
|
+
|
|
72
|
+
def should(self, option: str) -> bool:
|
|
73
|
+
"""Decide whether to output debug information in category `option`."""
|
|
74
|
+
if option == "callers" and self.suppress_callers:
|
|
75
|
+
return False
|
|
76
|
+
return option in self.options
|
|
77
|
+
|
|
78
|
+
@contextlib.contextmanager
|
|
79
|
+
def without_callers(self) -> Iterator[None]:
|
|
80
|
+
"""A context manager to prevent call stacks from being logged."""
|
|
81
|
+
old = self.suppress_callers
|
|
82
|
+
self.suppress_callers = True
|
|
83
|
+
try:
|
|
84
|
+
yield
|
|
85
|
+
finally:
|
|
86
|
+
self.suppress_callers = old
|
|
87
|
+
|
|
88
|
+
def write(self, msg: str, *, exc: BaseException | None = None) -> None:
|
|
89
|
+
"""Write a line of debug output.
|
|
90
|
+
|
|
91
|
+
`msg` is the line to write. A newline will be appended.
|
|
92
|
+
|
|
93
|
+
If `exc` is provided, a stack trace of the exception will be written
|
|
94
|
+
after the message.
|
|
95
|
+
|
|
96
|
+
"""
|
|
97
|
+
self.output.write(msg + "\n")
|
|
98
|
+
if exc is not None:
|
|
99
|
+
self.output.write("".join(traceback.format_exception(None, exc, exc.__traceback__)))
|
|
100
|
+
if self.should("self"):
|
|
101
|
+
caller_self = inspect.stack()[1][0].f_locals.get("self")
|
|
102
|
+
if caller_self is not None:
|
|
103
|
+
self.output.write(f"self: {caller_self!r}\n")
|
|
104
|
+
if self.should("callers"):
|
|
105
|
+
dump_stack_frames(out=self.output, skip=1)
|
|
106
|
+
self.output.flush()
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class NoDebugging(DebugControl):
|
|
110
|
+
"""A replacement for DebugControl that will never try to do anything."""
|
|
111
|
+
|
|
112
|
+
def __init__(self) -> None:
|
|
113
|
+
# pylint: disable=super-init-not-called
|
|
114
|
+
pass
|
|
115
|
+
|
|
116
|
+
def should(self, option: str) -> bool:
|
|
117
|
+
"""Should we write debug messages? Never."""
|
|
118
|
+
return False
|
|
119
|
+
|
|
120
|
+
@contextlib.contextmanager
|
|
121
|
+
def without_callers(self) -> Iterator[None]:
|
|
122
|
+
"""A dummy context manager to satisfy the api."""
|
|
123
|
+
yield # pragma: never called
|
|
124
|
+
|
|
125
|
+
def write(self, msg: str, *, exc: BaseException | None = None) -> None:
|
|
126
|
+
"""This will never be called."""
|
|
127
|
+
raise AssertionError("NoDebugging.write should never be called.")
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class DevNullDebug(NoDebugging):
|
|
131
|
+
"""A DebugControl that won't write anywhere."""
|
|
132
|
+
|
|
133
|
+
def write(self, msg: str, *, exc: BaseException | None = None) -> None:
|
|
134
|
+
pass
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def info_header(label: str) -> str:
|
|
138
|
+
"""Make a nice header string."""
|
|
139
|
+
return "--{:-<60s}".format(" " + label + " ")
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def info_formatter(info: Iterable[tuple[str, Any]]) -> Iterable[str]:
|
|
143
|
+
"""Produce a sequence of formatted lines from info.
|
|
144
|
+
|
|
145
|
+
`info` is a sequence of pairs (label, data). The produced lines are
|
|
146
|
+
nicely formatted, ready to print.
|
|
147
|
+
|
|
148
|
+
"""
|
|
149
|
+
info = list(info)
|
|
150
|
+
if not info:
|
|
151
|
+
return
|
|
152
|
+
LABEL_LEN = 30
|
|
153
|
+
assert all(len(l) < LABEL_LEN for l, _ in info)
|
|
154
|
+
for label, data in info:
|
|
155
|
+
if data == []:
|
|
156
|
+
data = "-none-"
|
|
157
|
+
prefix = f"{label:>{LABEL_LEN}}: "
|
|
158
|
+
match data:
|
|
159
|
+
case tuple() if len(str(data)) < 30:
|
|
160
|
+
yield f"{prefix}{data}"
|
|
161
|
+
case tuple() | list() | set():
|
|
162
|
+
for e in data:
|
|
163
|
+
yield f"{prefix}{e}"
|
|
164
|
+
prefix = " " * (LABEL_LEN + 2)
|
|
165
|
+
case _:
|
|
166
|
+
yield f"{prefix}{data}"
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def write_formatted_info(
|
|
170
|
+
write: Callable[[str], None],
|
|
171
|
+
header: str,
|
|
172
|
+
info: Iterable[tuple[str, Any]],
|
|
173
|
+
) -> None:
|
|
174
|
+
"""Write a sequence of (label,data) pairs nicely.
|
|
175
|
+
|
|
176
|
+
`write` is a function write(str) that accepts each line of output.
|
|
177
|
+
`header` is a string to start the section. `info` is a sequence of
|
|
178
|
+
(label, data) pairs, where label is a str, and data can be a single
|
|
179
|
+
value, or a list/set/tuple.
|
|
180
|
+
|
|
181
|
+
"""
|
|
182
|
+
write(info_header(header))
|
|
183
|
+
for line in info_formatter(info):
|
|
184
|
+
write(f" {line}")
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def exc_one_line(exc: Exception) -> str:
|
|
188
|
+
"""Get a one-line summary of an exception, including class name and message."""
|
|
189
|
+
lines = traceback.format_exception_only(type(exc), exc)
|
|
190
|
+
return "|".join(l.rstrip() for l in lines)
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
_FILENAME_REGEXES: list[tuple[str, str]] = [
|
|
194
|
+
(r".*[/\\]pytest-of-.*[/\\]pytest-\d+([/\\]popen-gw\d+)?", "tmp:"),
|
|
195
|
+
]
|
|
196
|
+
_FILENAME_SUBS: list[tuple[str, str]] = []
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
@overload
|
|
200
|
+
def short_filename(filename: str) -> str:
|
|
201
|
+
pass
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
@overload
|
|
205
|
+
def short_filename(filename: None) -> None:
|
|
206
|
+
pass
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def short_filename(filename: str | None) -> str | None:
|
|
210
|
+
"""Shorten a file name. Directories are replaced by prefixes like 'syspath:'"""
|
|
211
|
+
if not _FILENAME_SUBS:
|
|
212
|
+
for pathdir in sys.path:
|
|
213
|
+
_FILENAME_SUBS.append((pathdir, "syspath:"))
|
|
214
|
+
import coverage
|
|
215
|
+
|
|
216
|
+
_FILENAME_SUBS.append((os.path.dirname(coverage.__file__), "cov:"))
|
|
217
|
+
_FILENAME_SUBS.sort(key=(lambda pair: len(pair[0])), reverse=True)
|
|
218
|
+
if filename is not None:
|
|
219
|
+
for pat, sub in _FILENAME_REGEXES:
|
|
220
|
+
filename = re.sub(pat, sub, filename)
|
|
221
|
+
for before, after in _FILENAME_SUBS:
|
|
222
|
+
filename = filename.replace(before, after)
|
|
223
|
+
return filename
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def file_summary(filename: str) -> str:
|
|
227
|
+
"""A one-line summary of a file, for log messages."""
|
|
228
|
+
try:
|
|
229
|
+
s = os.stat(filename)
|
|
230
|
+
except FileNotFoundError:
|
|
231
|
+
summary = "does not exist"
|
|
232
|
+
except Exception as e:
|
|
233
|
+
summary = f"error: {e}"
|
|
234
|
+
else:
|
|
235
|
+
mod = datetime.datetime.fromtimestamp(s.st_mtime)
|
|
236
|
+
summary = f"{s.st_size} bytes, modified {mod}"
|
|
237
|
+
return summary
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
def short_stack(
|
|
241
|
+
skip: int = 0,
|
|
242
|
+
full: bool = False,
|
|
243
|
+
frame_ids: bool = False,
|
|
244
|
+
short_filenames: bool = False,
|
|
245
|
+
) -> str:
|
|
246
|
+
"""Return a string summarizing the call stack.
|
|
247
|
+
|
|
248
|
+
The string is multi-line, with one line per stack frame. Each line shows
|
|
249
|
+
the function name, the file name, and the line number:
|
|
250
|
+
|
|
251
|
+
...
|
|
252
|
+
start_import_stop : /Users/ned/coverage/trunk/tests/coveragetest.py:95
|
|
253
|
+
import_local_file : /Users/ned/coverage/trunk/tests/coveragetest.py:81
|
|
254
|
+
import_local_file : /Users/ned/coverage/trunk/coverage/backward.py:159
|
|
255
|
+
...
|
|
256
|
+
|
|
257
|
+
`skip` is the number of closest immediate frames to skip, so that debugging
|
|
258
|
+
functions can call this and not be included in the result.
|
|
259
|
+
|
|
260
|
+
If `full` is true, then include all frames. Otherwise, initial "boring"
|
|
261
|
+
frames (ones in site-packages and earlier) are omitted.
|
|
262
|
+
|
|
263
|
+
`short_filenames` will shorten filenames using `short_filename`, to reduce
|
|
264
|
+
the amount of repetitive noise in stack traces.
|
|
265
|
+
|
|
266
|
+
"""
|
|
267
|
+
# Regexes in initial frames that we don't care about.
|
|
268
|
+
# fmt: off
|
|
269
|
+
BORING_PRELUDE = [
|
|
270
|
+
"<string>", # pytest-xdist has string execution.
|
|
271
|
+
r"\bigor.py$", # Our test runner.
|
|
272
|
+
r"\bsite-packages\b", # pytest etc getting to our tests.
|
|
273
|
+
]
|
|
274
|
+
# fmt: on
|
|
275
|
+
|
|
276
|
+
stack: Iterable[inspect.FrameInfo] = inspect.stack()[:skip:-1]
|
|
277
|
+
if not full:
|
|
278
|
+
for pat in BORING_PRELUDE:
|
|
279
|
+
stack = itertools.dropwhile(
|
|
280
|
+
(lambda fi, pat=pat: re.search(pat, fi.filename)), # type: ignore[misc]
|
|
281
|
+
stack,
|
|
282
|
+
)
|
|
283
|
+
lines = []
|
|
284
|
+
for frame_info in stack:
|
|
285
|
+
line = f"{frame_info.function:>30s} : "
|
|
286
|
+
if frame_ids:
|
|
287
|
+
line += f"{id(frame_info.frame):#x} "
|
|
288
|
+
filename = frame_info.filename
|
|
289
|
+
if short_filenames:
|
|
290
|
+
filename = short_filename(filename)
|
|
291
|
+
line += f"{filename}:{frame_info.lineno}"
|
|
292
|
+
lines.append(line)
|
|
293
|
+
return "\n".join(lines)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def dump_stack_frames(out: TWritable, skip: int = 0) -> None:
|
|
297
|
+
"""Print a summary of the stack to `out`."""
|
|
298
|
+
out.write(short_stack(skip=skip + 1) + "\n")
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def clipped_repr(text: str, numchars: int = 50) -> str:
|
|
302
|
+
"""`repr(text)`, but limited to `numchars`."""
|
|
303
|
+
r = reprlib.Repr()
|
|
304
|
+
r.maxstring = numchars
|
|
305
|
+
return r.repr(text)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
def short_id(id64: int) -> int:
|
|
309
|
+
"""Given a 64-bit id, make a shorter 16-bit one."""
|
|
310
|
+
id16 = 0
|
|
311
|
+
for offset in range(0, 64, 16):
|
|
312
|
+
id16 ^= id64 >> offset
|
|
313
|
+
return id16 & 0xFFFF
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def add_pid_and_tid(text: str) -> str:
|
|
317
|
+
"""A filter to add pid and tid to debug messages."""
|
|
318
|
+
# Thread ids are useful, but too long. Make a shorter one.
|
|
319
|
+
tid = f"{short_id(_thread.get_ident()):04x}"
|
|
320
|
+
text = f"{os.getpid():5d}.{tid}: {text}"
|
|
321
|
+
return text
|
|
322
|
+
|
|
323
|
+
|
|
324
|
+
AUTO_REPR_IGNORE = {"$coverage.object_id"}
|
|
325
|
+
|
|
326
|
+
|
|
327
|
+
def auto_repr(self: Any) -> str:
|
|
328
|
+
"""A function implementing an automatic __repr__ for debugging."""
|
|
329
|
+
show_attrs = (
|
|
330
|
+
(k, v)
|
|
331
|
+
for k, v in self.__dict__.items()
|
|
332
|
+
if getattr(v, "show_repr_attr", True)
|
|
333
|
+
and not inspect.ismethod(v)
|
|
334
|
+
and k not in AUTO_REPR_IGNORE
|
|
335
|
+
)
|
|
336
|
+
return "<{klass} @{id:#x}{attrs}>".format(
|
|
337
|
+
klass=self.__class__.__name__,
|
|
338
|
+
id=id(self),
|
|
339
|
+
attrs="".join(f" {k}={v!r}" for k, v in show_attrs),
|
|
340
|
+
)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def simplify(v: Any) -> Any: # pragma: debugging
|
|
344
|
+
"""Turn things which are nearly dict/list/etc into dict/list/etc."""
|
|
345
|
+
if isinstance(v, dict):
|
|
346
|
+
return {k: simplify(vv) for k, vv in v.items()}
|
|
347
|
+
elif isinstance(v, (list, tuple)):
|
|
348
|
+
return type(v)(simplify(vv) for vv in v)
|
|
349
|
+
elif hasattr(v, "__dict__"):
|
|
350
|
+
return simplify({"." + k: v for k, v in v.__dict__.items()})
|
|
351
|
+
else:
|
|
352
|
+
return v
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def ppformat(v: Any) -> str: # pragma: debugging
|
|
356
|
+
"""Debug helper to pretty-print data, including SimpleNamespace objects."""
|
|
357
|
+
return pprint.pformat(simplify(v), indent=4, compact=True, sort_dicts=True, width=140)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
def pp(v: Any) -> None: # pragma: debugging
|
|
361
|
+
"""Debug helper to pretty-print data, including SimpleNamespace objects."""
|
|
362
|
+
print(ppformat(v))
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def filter_text(text: str, filters: Iterable[Callable[[str], str]]) -> str:
|
|
366
|
+
"""Run `text` through a series of filters.
|
|
367
|
+
|
|
368
|
+
`filters` is a list of functions. Each takes a string and returns a
|
|
369
|
+
string. Each is run in turn. After each filter, the text is split into
|
|
370
|
+
lines, and each line is passed through the next filter.
|
|
371
|
+
|
|
372
|
+
Returns: the final string that results after all of the filters have
|
|
373
|
+
run.
|
|
374
|
+
|
|
375
|
+
"""
|
|
376
|
+
clean_text = text.rstrip()
|
|
377
|
+
ending = text[len(clean_text) :]
|
|
378
|
+
text = clean_text
|
|
379
|
+
for filter_fn in filters:
|
|
380
|
+
lines = []
|
|
381
|
+
for line in text.splitlines():
|
|
382
|
+
lines.extend(filter_fn(line).splitlines())
|
|
383
|
+
text = "\n".join(lines)
|
|
384
|
+
return text + ending
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class CwdTracker:
|
|
388
|
+
"""A class to add cwd info to debug messages."""
|
|
389
|
+
|
|
390
|
+
def __init__(self) -> None:
|
|
391
|
+
self.cwd: str | None = None
|
|
392
|
+
|
|
393
|
+
def filter(self, text: str) -> str:
|
|
394
|
+
"""Add a cwd message for each new cwd."""
|
|
395
|
+
cwd = os.getcwd()
|
|
396
|
+
if cwd != self.cwd:
|
|
397
|
+
text = f"cwd is now {cwd!r}\n{text}"
|
|
398
|
+
self.cwd = cwd
|
|
399
|
+
return text
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
class ProcessTracker:
|
|
403
|
+
"""Track process creation for debug logging."""
|
|
404
|
+
|
|
405
|
+
def __init__(self) -> None:
|
|
406
|
+
self.pid: int = os.getpid()
|
|
407
|
+
self.did_welcome = False
|
|
408
|
+
|
|
409
|
+
def filter(self, text: str) -> str:
|
|
410
|
+
"""Add a message about how new processes came to be."""
|
|
411
|
+
welcome = ""
|
|
412
|
+
pid = os.getpid()
|
|
413
|
+
if self.pid != pid:
|
|
414
|
+
welcome = f"New process: forked {self.pid} -> {pid}\n"
|
|
415
|
+
self.pid = pid
|
|
416
|
+
elif not self.did_welcome:
|
|
417
|
+
argv = getattr(sys, "argv", None)
|
|
418
|
+
welcome = (
|
|
419
|
+
f"New process: {pid=}, executable: {sys.executable!r}\n"
|
|
420
|
+
+ f"New process: cmd: {argv!r}\n"
|
|
421
|
+
+ f"New process parent pid: {os.getppid()!r}\n"
|
|
422
|
+
)
|
|
423
|
+
|
|
424
|
+
if welcome:
|
|
425
|
+
self.did_welcome = True
|
|
426
|
+
return welcome + text
|
|
427
|
+
else:
|
|
428
|
+
return text
|
|
429
|
+
|
|
430
|
+
|
|
431
|
+
class PytestTracker:
|
|
432
|
+
"""Track the current pytest test name to add to debug messages."""
|
|
433
|
+
|
|
434
|
+
def __init__(self) -> None:
|
|
435
|
+
self.test_name: str | None = None
|
|
436
|
+
|
|
437
|
+
def filter(self, text: str) -> str:
|
|
438
|
+
"""Add a message when the pytest test changes."""
|
|
439
|
+
test_name = os.getenv("PYTEST_CURRENT_TEST")
|
|
440
|
+
if test_name != self.test_name:
|
|
441
|
+
text = f"Pytest context: {test_name}\n{text}"
|
|
442
|
+
self.test_name = test_name
|
|
443
|
+
return text
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
class DebugOutputFile:
|
|
447
|
+
"""A file-like object that includes pid and cwd information."""
|
|
448
|
+
|
|
449
|
+
def __init__(
|
|
450
|
+
self,
|
|
451
|
+
outfile: IO[str] | None,
|
|
452
|
+
filters: Iterable[Callable[[str], str]],
|
|
453
|
+
):
|
|
454
|
+
self.outfile = outfile
|
|
455
|
+
self.filters = list(filters)
|
|
456
|
+
self.pid = os.getpid()
|
|
457
|
+
|
|
458
|
+
@classmethod
|
|
459
|
+
def get_one(
|
|
460
|
+
cls,
|
|
461
|
+
fileobj: IO[str] | None = None,
|
|
462
|
+
file_name: str | None = None,
|
|
463
|
+
filters: Iterable[Callable[[str], str]] = (),
|
|
464
|
+
interim: bool = False,
|
|
465
|
+
) -> DebugOutputFile:
|
|
466
|
+
"""Get a DebugOutputFile.
|
|
467
|
+
|
|
468
|
+
If `fileobj` is provided, then a new DebugOutputFile is made with it.
|
|
469
|
+
|
|
470
|
+
If `fileobj` isn't provided, then a file is chosen (`file_name` if
|
|
471
|
+
provided, or COVERAGE_DEBUG_FILE, or stderr), and a process-wide
|
|
472
|
+
singleton DebugOutputFile is made.
|
|
473
|
+
|
|
474
|
+
`filters` are the text filters to apply to the stream to annotate with
|
|
475
|
+
pids, etc.
|
|
476
|
+
|
|
477
|
+
If `interim` is true, then a future `get_one` can replace this one.
|
|
478
|
+
|
|
479
|
+
"""
|
|
480
|
+
if fileobj is not None:
|
|
481
|
+
# Make DebugOutputFile around the fileobj passed.
|
|
482
|
+
return cls(fileobj, filters)
|
|
483
|
+
|
|
484
|
+
the_one, is_interim = cls._get_singleton_data()
|
|
485
|
+
if the_one is None or is_interim:
|
|
486
|
+
if file_name is not None:
|
|
487
|
+
fileobj = open(file_name, "a", encoding="utf-8")
|
|
488
|
+
else:
|
|
489
|
+
# $set_env.py: COVERAGE_DEBUG_FILE - Where to write debug output
|
|
490
|
+
file_name = os.getenv("COVERAGE_DEBUG_FILE", FORCED_DEBUG_FILE)
|
|
491
|
+
if file_name in ["stdout", "stderr"]:
|
|
492
|
+
fileobj = getattr(sys, file_name)
|
|
493
|
+
elif file_name:
|
|
494
|
+
fileobj = open(file_name, "a", encoding="utf-8")
|
|
495
|
+
atexit.register(fileobj.close)
|
|
496
|
+
else:
|
|
497
|
+
fileobj = sys.stderr
|
|
498
|
+
the_one = cls(fileobj, filters)
|
|
499
|
+
cls._set_singleton_data(the_one, interim)
|
|
500
|
+
|
|
501
|
+
if not (the_one.filters):
|
|
502
|
+
the_one.filters = list(filters)
|
|
503
|
+
return the_one
|
|
504
|
+
|
|
505
|
+
# Because of the way igor.py deletes and re-imports modules,
|
|
506
|
+
# this class can be defined more than once. But we really want
|
|
507
|
+
# a process-wide singleton. So stash it in sys.modules instead of
|
|
508
|
+
# on a class attribute. Yes, this is aggressively gross.
|
|
509
|
+
|
|
510
|
+
SYS_MOD_NAME: Final[str] = "$coverage.debug.DebugOutputFile.the_one"
|
|
511
|
+
SINGLETON_ATTR: Final[str] = "the_one_and_is_interim"
|
|
512
|
+
|
|
513
|
+
@classmethod
|
|
514
|
+
def _set_singleton_data(cls, the_one: DebugOutputFile, interim: bool) -> None:
|
|
515
|
+
"""Set the one DebugOutputFile to rule them all."""
|
|
516
|
+
singleton_module = types.ModuleType(cls.SYS_MOD_NAME)
|
|
517
|
+
setattr(singleton_module, cls.SINGLETON_ATTR, (the_one, interim))
|
|
518
|
+
sys.modules[cls.SYS_MOD_NAME] = singleton_module
|
|
519
|
+
|
|
520
|
+
@classmethod
|
|
521
|
+
def _get_singleton_data(cls) -> tuple[DebugOutputFile | None, bool]:
|
|
522
|
+
"""Get the one DebugOutputFile."""
|
|
523
|
+
singleton_module = sys.modules.get(cls.SYS_MOD_NAME)
|
|
524
|
+
return getattr(singleton_module, cls.SINGLETON_ATTR, (None, True))
|
|
525
|
+
|
|
526
|
+
@classmethod
|
|
527
|
+
def _del_singleton_data(cls) -> None:
|
|
528
|
+
"""Delete the one DebugOutputFile, just for tests to use."""
|
|
529
|
+
if cls.SYS_MOD_NAME in sys.modules:
|
|
530
|
+
del sys.modules[cls.SYS_MOD_NAME]
|
|
531
|
+
|
|
532
|
+
def write(self, text: str) -> None:
|
|
533
|
+
"""Just like file.write, but filter through all our filters."""
|
|
534
|
+
assert self.outfile is not None
|
|
535
|
+
if not self.outfile.closed:
|
|
536
|
+
self.outfile.write(filter_text(text, self.filters))
|
|
537
|
+
self.outfile.flush()
|
|
538
|
+
|
|
539
|
+
def flush(self) -> None:
|
|
540
|
+
"""Flush our file."""
|
|
541
|
+
assert self.outfile is not None
|
|
542
|
+
if not self.outfile.closed:
|
|
543
|
+
self.outfile.flush()
|
|
544
|
+
|
|
545
|
+
|
|
546
|
+
def log(msg: str, stack: bool = False) -> None: # pragma: debugging
|
|
547
|
+
"""Write a log message as forcefully as possible."""
|
|
548
|
+
out = DebugOutputFile.get_one(interim=True)
|
|
549
|
+
out.write(msg + "\n")
|
|
550
|
+
if stack:
|
|
551
|
+
dump_stack_frames(out=out, skip=1)
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def decorate_methods(
|
|
555
|
+
decorator: Callable[..., Any],
|
|
556
|
+
butnot: Iterable[str] = (),
|
|
557
|
+
private: bool = False,
|
|
558
|
+
) -> Callable[..., Any]: # pragma: debugging
|
|
559
|
+
"""A class decorator to apply a decorator to methods."""
|
|
560
|
+
|
|
561
|
+
def _decorator(cls): # type: ignore[no-untyped-def]
|
|
562
|
+
for name, meth in inspect.getmembers(cls, inspect.isroutine):
|
|
563
|
+
if name not in cls.__dict__:
|
|
564
|
+
continue
|
|
565
|
+
if name != "__init__":
|
|
566
|
+
if not private and name.startswith("_"):
|
|
567
|
+
continue
|
|
568
|
+
if name in butnot:
|
|
569
|
+
continue
|
|
570
|
+
setattr(cls, name, decorator(meth))
|
|
571
|
+
return cls
|
|
572
|
+
|
|
573
|
+
return _decorator
|
|
574
|
+
|
|
575
|
+
|
|
576
|
+
def break_in_pudb(func: AnyCallable) -> AnyCallable: # pragma: debugging
|
|
577
|
+
"""A function decorator to stop in the debugger for each call."""
|
|
578
|
+
|
|
579
|
+
@functools.wraps(func)
|
|
580
|
+
def _wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
581
|
+
import pudb
|
|
582
|
+
|
|
583
|
+
sys.stdout = sys.__stdout__
|
|
584
|
+
pudb.set_trace()
|
|
585
|
+
return func(*args, **kwargs)
|
|
586
|
+
|
|
587
|
+
return _wrapper
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
OBJ_IDS = itertools.count()
|
|
591
|
+
CALLS = itertools.count()
|
|
592
|
+
OBJ_ID_ATTR = "$coverage.object_id"
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def show_calls(
|
|
596
|
+
show_args: bool = True,
|
|
597
|
+
show_stack: bool = False,
|
|
598
|
+
show_return: bool = False,
|
|
599
|
+
) -> Callable[..., Any]: # pragma: debugging
|
|
600
|
+
"""A method decorator to debug-log each call to the function."""
|
|
601
|
+
|
|
602
|
+
def _decorator(func: AnyCallable) -> AnyCallable:
|
|
603
|
+
@functools.wraps(func)
|
|
604
|
+
def _wrapper(self: Any, *args: Any, **kwargs: Any) -> Any:
|
|
605
|
+
oid = getattr(self, OBJ_ID_ATTR, None)
|
|
606
|
+
if oid is None:
|
|
607
|
+
oid = f"{os.getpid():08d} {next(OBJ_IDS):04d}"
|
|
608
|
+
setattr(self, OBJ_ID_ATTR, oid)
|
|
609
|
+
extra = ""
|
|
610
|
+
if show_args:
|
|
611
|
+
eargs = ", ".join(map(repr, args))
|
|
612
|
+
ekwargs = ", ".join("{}={!r}".format(*item) for item in kwargs.items())
|
|
613
|
+
extra += "("
|
|
614
|
+
extra += eargs
|
|
615
|
+
if eargs and ekwargs:
|
|
616
|
+
extra += ", "
|
|
617
|
+
extra += ekwargs
|
|
618
|
+
extra += ")"
|
|
619
|
+
if show_stack:
|
|
620
|
+
extra += " @ "
|
|
621
|
+
extra += "; ".join(short_stack(short_filenames=True).splitlines())
|
|
622
|
+
callid = next(CALLS)
|
|
623
|
+
msg = f"{oid} {callid:04d} {func.__name__}{extra}\n"
|
|
624
|
+
DebugOutputFile.get_one(interim=True).write(msg)
|
|
625
|
+
ret = func(self, *args, **kwargs)
|
|
626
|
+
if show_return:
|
|
627
|
+
msg = f"{oid} {callid:04d} {func.__name__} return {ret!r}\n"
|
|
628
|
+
DebugOutputFile.get_one(interim=True).write(msg)
|
|
629
|
+
return ret
|
|
630
|
+
|
|
631
|
+
return _wrapper
|
|
632
|
+
|
|
633
|
+
return _decorator
|
|
634
|
+
|
|
635
|
+
|
|
636
|
+
def relevant_environment_display(env: Mapping[str, str]) -> list[tuple[str, str]]:
|
|
637
|
+
"""Filter environment variables for a debug display.
|
|
638
|
+
|
|
639
|
+
Select variables to display (with COV or PY in the name, or HOME, TEMP, or
|
|
640
|
+
TMP), and also cloak sensitive values with asterisks.
|
|
641
|
+
|
|
642
|
+
Arguments:
|
|
643
|
+
env: a dict of environment variable names and values.
|
|
644
|
+
|
|
645
|
+
Returns:
|
|
646
|
+
A list of pairs (name, value) to show.
|
|
647
|
+
|
|
648
|
+
"""
|
|
649
|
+
SLUGS = {"COV", "PY"}
|
|
650
|
+
INCLUDE = {"HOME", "TEMP", "TMP"}
|
|
651
|
+
CLOAK = {"API", "TOKEN", "KEY", "SECRET", "PASS", "SIGNATURE"}
|
|
652
|
+
TRUNCATE = {"COVERAGE_PROCESS_CONFIG"}
|
|
653
|
+
TRUNCATE_LEN = 60
|
|
654
|
+
|
|
655
|
+
to_show = []
|
|
656
|
+
for name, val in env.items():
|
|
657
|
+
show = False
|
|
658
|
+
if name in INCLUDE:
|
|
659
|
+
show = True
|
|
660
|
+
elif any(slug in name for slug in SLUGS):
|
|
661
|
+
show = True
|
|
662
|
+
if show:
|
|
663
|
+
if any(slug in name for slug in CLOAK):
|
|
664
|
+
val = re.sub(r"\w", "*", val)
|
|
665
|
+
if name in TRUNCATE:
|
|
666
|
+
if len(val) > TRUNCATE_LEN:
|
|
667
|
+
val = val[: TRUNCATE_LEN - 3] + "..."
|
|
668
|
+
to_show.append((name, val))
|
|
669
|
+
return human_sorted_items(to_show)
|