coverage 7.12.0__cp314-cp314-musllinux_1_2_i686.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 (59) hide show
  1. coverage/__init__.py +40 -0
  2. coverage/__main__.py +12 -0
  3. coverage/annotate.py +114 -0
  4. coverage/bytecode.py +196 -0
  5. coverage/cmdline.py +1184 -0
  6. coverage/collector.py +486 -0
  7. coverage/config.py +731 -0
  8. coverage/context.py +74 -0
  9. coverage/control.py +1481 -0
  10. coverage/core.py +139 -0
  11. coverage/data.py +227 -0
  12. coverage/debug.py +669 -0
  13. coverage/disposition.py +59 -0
  14. coverage/env.py +135 -0
  15. coverage/exceptions.py +85 -0
  16. coverage/execfile.py +329 -0
  17. coverage/files.py +553 -0
  18. coverage/html.py +860 -0
  19. coverage/htmlfiles/coverage_html.js +735 -0
  20. coverage/htmlfiles/favicon_32.png +0 -0
  21. coverage/htmlfiles/index.html +199 -0
  22. coverage/htmlfiles/keybd_closed.png +0 -0
  23. coverage/htmlfiles/pyfile.html +149 -0
  24. coverage/htmlfiles/style.css +385 -0
  25. coverage/htmlfiles/style.scss +842 -0
  26. coverage/inorout.py +614 -0
  27. coverage/jsonreport.py +192 -0
  28. coverage/lcovreport.py +219 -0
  29. coverage/misc.py +373 -0
  30. coverage/multiproc.py +120 -0
  31. coverage/numbits.py +146 -0
  32. coverage/parser.py +1215 -0
  33. coverage/patch.py +166 -0
  34. coverage/phystokens.py +197 -0
  35. coverage/plugin.py +617 -0
  36. coverage/plugin_support.py +299 -0
  37. coverage/py.typed +1 -0
  38. coverage/python.py +272 -0
  39. coverage/pytracer.py +369 -0
  40. coverage/regions.py +127 -0
  41. coverage/report.py +298 -0
  42. coverage/report_core.py +117 -0
  43. coverage/results.py +502 -0
  44. coverage/sqldata.py +1153 -0
  45. coverage/sqlitedb.py +239 -0
  46. coverage/sysmon.py +513 -0
  47. coverage/templite.py +318 -0
  48. coverage/tomlconfig.py +210 -0
  49. coverage/tracer.cpython-314-i386-linux-musl.so +0 -0
  50. coverage/tracer.pyi +43 -0
  51. coverage/types.py +206 -0
  52. coverage/version.py +35 -0
  53. coverage/xmlreport.py +264 -0
  54. coverage-7.12.0.dist-info/METADATA +221 -0
  55. coverage-7.12.0.dist-info/RECORD +59 -0
  56. coverage-7.12.0.dist-info/WHEEL +5 -0
  57. coverage-7.12.0.dist-info/entry_points.txt +4 -0
  58. coverage-7.12.0.dist-info/licenses/LICENSE.txt +177 -0
  59. coverage-7.12.0.dist-info/top_level.txt +1 -0
