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