coverage/control.py ADDED
@@ -0,0 +1,1481 @@
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
+ """Central control stuff for coverage.py."""
5
+
6
+ from __future__ import annotations
7
+
8
+ import atexit
9
+ import collections
10
+ import contextlib
11
+ import datetime
12
+ import functools
13
+ import os
14
+ import os.path
15
+ import platform
16
+ import signal
17
+ import sys
18
+ import threading
19
+ import time
20
+ import warnings
21
+ from collections.abc import Iterable, Iterator
22
+ from types import FrameType
23
+ from typing import IO, Any, Callable, cast
24
+
25
+ from coverage import env
26
+ from coverage.annotate import AnnotateReporter
27
+ from coverage.collector import Collector
28
+ from coverage.config import CoverageConfig, read_coverage_config
29
+ from coverage.context import combine_context_switchers, should_start_context_test_function
30
+ from coverage.core import CTRACER_FILE, Core
31
+ from coverage.data import CoverageData, combine_parallel_data
32
+ from coverage.debug import (
33
+ DebugControl,
34
+ NoDebugging,
35
+ relevant_environment_display,
36
+ short_stack,
37
+ write_formatted_info,
38
+ )
39
+ from coverage.disposition import disposition_debug_msg
40
+ from coverage.exceptions import ConfigError, CoverageException, CoverageWarning, PluginError
41
+ from coverage.files import PathAliases, abs_file, relative_filename, set_relative_directory
42
+ from coverage.html import HtmlReporter
43
+ from coverage.inorout import InOrOut
44
+ from coverage.jsonreport import JsonReporter
45
+ from coverage.lcovreport import LcovReporter
46
+ from coverage.misc import (
47
+ DefaultValue,
48
+ bool_or_none,
49
+ ensure_dir_for_file,
50
+ isolate_module,
51
+ join_regex,
52
+ )
53
+ from coverage.multiproc import patch_multiprocessing
54
+ from coverage.patch import apply_patches
55
+ from coverage.plugin import FileReporter
56
+ from coverage.plugin_support import Plugins, TCoverageInit
57
+ from coverage.python import PythonFileReporter
58
+ from coverage.report import SummaryReporter
59
+ from coverage.report_core import render_report
60
+ from coverage.results import Analysis, analysis_from_file_reporter
61
+ from coverage.types import (
62
+ FilePath,
63
+ TConfigSectionIn,
64
+ TConfigurable,
65
+ TConfigValueIn,
66
+ TConfigValueOut,
67
+ TFileDisposition,
68
+ TLineNo,
69
+ TMorf,
70
+ )
71
+ from coverage.version import __url__
72
+ from coverage.xmlreport import XmlReporter
73
+
74
+ os = isolate_module(os)
75
+
76
+
77
+ @contextlib.contextmanager
78
+ def override_config(cov: Coverage, **kwargs: TConfigValueIn) -> Iterator[None]:
79
+ """Temporarily tweak the configuration of `cov`.
80
+
81
+ The arguments are applied to `cov.config` with the `from_args` method.
82
+ At the end of the with-statement, the old configuration is restored.
83
+ """
84
+ original_config = cov.config
85
+ cov.config = cov.config.copy()
86
+ try:
87
+ cov.config.from_args(**kwargs)
88
+ yield
89
+ finally:
90
+ cov.config = original_config
91
+
92
+
93
+ DEFAULT_DATAFILE = DefaultValue("MISSING")
94
+ _DEFAULT_DATAFILE = DEFAULT_DATAFILE # Just in case, for backwards compatibility
95
+ CONFIG_DATA_PREFIX = ":data:"
96
+
97
+
98
+ class Coverage(TConfigurable):
99
+ """Programmatic access to coverage.py.
100
+
101
+ To use::
102
+
103
+ from coverage import Coverage
104
+
105
+ cov = Coverage()
106
+ cov.start()
107
+ #.. call your code ..
108
+ cov.stop()
109
+ cov.html_report(directory="covhtml")
110
+
111
+ A context manager is available to do the same thing::
112
+
113
+ cov = Coverage()
114
+ with cov.collect():
115
+ #.. call your code ..
116
+ cov.html_report(directory="covhtml")
117
+
118
+ Note: in keeping with Python custom, names starting with underscore are
119
+ not part of the public API. They might stop working at any point. Please
120
+ limit yourself to documented methods to avoid problems.
121
+
122
+ Methods can raise any of the exceptions described in :ref:`api_exceptions`.
123
+
124
+ """
125
+
126
+ # The stack of started Coverage instances.
127
+ _instances: list[Coverage] = []
128
+
129
+ @classmethod
130
+ def current(cls) -> Coverage | None:
131
+ """Get the latest started `Coverage` instance, if any.
132
+
133
+ Returns: a `Coverage` instance, or None.
134
+
135
+ .. versionadded:: 5.0
136
+
137
+ """
138
+ if cls._instances:
139
+ return cls._instances[-1]
140
+ else:
141
+ return None
142
+
143
+ def __init__( # pylint: disable=too-many-arguments
144
+ self,
145
+ data_file: FilePath | DefaultValue | None = DEFAULT_DATAFILE,
146
+ data_suffix: str | bool | None = None,
147
+ cover_pylib: bool | None = None,
148
+ auto_data: bool = False,
149
+ timid: bool | None = None,
150
+ branch: bool | None = None,
151
+ config_file: FilePath | bool = True,
152
+ source: Iterable[str] | None = None,
153
+ source_pkgs: Iterable[str] | None = None,
154
+ source_dirs: Iterable[str] | None = None,
155
+ omit: str | Iterable[str] | None = None,
156
+ include: str | Iterable[str] | None = None,
157
+ debug: Iterable[str] | None = None,
158
+ concurrency: str | Iterable[str] | None = None,
159
+ check_preimported: bool = False,
160
+ context: str | None = None,
161
+ messages: bool = False,
162
+ plugins: Iterable[Callable[..., None]] | None = None,
163
+ ) -> None:
164
+ """
165
+ Many of these arguments duplicate and override values that can be
166
+ provided in a configuration file. Parameters that are missing here
167
+ will use values from the config file.
168
+
169
+ `data_file` is the base name of the data file to use. The config value
170
+ defaults to ".coverage". None can be provided to prevent writing a data
171
+ file. `data_suffix` is appended (with a dot) to `data_file` to create
172
+ the final file name. If `data_suffix` is simply True, then a suffix is
173
+ created with the machine and process identity included.
174
+
175
+ `cover_pylib` is a boolean determining whether Python code installed
176
+ with the Python interpreter is measured. This includes the Python
177
+ standard library and any packages installed with the interpreter.
178
+
179
+ If `auto_data` is true, then any existing data file will be read when
180
+ coverage measurement starts, and data will be saved automatically when
181
+ measurement stops.
182
+
183
+ If `timid` is true, then a slower and simpler trace function will be
184
+ used. This is important for some environments where manipulation of
185
+ tracing functions breaks the faster trace function.
186
+
187
+ If `branch` is true, then branch coverage will be measured in addition
188
+ to the usual statement coverage.
189
+
190
+ `config_file` determines what configuration file to read:
191
+
192
+ * If it is ".coveragerc", it is interpreted as if it were True,
193
+ for backward compatibility.
194
+
195
+ * If it is a string, it is the name of the file to read. If the
196
+ file can't be read, it is an error.
197
+
198
+ * If it is True, then a few standard files names are tried
199
+ (".coveragerc", "setup.cfg", "tox.ini"). It is not an error for
200
+ these files to not be found.
201
+
202
+ * If it is False, then no configuration file is read.
203
+
204
+ `source` is a list of file paths or package names. Only code located
205
+ in the trees indicated by the file paths or package names will be
206
+ measured.
207
+
208
+ `source_pkgs` is a list of package names. It works the same as
209
+ `source`, but can be used to name packages where the name can also be
210
+ interpreted as a file path.
211
+
212
+ `source_dirs` is a list of file paths. It works the same as
213
+ `source`, but raises an error if the path doesn't exist, rather
214
+ than being treated as a package name.
215
+
216
+ `include` and `omit` are lists of file name patterns. Files that match
217
+ `include` will be measured, files that match `omit` will not. Each
218
+ will also accept a single string argument.
219
+
220
+ `debug` is a list of strings indicating what debugging information is
221
+ desired.
222
+
223
+ `concurrency` is a string indicating the concurrency library being used
224
+ in the measured code. Without this, coverage.py will get incorrect
225
+ results if these libraries are in use. Valid strings are "greenlet",
226
+ "eventlet", "gevent", "multiprocessing", or "thread" (the default).
227
+ This can also be a list of these strings.
228
+
229
+ If `check_preimported` is true, then when coverage is started, the
230
+ already-imported files will be checked to see if they should be
231
+ measured by coverage. Importing measured files before coverage is
232
+ started can mean that code is missed.
233
+
234
+ `context` is a string to use as the :ref:`static context
235
+ <static_contexts>` label for collected data.
236
+
237
+ If `messages` is true, some messages will be printed to stdout
238
+ indicating what is happening.
239
+
240
+ If `plugins` are passed, they are an iterable of function objects
241
+ accepting a `reg` object to register plugins, as described in
242
+ :ref:`api_plugin`. When they are provided, they will override the
243
+ plugins found in the coverage configuration file.
244
+
245
+ .. versionadded:: 4.0
246
+ The `concurrency` parameter.
247
+
248
+ .. versionadded:: 4.2
249
+ The `concurrency` parameter can now be a list of strings.
250
+
251
+ .. versionadded:: 5.0
252
+ The `check_preimported` and `context` parameters.
253
+
254
+ .. versionadded:: 5.3
255
+ The `source_pkgs` parameter.
256
+
257
+ .. versionadded:: 6.0
258
+ The `messages` parameter.
259
+
260
+ .. versionadded:: 7.7
261
+ The `plugins` parameter.
262
+
263
+ .. versionadded:: 7.8
264
+ The `source_dirs` parameter.
265
+ """
266
+ # Start self.config as a usable default configuration. It will soon be
267
+ # replaced with the real configuration.
268
+ self.config = CoverageConfig()
269
+
270
+ # data_file=None means no disk file at all. data_file missing means
271
+ # use the value from the config file.
272
+ self._no_disk = data_file is None
273
+ if isinstance(data_file, DefaultValue):
274
+ data_file = None
275
+ if data_file is not None:
276
+ data_file = os.fspath(data_file)
277
+
278
+ # This is injectable by tests.
279
+ self._debug_file: IO[str] | None = None
280
+
281
+ self._auto_load = self._auto_save = auto_data
282
+ self._data_suffix_specified = data_suffix
283
+
284
+ # Is it ok for no data to be collected?
285
+ self._warn_no_data = True
286
+ self._warn_unimported_source = True
287
+ self._warn_preimported_source = check_preimported
288
+ self._no_warn_slugs: set[str] = set()
289
+ self._messages = messages
290
+
291
+ # If we're invoked from a .pth file, we shouldn't try to make another one.
292
+ self._make_pth_file = True
293
+
294
+ # A record of all the warnings that have been issued.
295
+ self._warnings: list[str] = []
296
+
297
+ # Other instance attributes, set with placebos or placeholders.
298
+ # More useful objects will be created later.
299
+ self._debug: DebugControl = NoDebugging()
300
+ self._inorout: InOrOut | None = None
301
+ self._plugins: Plugins = Plugins()
302
+ self._plugin_override = cast(Iterable[TCoverageInit] | None, plugins)
303
+ self._data: CoverageData | None = None
304
+ self._data_to_close: list[CoverageData] = []
305
+ self._core: Core | None = None
306
+ self._collector: Collector | None = None
307
+ self._metacov = False
308
+
309
+ self._file_mapper: Callable[[str], str] = abs_file
310
+ self._data_suffix = self._run_suffix = None
311
+ self._exclude_re: dict[str, str] = {}
312
+ self._old_sigterm: Callable[[int, FrameType | None], Any] | None = None
313
+
314
+ # State machine variables:
315
+ # Have we initialized everything?
316
+ self._inited = False
317
+ self._inited_for_start = False
318
+ # Have we started collecting and not stopped it?
319
+ self._started = False
320
+ # Should we write the debug output?
321
+ self._should_write_debug = True
322
+
323
+ # Build our configuration from a number of sources.
324
+ if isinstance(config_file, str) and config_file.startswith(CONFIG_DATA_PREFIX):
325
+ self.config = CoverageConfig.deserialize(config_file[len(CONFIG_DATA_PREFIX) :])
326
+ else:
327
+ if not isinstance(config_file, bool):
328
+ config_file = os.fspath(config_file)
329
+ self.config = read_coverage_config(
330
+ config_file=config_file,
331
+ warn=self._warn,
332
+ data_file=data_file,
333
+ cover_pylib=cover_pylib,
334
+ timid=timid,
335
+ branch=branch,
336
+ parallel=bool_or_none(data_suffix),
337
+ source=source,
338
+ source_pkgs=source_pkgs,
339
+ source_dirs=source_dirs,
340
+ run_omit=omit,
341
+ run_include=include,
342
+ debug=debug,
343
+ report_omit=omit,
344
+ report_include=include,
345
+ concurrency=concurrency,
346
+ context=context,
347
+ )
348
+
349
+ # If we have subprocess measurement happening automatically, then we
350
+ # want any explicit creation of a Coverage object to mean, this process
351
+ # is already coverage-aware, so don't auto-measure it. By now, the
352
+ # auto-creation of a Coverage object has already happened. But we can
353
+ # find it and tell it not to save its data.
354
+ if not env.METACOV:
355
+ _prevent_sub_process_measurement()
356
+
357
+ def _init(self) -> None:
358
+ """Set all the initial state.
359
+
360
+ This is called by the public methods to initialize state. This lets us
361
+ construct a :class:`Coverage` object, then tweak its state before this
362
+ function is called.
363
+
364
+ """
365
+ if self._inited:
366
+ return
367
+
368
+ self._inited = True
369
+
370
+ # Create and configure the debugging controller.
371
+ self._debug = DebugControl(self.config.debug, self._debug_file, self.config.debug_file)
372
+ if self._debug.should("process"):
373
+ self._debug.write("Coverage._init")
374
+
375
+ if "multiprocessing" in (self.config.concurrency or ()):
376
+ # Multi-processing uses parallel for the subprocesses, so also use
377
+ # it for the main process.
378
+ self.config.parallel = True
379
+
380
+ # _exclude_re is a dict that maps exclusion list names to compiled regexes.
381
+ self._exclude_re = {}
382
+
383
+ set_relative_directory()
384
+ if self.config.relative_files:
385
+ self._file_mapper = relative_filename
386
+
387
+ # Load plugins
388
+ self._plugins = Plugins(self._debug)
389
+ if self._plugin_override:
390
+ self._plugins.load_from_callables(self._plugin_override)
391
+ else:
392
+ self._plugins.load_from_config(self.config.plugins, self.config)
393
+
394
+ # Run configuring plugins.
395
+ for plugin in self._plugins.configurers:
396
+ # We need an object with set_option and get_option. Either self or
397
+ # self.config will do. Choosing randomly stops people from doing
398
+ # other things with those objects, against the public API. Yes,
399
+ # this is a bit childish. :)
400
+ plugin.configure([self, self.config][int(time.time()) % 2])
401
+
402
+ def _post_init(self) -> None:
403
+ """Stuff to do after everything is initialized."""
404
+ if self._should_write_debug:
405
+ self._should_write_debug = False
406
+ self._write_startup_debug()
407
+
408
+ # "[run] _crash" will raise an exception if the value is close by in
409
+ # the call stack, for testing error handling.
410
+ if self.config._crash and self.config._crash in short_stack():
411
+ raise RuntimeError(f"Crashing because called by {self.config._crash}")
412
+
413
+ def _write_startup_debug(self) -> None:
414
+ """Write out debug info at startup if needed."""
415
+ wrote_any = False
416
+ with self._debug.without_callers():
417
+ if self._debug.should("config"):
418
+ write_formatted_info(self._debug.write, "config", self.config.debug_info())
419
+ wrote_any = True
420
+
421
+ if self._debug.should("sys"):
422
+ write_formatted_info(self._debug.write, "sys", self.sys_info())
423
+ for plugin in self._plugins:
424
+ header = "sys: " + plugin._coverage_plugin_name
425
+ write_formatted_info(self._debug.write, header, plugin.sys_info())
426
+ wrote_any = True
427
+
428
+ if self._debug.should("pybehave"):
429
+ write_formatted_info(self._debug.write, "pybehave", env.debug_info())
430
+ wrote_any = True
431
+
432
+ if self._debug.should("sqlite"):
433
+ write_formatted_info(self._debug.write, "sqlite", CoverageData.sys_info())
434
+ wrote_any = True
435
+
436
+ if wrote_any:
437
+ write_formatted_info(self._debug.write, "end", ())
438
+
439
+ def _should_trace(self, filename: str, frame: FrameType) -> TFileDisposition:
440
+ """Decide whether to trace execution in `filename`.
441
+
442
+ Calls `_should_trace_internal`, and returns the FileDisposition.
443
+
444
+ """
445
+ assert self._inorout is not None
446
+ disp = self._inorout.should_trace(filename, frame)
447
+ if self._debug.should("trace"):
448
+ self._debug.write(disposition_debug_msg(disp))
449
+ return disp
450
+
451
+ def _check_include_omit_etc(self, filename: str, frame: FrameType) -> bool:
452
+ """Check a file name against the include/omit/etc, rules, verbosely.
453
+
454
+ Returns a boolean: True if the file should be traced, False if not.
455
+
456
+ """
457
+ assert self._inorout is not None
458
+ reason = self._inorout.check_include_omit_etc(filename, frame)
459
+ if self._debug.should("trace"):
460
+ if not reason:
461
+ msg = f"Including {filename!r}"
462
+ else:
463
+ msg = f"Not including {filename!r}: {reason}"
464
+ self._debug.write(msg)
465
+
466
+ return not reason
467
+
468
+ def _warn(self, msg: str, slug: str | None = None, once: bool = False) -> None:
469
+ """Use `msg` as a warning.
470
+
471
+ For warning suppression, use `slug` as the shorthand.
472
+
473
+ If `once` is true, only show this warning once (determined by the
474
+ slug.)
475
+
476
+ """
477
+ if not self._no_warn_slugs:
478
+ self._no_warn_slugs = set(self.config.disable_warnings)
479
+
480
+ if slug in self._no_warn_slugs:
481
+ # Don't issue the warning
482
+ return
483
+
484
+ self._warnings.append(msg)
485
+ if slug:
486
+ msg = f"{msg} ({slug}); see {__url__}/messages.html#warning-{slug}"
487
+ if self._debug.should("pid"):
488
+ msg = f"[{os.getpid()}] {msg}"
489
+ warnings.warn(msg, category=CoverageWarning, stacklevel=2)
490
+
491
+ if once:
492
+ assert slug is not None
493
+ self._no_warn_slugs.add(slug)
494
+
495
+ def _message(self, msg: str) -> None:
496
+ """Write a message to the user, if configured to do so."""
497
+ if self._messages:
498
+ print(msg)
499
+
500
+ def get_option(self, option_name: str) -> TConfigValueOut | None:
501
+ """Get an option from the configuration.
502
+
503
+ `option_name` is a colon-separated string indicating the section and
504
+ option name. For example, the ``branch`` option in the ``[run]``
505
+ section of the config file would be indicated with `"run:branch"`.
506
+
507
+ Returns the value of the option. The type depends on the option
508
+ selected.
509
+
510
+ As a special case, an `option_name` of ``"paths"`` will return an
511
+ dictionary with the entire ``[paths]`` section value.
512
+
513
+ .. versionadded:: 4.0
514
+
515
+ """
516
+ return self.config.get_option(option_name)
517
+
518
+ def set_option(self, option_name: str, value: TConfigValueIn | TConfigSectionIn) -> None:
519
+ """Set an option in the configuration.
520
+
521
+ `option_name` is a colon-separated string indicating the section and
522
+ option name. For example, the ``branch`` option in the ``[run]``
523
+ section of the config file would be indicated with ``"run:branch"``.
524
+
525
+ `value` is the new value for the option. This should be an
526
+ appropriate Python value. For example, use True for booleans, not the
527
+ string ``"True"``.
528
+
529
+ As an example, calling:
530
+
531
+ .. code-block:: python
532
+
533
+ cov.set_option("run:branch", True)
534
+
535
+ has the same effect as this configuration file:
536
+
537
+ .. code-block:: ini
538
+
539
+ [run]
540
+ branch = True
541
+
542
+ As a special case, an `option_name` of ``"paths"`` will replace the
543
+ entire ``[paths]`` section. The value should be a dictionary.
544
+
545
+ .. versionadded:: 4.0
546
+
547
+ """
548
+ self.config.set_option(option_name, value)
549
+
550
+ def load(self) -> None:
551
+ """Load previously-collected coverage data from the data file."""
552
+ self._init()
553
+ if self._collector is not None:
554
+ self._collector.reset()
555
+ should_skip = self.config.parallel and not os.path.exists(self.config.data_file)
556
+ if not should_skip:
557
+ self._init_data(suffix=None)
558
+ self._post_init()
559
+ if not should_skip:
560
+ assert self._data is not None
561
+ self._data.read()
562
+
563
+ def _init_for_start(self) -> None:
564
+ """Initialization for start()"""
565
+ # Construct the collector.
566
+ concurrency: list[str] = self.config.concurrency
567
+ if "multiprocessing" in concurrency:
568
+ if self.config.config_file is None:
569
+ raise ConfigError("multiprocessing requires a configuration file")
570
+ patch_multiprocessing(rcfile=self.config.config_file)
571
+
572
+ dycon = self.config.dynamic_context
573
+ if not dycon or dycon == "none":
574
+ context_switchers = []
575
+ elif dycon == "test_function":
576
+ context_switchers = [should_start_context_test_function]
577
+ else:
578
+ raise ConfigError(f"Don't understand dynamic_context setting: {dycon!r}")
579
+
580
+ context_switchers.extend(
581
+ plugin.dynamic_context for plugin in self._plugins.context_switchers
582
+ )
583
+
584
+ should_start_context = combine_context_switchers(context_switchers)
585
+
586
+ self._core = Core(
587
+ warn=self._warn,
588
+ debug=(self._debug if self._debug.should("core") else None),
589
+ config=self.config,
590
+ dynamic_contexts=(should_start_context is not None),
591
+ metacov=self._metacov,
592
+ )
593
+ self._collector = Collector(
594
+ core=self._core,
595
+ should_trace=self._should_trace,
596
+ check_include=self._check_include_omit_etc,
597
+ should_start_context=should_start_context,
598
+ file_mapper=self._file_mapper,
599
+ branch=self.config.branch,
600
+ warn=self._warn,
601
+ concurrency=concurrency,
602
+ )
603
+
604
+ suffix = self._data_suffix_specified
605
+ if suffix:
606
+ if not isinstance(suffix, str):
607
+ # if data_suffix=True, use .machinename.pid.random
608
+ suffix = True
609
+ elif self.config.parallel:
610
+ if suffix is None:
611
+ suffix = True
612
+ elif not isinstance(suffix, str):
613
+ suffix = bool(suffix)
614
+ else:
615
+ suffix = None
616
+
617
+ self._init_data(suffix)
618
+
619
+ assert self._data is not None
620
+ self._collector.use_data(self._data, self.config.context)
621
+
622
+ # Early warning if we aren't going to be able to support plugins.
623
+ if self._plugins.file_tracers and not self._core.supports_plugins:
624
+ self._warn(
625
+ "Plugin file tracers ({}) aren't supported with {}".format(
626
+ ", ".join(
627
+ plugin._coverage_plugin_name for plugin in self._plugins.file_tracers
628
+ ),
629
+ self._collector.tracer_name(),
630
+ ),
631
+ )
632
+ for plugin in self._plugins.file_tracers:
633
+ plugin._coverage_enabled = False
634
+
635
+ # Create the file classifying substructure.
636
+ self._inorout = InOrOut(
637
+ config=self.config,
638
+ warn=self._warn,
639
+ debug=(self._debug if self._debug.should("trace") else None),
640
+ include_namespace_packages=self.config.include_namespace_packages,
641
+ )
642
+ self._inorout.plugins = self._plugins
643
+ self._inorout.disp_class = self._core.file_disposition_class
644
+
645
+ # It's useful to write debug info after initing for start.
646
+ self._should_write_debug = True
647
+
648
+ # Register our clean-up handlers.
649
+ atexit.register(self._atexit)
650
+ if self.config.sigterm:
651
+ is_main = (threading.current_thread() == threading.main_thread()) # fmt: skip
652
+ if is_main and not env.WINDOWS:
653
+ # The Python docs seem to imply that SIGTERM works uniformly even
654
+ # on Windows, but that's not my experience, and this agrees:
655
+ # https://stackoverflow.com/questions/35772001/x/35792192#35792192
656
+ self._old_sigterm = signal.signal( # type: ignore[assignment]
657
+ signal.SIGTERM,
658
+ self._on_sigterm,
659
+ )
660
+
661
+ def _init_data(self, suffix: str | bool | None) -> None:
662
+ """Create a data file if we don't have one yet."""
663
+ if self._data is None:
664
+ # Create the data file. We do this at construction time so that the
665
+ # data file will be written into the directory where the process
666
+ # started rather than wherever the process eventually chdir'd to.
667
+ ensure_dir_for_file(self.config.data_file)
668
+ self._data = CoverageData(
669
+ basename=self.config.data_file,
670
+ suffix=suffix,
671
+ warn=self._warn,
672
+ debug=self._debug,
673
+ no_disk=self._no_disk,
674
+ )
675
+ self._data_to_close.append(self._data)
676
+
677
+ def start(self) -> None:
678
+ """Start measuring code coverage.
679
+
680
+ Coverage measurement is only collected in functions called after
681
+ :meth:`start` is invoked. Statements in the same scope as
682
+ :meth:`start` won't be measured.
683
+
684
+ Once you invoke :meth:`start`, you must also call :meth:`stop`
685
+ eventually, or your process might not shut down cleanly.
686
+
687
+ The :meth:`collect` method is a context manager to handle both
688
+ starting and stopping collection.
689
+
690
+ """
691
+ self._init()
692
+ if not self._inited_for_start:
693
+ self._inited_for_start = True
694
+ self._init_for_start()
695
+ self._post_init()
696
+
697
+ assert self._collector is not None
698
+ assert self._inorout is not None
699
+
700
+ # Issue warnings for possible problems.
701
+ self._inorout.warn_conflicting_settings()
702
+
703
+ # See if we think some code that would eventually be measured has
704
+ # already been imported.
705
+ if self._warn_preimported_source:
706
+ self._inorout.warn_already_imported_files()
707
+
708
+ if self._auto_load:
709
+ self.load()
710
+
711
+ apply_patches(self, self.config, self._debug, make_pth_file=self._make_pth_file)
712
+
713
+ self._collector.start()
714
+ self._started = True
715
+ self._instances.append(self)
716
+
717
+ def stop(self) -> None:
718
+ """Stop measuring code coverage."""
719
+ if self._instances:
720
+ if self._instances[-1] is self:
721
+ self._instances.pop()
722
+ if self._started:
723
+ assert self._collector is not None
724
+ self._collector.stop()
725
+ self._started = False
726
+
727
+ @contextlib.contextmanager
728
+ def collect(self) -> Iterator[None]:
729
+ """A context manager to start/stop coverage measurement collection.
730
+
731
+ .. versionadded:: 7.3
732
+
733
+ """
734
+ self.start()
735
+ try:
736
+ yield
737
+ finally:
738
+ self.stop() # pragma: nested
739
+
740
+ def _atexit(self, event: str = "atexit") -> None:
741
+ """Clean up on process shutdown."""
742
+ if self._debug.should("process"):
743
+ self._debug.write(f"{event}: pid: {os.getpid()}, instance: {self!r}")
744
+ if self._started:
745
+ self.stop()
746
+ if self._auto_save or event == "sigterm":
747
+ self.save()
748
+ for d in self._data_to_close:
749
+ d.close(force=True)
750
+
751
+ def _on_sigterm(self, signum_unused: int, frame_unused: FrameType | None) -> None:
752
+ """A handler for signal.SIGTERM."""
753
+ self._atexit("sigterm")
754
+ # Statements after here won't be seen by metacov because we just wrote
755
+ # the data, and are about to kill the process.
756
+ signal.signal(signal.SIGTERM, self._old_sigterm) # pragma: not covered
757
+ os.kill(os.getpid(), signal.SIGTERM) # pragma: not covered
758
+
759
+ def erase(self) -> None:
760
+ """Erase previously collected coverage data.
761
+
762
+ This removes the in-memory data collected in this session as well as
763
+ discarding the data file.
764
+
765
+ """
766
+ self._init()
767
+ self._post_init()
768
+ if self._collector is not None:
769
+ self._collector.reset()
770
+ self._init_data(suffix=None)
771
+ assert self._data is not None
772
+ self._data.erase(parallel=self.config.parallel)
773
+ self._data = None
774
+ self._inited_for_start = False
775
+
776
+ def switch_context(self, new_context: str) -> None:
777
+ """Switch to a new dynamic context.
778
+
779
+ `new_context` is a string to use as the :ref:`dynamic context
780
+ <dynamic_contexts>` label for collected data. If a :ref:`static
781
+ context <static_contexts>` is in use, the static and dynamic context
782
+ labels will be joined together with a pipe character.
783
+
784
+ Coverage collection must be started already.
785
+
786
+ .. versionadded:: 5.0
787
+
788
+ """
789
+ if not self._started: # pragma: part started
790
+ raise CoverageException("Cannot switch context, coverage is not started")
791
+
792
+ assert self._collector is not None
793
+ if self._collector.should_start_context:
794
+ self._warn("Conflicting dynamic contexts", slug="dynamic-conflict", once=True)
795
+
796
+ self._collector.switch_context(new_context)
797
+
798
+ def clear_exclude(self, which: str = "exclude") -> None:
799
+ """Clear the exclude list."""
800
+ self._init()
801
+ setattr(self.config, f"{which}_list", [])
802
+ self._exclude_regex_stale()
803
+
804
+ def exclude(self, regex: str, which: str = "exclude") -> None:
805
+ """Exclude source lines from execution consideration.
806
+
807
+ A number of lists of regular expressions are maintained. Each list
808
+ selects lines that are treated differently during reporting.
809
+
810
+ `which` determines which list is modified. The "exclude" list selects
811
+ lines that are not considered executable at all. The "partial" list
812
+ indicates lines with branches that are not taken.
813
+
814
+ `regex` is a regular expression. The regex is added to the specified
815
+ list. If any of the regexes in the list is found in a line, the line
816
+ is marked for special treatment during reporting.
817
+
818
+ """
819
+ self._init()
820
+ excl_list = getattr(self.config, f"{which}_list")
821
+ excl_list.append(regex)
822
+ self._exclude_regex_stale()
823
+
824
+ def _exclude_regex_stale(self) -> None:
825
+ """Drop all the compiled exclusion regexes, a list was modified."""
826
+ self._exclude_re.clear()
827
+
828
+ def _exclude_regex(self, which: str) -> str:
829
+ """Return a regex string for the given exclusion list."""
830
+ if which not in self._exclude_re:
831
+ excl_list = getattr(self.config, f"{which}_list")
832
+ self._exclude_re[which] = join_regex(excl_list)
833
+ return self._exclude_re[which]
834
+
835
+ def get_exclude_list(self, which: str = "exclude") -> list[str]:
836
+ """Return a list of excluded regex strings.
837
+
838
+ `which` indicates which list is desired. See :meth:`exclude` for the
839
+ lists that are available, and their meaning.
840
+
841
+ """
842
+ self._init()
843
+ return cast(list[str], getattr(self.config, f"{which}_list"))
844
+
845
+ def save(self) -> None:
846
+ """Save the collected coverage data to the data file."""
847
+ data = self.get_data()
848
+ data.write()
849
+
850
+ def _make_aliases(self) -> PathAliases:
851
+ """Create a PathAliases from our configuration."""
852
+ aliases = PathAliases(
853
+ debugfn=(self._debug.write if self._debug.should("pathmap") else None),
854
+ relative=self.config.relative_files,
855
+ )
856
+ for paths in self.config.paths.values():
857
+ result = paths[0]
858
+ for pattern in paths[1:]:
859
+ aliases.add(pattern, result)
860
+ return aliases
861
+
862
+ def combine(
863
+ self,
864
+ data_paths: Iterable[str] | None = None,
865
+ strict: bool = False,
866
+ keep: bool = False,
867
+ ) -> None:
868
+ """Combine together a number of similarly-named coverage data files.
869
+
870
+ All coverage data files whose name starts with `data_file` (from the
871
+ coverage() constructor) will be read, and combined together into the
872
+ current measurements.
873
+
874
+ `data_paths` is a list of files or directories from which data should
875
+ be combined. If no list is passed, then the data files from the
876
+ directory indicated by the current data file (probably the current
877
+ directory) will be combined.
878
+
879
+ If `strict` is true, then it is an error to attempt to combine when
880
+ there are no data files to combine.
881
+
882
+ If `keep` is true, then original input data files won't be deleted.
883
+
884
+ .. versionadded:: 4.0
885
+ The `data_paths` parameter.
886
+
887
+ .. versionadded:: 4.3
888
+ The `strict` parameter.
889
+
890
+ .. versionadded: 5.5
891
+ The `keep` parameter.
892
+ """
893
+ self._init()
894
+ self._init_data(suffix=None)
895
+ self._post_init()
896
+ self.get_data()
897
+
898
+ assert self._data is not None
899
+ combine_parallel_data(
900
+ self._data,
901
+ aliases=self._make_aliases(),
902
+ data_paths=data_paths,
903
+ strict=strict,
904
+ keep=keep,
905
+ message=self._message,
906
+ )
907
+
908
+ def get_data(self) -> CoverageData:
909
+ """Get the collected data.
910
+
911
+ Also warn about various problems collecting data.
912
+
913
+ Returns a :class:`coverage.CoverageData`, the collected coverage data.
914
+
915
+ .. versionadded:: 4.0
916
+
917
+ """
918
+ self._init()
919
+ self._init_data(suffix=None)
920
+ self._post_init()
921
+
922
+ if self._collector is not None:
923
+ for plugin in self._plugins:
924
+ if not plugin._coverage_enabled:
925
+ self._collector.plugin_was_disabled(plugin)
926
+
927
+ if self._collector.flush_data():
928
+ self._post_save_work()
929
+
930
+ assert self._data is not None
931
+ return self._data
932
+
933
+ def _post_save_work(self) -> None:
934
+ """After saving data, look for warnings, post-work, etc.
935
+
936
+ Warn about things that should have happened but didn't.
937
+ Look for un-executed files.
938
+
939
+ """
940
+ assert self._data is not None
941
+ assert self._inorout is not None
942
+
943
+ # If there are still entries in the source_pkgs_unmatched list,
944
+ # then we never encountered those packages.
945
+ if self._warn_unimported_source:
946
+ self._inorout.warn_unimported_source()
947
+
948
+ # Find out if we got any data.
949
+ if not self._data and self._warn_no_data:
950
+ self._warn("No data was collected.", slug="no-data-collected")
951
+
952
+ # Touch all the files that could have executed, so that we can
953
+ # mark completely un-executed files as 0% covered.
954
+ file_paths = collections.defaultdict(list)
955
+ for file_path, plugin_name in self._inorout.find_possibly_unexecuted_files():
956
+ file_path = self._file_mapper(file_path)
957
+ file_paths[plugin_name].append(file_path)
958
+ for plugin_name, paths in file_paths.items():
959
+ self._data.touch_files(paths, plugin_name)
960
+
961
+ # Backward compatibility with version 1.
962
+ def analysis(self, morf: TMorf) -> tuple[str, list[TLineNo], list[TLineNo], str]:
963
+ """Like `analysis2` but doesn't return excluded line numbers."""
964
+ f, s, _, m, mf = self.analysis2(morf)
965
+ return f, s, m, mf
966
+
967
+ def analysis2(
968
+ self,
969
+ morf: TMorf,
970
+ ) -> tuple[str, list[TLineNo], list[TLineNo], list[TLineNo], str]:
971
+ """Analyze a module.
972
+
973
+ `morf` is a module or a file name. It will be analyzed to determine
974
+ its coverage statistics. The return value is a 5-tuple:
975
+
976
+ * The file name for the module.
977
+ * A list of line numbers of executable statements.
978
+ * A list of line numbers of excluded statements.
979
+ * A list of line numbers of statements not run (missing from
980
+ execution).
981
+ * A readable formatted string of the missing line numbers.
982
+
983
+ The analysis uses the source file itself and the current measured
984
+ coverage data.
985
+
986
+ """
987
+ analysis = self._analyze(morf)
988
+ return (
989
+ analysis.filename,
990
+ sorted(analysis.statements),
991
+ sorted(analysis.excluded),
992
+ sorted(analysis.missing),
993
+ analysis.missing_formatted(),
994
+ )
995
+
996
+ @functools.lru_cache(maxsize=1)
997
+ def _analyze(self, morf: TMorf) -> Analysis:
998
+ """Analyze a module or file. Private for now."""
999
+ self._init()
1000
+ self._post_init()
1001
+
1002
+ data = self.get_data()
1003
+ file_reporter = self._get_file_reporter(morf)
1004
+ filename = self._file_mapper(file_reporter.filename)
1005
+ return analysis_from_file_reporter(data, self.config.precision, file_reporter, filename)
1006
+
1007
+ def branch_stats(self, morf: TMorf) -> dict[TLineNo, tuple[int, int]]:
1008
+ """Get branch statistics about a module.
1009
+
1010
+ `morf` is a module or a file name.
1011
+
1012
+ Returns a dict mapping line numbers to a tuple:
1013
+ (total_exits, taken_exits).
1014
+
1015
+ .. versionadded:: 7.7
1016
+
1017
+ """
1018
+ analysis = self._analyze(morf)
1019
+ return analysis.branch_stats()
1020
+
1021
+ @functools.lru_cache(maxsize=1)
1022
+ def _get_file_reporter(self, morf: TMorf) -> FileReporter:
1023
+ """Get a FileReporter for a module or file name."""
1024
+ assert self._data is not None
1025
+ plugin = None
1026
+ file_reporter: str | FileReporter = "python"
1027
+
1028
+ if isinstance(morf, str):
1029
+ mapped_morf = self._file_mapper(morf)
1030
+ plugin_name = self._data.file_tracer(mapped_morf)
1031
+ if plugin_name:
1032
+ plugin = self._plugins.get(plugin_name)
1033
+
1034
+ if plugin:
1035
+ file_reporter = plugin.file_reporter(mapped_morf)
1036
+ if file_reporter is None:
1037
+ raise PluginError(
1038
+ "Plugin {!r} did not provide a file reporter for {!r}.".format(
1039
+ plugin._coverage_plugin_name,
1040
+ morf,
1041
+ ),
1042
+ )
1043
+
1044
+ if file_reporter == "python":
1045
+ file_reporter = PythonFileReporter(morf, self)
1046
+
1047
+ assert isinstance(file_reporter, FileReporter)
1048
+ return file_reporter
1049
+
1050
+ def _get_file_reporters(
1051
+ self,
1052
+ morfs: Iterable[TMorf] | None = None,
1053
+ ) -> list[tuple[FileReporter, TMorf]]:
1054
+ """Get FileReporters for a list of modules or file names.
1055
+
1056
+ For each module or file name in `morfs`, find a FileReporter. Return
1057
+ a list pairing FileReporters with the morfs.
1058
+
1059
+ If `morfs` is a single module or file name, this returns a list of one
1060
+ FileReporter. If `morfs` is empty or None, then the list of all files
1061
+ measured is used to find the FileReporters.
1062
+
1063
+ """
1064
+ assert self._data is not None
1065
+ if not morfs:
1066
+ morfs = self._data.measured_files()
1067
+
1068
+ # Be sure we have a collection.
1069
+ if not isinstance(morfs, (list, tuple, set)):
1070
+ morfs = [morfs] # type: ignore[list-item]
1071
+
1072
+ morfs = sorted(morfs, key=lambda m: m if isinstance(m, str) else m.__name__)
1073
+ return [(self._get_file_reporter(morf), morf) for morf in morfs]
1074
+
1075
+ def _prepare_data_for_reporting(self) -> None:
1076
+ """Re-map data before reporting, to get implicit "combine" behavior."""
1077
+ if self.config.paths:
1078
+ mapped_data = CoverageData(warn=self._warn, debug=self._debug, no_disk=True)
1079
+ if self._data is not None:
1080
+ mapped_data.update(self._data, map_path=self._make_aliases().map)
1081
+ self._data = mapped_data
1082
+ self._data_to_close.append(mapped_data)
1083
+
1084
+ def report(
1085
+ self,
1086
+ morfs: Iterable[TMorf] | None = None,
1087
+ show_missing: bool | None = None,
1088
+ ignore_errors: bool | None = None,
1089
+ file: IO[str] | None = None,
1090
+ omit: str | list[str] | None = None,
1091
+ include: str | list[str] | None = None,
1092
+ skip_covered: bool | None = None,
1093
+ contexts: list[str] | None = None,
1094
+ skip_empty: bool | None = None,
1095
+ precision: int | None = None,
1096
+ sort: str | None = None,
1097
+ output_format: str | None = None,
1098
+ ) -> float:
1099
+ """Write a textual summary report to `file`.
1100
+
1101
+ Each module in `morfs` is listed, with counts of statements, executed
1102
+ statements, missing statements, and a list of lines missed.
1103
+
1104
+ If `show_missing` is true, then details of which lines or branches are
1105
+ missing will be included in the report. If `ignore_errors` is true,
1106
+ then a failure while reporting a single file will not stop the entire
1107
+ report.
1108
+
1109
+ `file` is a file-like object, suitable for writing.
1110
+
1111
+ `output_format` determines the format, either "text" (the default),
1112
+ "markdown", or "total".
1113
+
1114
+ `include` is a list of file name patterns. Files that match will be
1115
+ included in the report. Files matching `omit` will not be included in
1116
+ the report.
1117
+
1118
+ If `skip_covered` is true, don't report on files with 100% coverage.
1119
+
1120
+ If `skip_empty` is true, don't report on empty files (those that have
1121
+ no statements).
1122
+
1123
+ `contexts` is a list of regular expression strings. Only data from
1124
+ :ref:`dynamic contexts <dynamic_contexts>` that match one of those
1125
+ expressions (using :func:`re.search <python:re.search>`) will be
1126
+ included in the report.
1127
+
1128
+ `precision` is the number of digits to display after the decimal
1129
+ point for percentages.
1130
+
1131
+ All of the arguments default to the settings read from the
1132
+ :ref:`configuration file <config>`.
1133
+
1134
+ Returns a float, the total percentage covered.
1135
+
1136
+ .. versionadded:: 4.0
1137
+ The `skip_covered` parameter.
1138
+
1139
+ .. versionadded:: 5.0
1140
+ The `contexts` and `skip_empty` parameters.
1141
+
1142
+ .. versionadded:: 5.2
1143
+ The `precision` parameter.
1144
+
1145
+ .. versionadded:: 7.0
1146
+ The `format` parameter.
1147
+
1148
+ """
1149
+ self._prepare_data_for_reporting()
1150
+ with override_config(
1151
+ self,
1152
+ ignore_errors=ignore_errors,
1153
+ report_omit=omit,
1154
+ report_include=include,
1155
+ show_missing=show_missing,
1156
+ skip_covered=skip_covered,
1157
+ report_contexts=contexts,
1158
+ skip_empty=skip_empty,
1159
+ precision=precision,
1160
+ sort=sort,
1161
+ format=output_format,
1162
+ ):
1163
+ reporter = SummaryReporter(self)
1164
+ return reporter.report(morfs, outfile=file)
1165
+
1166
+ def annotate(
1167
+ self,
1168
+ morfs: Iterable[TMorf] | None = None,
1169
+ directory: str | None = None,
1170
+ ignore_errors: bool | None = None,
1171
+ omit: str | list[str] | None = None,
1172
+ include: str | list[str] | None = None,
1173
+ contexts: list[str] | None = None,
1174
+ ) -> None:
1175
+ """Annotate a list of modules.
1176
+
1177
+ Each module in `morfs` is annotated. The source is written to a new
1178
+ file, named with a ",cover" suffix, with each line prefixed with a
1179
+ marker to indicate the coverage of the line. Covered lines have ">",
1180
+ excluded lines have "-", and missing lines have "!".
1181
+
1182
+ See :meth:`report` for other arguments.
1183
+
1184
+ """
1185
+ self._prepare_data_for_reporting()
1186
+ with override_config(
1187
+ self,
1188
+ ignore_errors=ignore_errors,
1189
+ report_omit=omit,
1190
+ report_include=include,
1191
+ report_contexts=contexts,
1192
+ ):
1193
+ reporter = AnnotateReporter(self)
1194
+ reporter.report(morfs, directory=directory)
1195
+
1196
+ def html_report(
1197
+ self,
1198
+ morfs: Iterable[TMorf] | None = None,
1199
+ directory: str | None = None,
1200
+ ignore_errors: bool | None = None,
1201
+ omit: str | list[str] | None = None,
1202
+ include: str | list[str] | None = None,
1203
+ extra_css: str | None = None,
1204
+ title: str | None = None,
1205
+ skip_covered: bool | None = None,
1206
+ show_contexts: bool | None = None,
1207
+ contexts: list[str] | None = None,
1208
+ skip_empty: bool | None = None,
1209
+ precision: int | None = None,
1210
+ ) -> float:
1211
+ """Generate an HTML report.
1212
+
1213
+ The HTML is written to `directory`. The file "index.html" is the
1214
+ overview starting point, with links to more detailed pages for
1215
+ individual modules.
1216
+
1217
+ `extra_css` is a path to a file of other CSS to apply on the page.
1218
+ It will be copied into the HTML directory.
1219
+
1220
+ `title` is a text string (not HTML) to use as the title of the HTML
1221
+ report.
1222
+
1223
+ See :meth:`report` for other arguments.
1224
+
1225
+ Returns a float, the total percentage covered.
1226
+
1227
+ .. note::
1228
+
1229
+ The HTML report files are generated incrementally based on the
1230
+ source files and coverage results. If you modify the report files,
1231
+ the changes will not be considered. You should be careful about
1232
+ changing the files in the report folder.
1233
+
1234
+ """
1235
+ self._prepare_data_for_reporting()
1236
+ with override_config(
1237
+ self,
1238
+ ignore_errors=ignore_errors,
1239
+ report_omit=omit,
1240
+ report_include=include,
1241
+ html_dir=directory,
1242
+ extra_css=extra_css,
1243
+ html_title=title,
1244
+ html_skip_covered=skip_covered,
1245
+ show_contexts=show_contexts,
1246
+ report_contexts=contexts,
1247
+ html_skip_empty=skip_empty,
1248
+ precision=precision,
1249
+ ):
1250
+ reporter = HtmlReporter(self)
1251
+ return reporter.report(morfs)
1252
+
1253
+ def xml_report(
1254
+ self,
1255
+ morfs: Iterable[TMorf] | None = None,
1256
+ outfile: str | None = None,
1257
+ ignore_errors: bool | None = None,
1258
+ omit: str | list[str] | None = None,
1259
+ include: str | list[str] | None = None,
1260
+ contexts: list[str] | None = None,
1261
+ skip_empty: bool | None = None,
1262
+ ) -> float:
1263
+ """Generate an XML report of coverage results.
1264
+
1265
+ The report is compatible with Cobertura reports.
1266
+
1267
+ Each module in `morfs` is included in the report. `outfile` is the
1268
+ path to write the file to, "-" will write to stdout.
1269
+
1270
+ See :meth:`report` for other arguments.
1271
+
1272
+ Returns a float, the total percentage covered.
1273
+
1274
+ """
1275
+ self._prepare_data_for_reporting()
1276
+ with override_config(
1277
+ self,
1278
+ ignore_errors=ignore_errors,
1279
+ report_omit=omit,
1280
+ report_include=include,
1281
+ xml_output=outfile,
1282
+ report_contexts=contexts,
1283
+ skip_empty=skip_empty,
1284
+ ):
1285
+ return render_report(self.config.xml_output, XmlReporter(self), morfs, self._message)
1286
+
1287
+ def json_report(
1288
+ self,
1289
+ morfs: Iterable[TMorf] | None = None,
1290
+ outfile: str | None = None,
1291
+ ignore_errors: bool | None = None,
1292
+ omit: str | list[str] | None = None,
1293
+ include: str | list[str] | None = None,
1294
+ contexts: list[str] | None = None,
1295
+ pretty_print: bool | None = None,
1296
+ show_contexts: bool | None = None,
1297
+ ) -> float:
1298
+ """Generate a JSON report of coverage results.
1299
+
1300
+ Each module in `morfs` is included in the report. `outfile` is the
1301
+ path to write the file to, "-" will write to stdout.
1302
+
1303
+ `pretty_print` is a boolean, whether to pretty-print the JSON output or not.
1304
+
1305
+ See :meth:`report` for other arguments.
1306
+
1307
+ Returns a float, the total percentage covered.
1308
+
1309
+ .. versionadded:: 5.0
1310
+
1311
+ """
1312
+ self._prepare_data_for_reporting()
1313
+ with override_config(
1314
+ self,
1315
+ ignore_errors=ignore_errors,
1316
+ report_omit=omit,
1317
+ report_include=include,
1318
+ json_output=outfile,
1319
+ report_contexts=contexts,
1320
+ json_pretty_print=pretty_print,
1321
+ json_show_contexts=show_contexts,
1322
+ ):
1323
+ return render_report(self.config.json_output, JsonReporter(self), morfs, self._message)
1324
+
1325
+ def lcov_report(
1326
+ self,
1327
+ morfs: Iterable[TMorf] | None = None,
1328
+ outfile: str | None = None,
1329
+ ignore_errors: bool | None = None,
1330
+ omit: str | list[str] | None = None,
1331
+ include: str | list[str] | None = None,
1332
+ contexts: list[str] | None = None,
1333
+ ) -> float:
1334
+ """Generate an LCOV report of coverage results.
1335
+
1336
+ Each module in `morfs` is included in the report. `outfile` is the
1337
+ path to write the file to, "-" will write to stdout.
1338
+
1339
+ See :meth:`report` for other arguments.
1340
+
1341
+ .. versionadded:: 6.3
1342
+ """
1343
+ self._prepare_data_for_reporting()
1344
+ with override_config(
1345
+ self,
1346
+ ignore_errors=ignore_errors,
1347
+ report_omit=omit,
1348
+ report_include=include,
1349
+ lcov_output=outfile,
1350
+ report_contexts=contexts,
1351
+ ):
1352
+ return render_report(self.config.lcov_output, LcovReporter(self), morfs, self._message)
1353
+
1354
+ def sys_info(self) -> Iterable[tuple[str, Any]]:
1355
+ """Return a list of (key, value) pairs showing internal information."""
1356
+
1357
+ import coverage as covmod
1358
+
1359
+ self._init()
1360
+ self._post_init()
1361
+
1362
+ def plugin_info(plugins: list[Any]) -> list[str]:
1363
+ """Make an entry for the sys_info from a list of plug-ins."""
1364
+ entries = []
1365
+ for plugin in plugins:
1366
+ entry = plugin._coverage_plugin_name
1367
+ if not plugin._coverage_enabled:
1368
+ entry += " (disabled)"
1369
+ entries.append(entry)
1370
+ return entries
1371
+
1372
+ info = [
1373
+ ("coverage_version", covmod.__version__),
1374
+ ("coverage_module", covmod.__file__),
1375
+ ("core", self._collector.tracer_name() if self._collector is not None else "-none-"),
1376
+ ("CTracer", f"available from {CTRACER_FILE}" if CTRACER_FILE else "unavailable"),
1377
+ ("plugins.file_tracers", plugin_info(self._plugins.file_tracers)),
1378
+ ("plugins.configurers", plugin_info(self._plugins.configurers)),
1379
+ ("plugins.context_switchers", plugin_info(self._plugins.context_switchers)),
1380
+ ("configs_attempted", self.config.config_files_attempted),
1381
+ ("configs_read", self.config.config_files_read),
1382
+ ("config_file", self.config.config_file),
1383
+ (
1384
+ "config_contents",
1385
+ repr(self.config._config_contents) if self.config._config_contents else "-none-",
1386
+ ),
1387
+ ("data_file", self._data.data_filename() if self._data is not None else "-none-"),
1388
+ ("python", sys.version.replace("\n", "")),
1389
+ ("platform", platform.platform()),
1390
+ ("implementation", platform.python_implementation()),
1391
+ ("build", platform.python_build()),
1392
+ ("gil_enabled", getattr(sys, "_is_gil_enabled", lambda: True)()),
1393
+ ("executable", sys.executable),
1394
+ ("def_encoding", sys.getdefaultencoding()),
1395
+ ("fs_encoding", sys.getfilesystemencoding()),
1396
+ ("pid", os.getpid()),
1397
+ ("cwd", os.getcwd()),
1398
+ ("path", sys.path),
1399
+ ("environment", [f"{k} = {v}" for k, v in relevant_environment_display(os.environ)]),
1400
+ ("command_line", " ".join(getattr(sys, "argv", ["-none-"]))),
1401
+ ("time", f"{datetime.datetime.now():%Y-%m-%d %H:%M:%S}"),
1402
+ ]
1403
+
1404
+ if self._inorout is not None:
1405
+ info.extend(self._inorout.sys_info())
1406
+
1407
+ return info
1408
+
1409
+
1410
+ # Mega debugging...
1411
+ # $set_env.py: COVERAGE_DEBUG_CALLS - Lots and lots of output about calls to Coverage.
1412
+ if int(os.getenv("COVERAGE_DEBUG_CALLS", 0)): # pragma: debugging
1413
+ from coverage.debug import decorate_methods, show_calls
1414
+
1415
+ Coverage = decorate_methods( # type: ignore[misc]
1416
+ show_calls(show_args=True),
1417
+ butnot=["get_data"],
1418
+ )(Coverage)
1419
+
1420
+
1421
+ def process_startup(*, force: bool = False) -> Coverage | None:
1422
+ """Call this at Python start-up to perhaps measure coverage.
1423
+
1424
+ If the environment variable COVERAGE_PROCESS_START is defined, coverage
1425
+ measurement is started. The value of the variable is the config file
1426
+ to use.
1427
+
1428
+ For details, see https://coverage.readthedocs.io/en/latest/subprocess.html.
1429
+
1430
+ Returns the :class:`Coverage` instance that was started, or None if it was
1431
+ not started by this call.
1432
+
1433
+ """
1434
+ config_data = os.getenv("COVERAGE_PROCESS_CONFIG")
1435
+ cps = os.getenv("COVERAGE_PROCESS_START")
1436
+ if config_data is not None:
1437
+ config_file = CONFIG_DATA_PREFIX + config_data
1438
+ elif cps is not None:
1439
+ config_file = cps
1440
+ else:
1441
+ # No request for coverage, nothing to do.
1442
+ return None
1443
+
1444
+ # This function can be called more than once in a process. This happens
1445
+ # because some virtualenv configurations make the same directory visible
1446
+ # twice in sys.path. This means that the .pth file will be found twice,
1447
+ # and executed twice, executing this function twice. We set a global
1448
+ # flag (an attribute on this function) to indicate that coverage.py has
1449
+ # already been started, so we can avoid doing it twice.
1450
+ #
1451
+ # https://github.com/coveragepy/coveragepy/issues/340 has more details.
1452
+
1453
+ if not force and hasattr(process_startup, "coverage"):
1454
+ # We've annotated this function before, so we must have already
1455
+ # auto-started coverage.py in this process. Nothing to do.
1456
+ return None
1457
+
1458
+ cov = Coverage(config_file=config_file)
1459
+ process_startup.coverage = cov # type: ignore[attr-defined]
1460
+ cov._warn_no_data = False
1461
+ cov._warn_unimported_source = False
1462
+ cov._warn_preimported_source = False
1463
+ cov._auto_save = True
1464
+ cov._make_pth_file = False
1465
+ cov.start()
1466
+
1467
+ return cov
1468
+
1469
+
1470
+ def _after_fork_in_child() -> None:
1471
+ """Used by patch=fork in the child process to restart coverage."""
1472
+ if cov := Coverage.current():
1473
+ cov.stop()
1474
+ process_startup(force=True)
1475
+
1476
+
1477
+ def _prevent_sub_process_measurement() -> None:
1478
+ """Stop any subprocess auto-measurement from writing data."""
1479
+ auto_created_coverage = getattr(process_startup, "coverage", None)
1480
+ if auto_created_coverage is not None:
1481
+ auto_created_coverage._auto_save = False