0
# Core Coverage Measurement
1
2
Primary coverage measurement and control functionality. The Coverage class serves as the main entry point for all coverage operations, managing measurement lifecycle, configuration, and basic analysis.
3
4
## Capabilities
5
6
### Coverage Class Constructor
7
8
Creates a Coverage instance with comprehensive configuration options for measurement control, data management, and source filtering.
9
10
```python { .api }
11
class Coverage:
12
def __init__(
13
self,
14
data_file=None, # Path to coverage data file
15
data_suffix=None, # Suffix for data file names
16
cover_pylib=None, # Include Python standard library
17
auto_data=False, # Automatically save data on exit
18
timid=None, # Use simpler but slower tracing
19
branch=None, # Enable branch coverage measurement
20
config_file=True, # Path to config file or boolean
21
source=None, # Source files/directories to measure
22
source_pkgs=None, # Source packages to measure
23
source_dirs=None, # Source directories to measure
24
omit=None, # Files/patterns to omit
25
include=None, # Files/patterns to include
26
debug=None, # Debug options list
27
concurrency=None, # Concurrency libraries in use
28
check_preimported=False, # Check already imported modules
29
context=None, # Context label for this run
30
messages=False, # Show messages during execution
31
plugins=None # Plugin callables list
32
):
33
"""
34
Create a Coverage instance for measurement and reporting.
35
36
Parameters:
37
- data_file (str | None): Path to the data file. If None, uses default
38
- data_suffix (str | bool | None): Suffix for parallel data files
39
- cover_pylib (bool | None): Whether to measure standard library
40
- auto_data (bool): Automatically save data when program ends
41
- timid (bool | None): Use simpler trace function for compatibility
42
- branch (bool | None): Measure branch coverage in addition to lines
43
- config_file (str | bool): Configuration file path or False to disable
44
- source (list[str] | None): Source files or directories to measure
45
- source_pkgs (list[str] | None): Source packages to measure
46
- source_dirs (list[str] | None): Source directories to measure
47
- omit (str | list[str] | None): File patterns to omit from measurement
48
- include (str | list[str] | None): File patterns to include in measurement
49
- debug (list[str] | None): Debug options ('trace', 'config', 'callers', etc.)
50
- concurrency (str | list[str] | None): Concurrency library names
51
- check_preimported (bool): Check for modules imported before start
52
- context (str | None): Context label for this measurement run
53
- messages (bool): Display informational messages during execution
54
- plugins (list[callable] | None): Plugin initialization functions
55
"""
56
```
57
58
Usage example:
59
60
```python
61
import coverage
62
63
# Basic usage
64
cov = coverage.Coverage()
65
66
# Advanced configuration
67
cov = coverage.Coverage(
68
data_file='.coverage',
69
branch=True,
70
source=['src/'],
71
omit=['*/tests/*', '*/venv/*'],
72
config_file='pyproject.toml'
73
)
74
```
75
76
### Measurement Control
77
78
Start, stop, and manage coverage measurement with context switching support for dynamic analysis.
79
80
```python { .api }
81
def start(self) -> None:
82
"""
83
Start coverage measurement.
84
85
Raises:
86
CoverageException: If coverage is already started
87
"""
88
89
def stop(self) -> None:
90
"""
91
Stop coverage measurement.
92
93
Returns data can be retrieved and reports generated after stopping.
94
"""
95
96
def switch_context(self, new_context: str) -> None:
97
"""
98
Switch to a new dynamic context for measurement.
99
100
Parameters:
101
- new_context (str): New context label
102
"""
103
104
@contextlib.contextmanager
105
def collect(self):
106
"""
107
Context manager for temporary coverage collection.
108
109
Usage:
110
with cov.collect():
111
# Code to measure
112
pass
113
"""
114
```
115
116
Usage example:
117
118
```python
119
import coverage
120
121
cov = coverage.Coverage()
122
123
# Basic measurement
124
cov.start()
125
# Your code here
126
import my_module
127
result = my_module.function()
128
cov.stop()
129
130
# Context switching
131
cov.start()
132
cov.switch_context('test_setup')
133
setup_code()
134
cov.switch_context('test_execution')
135
test_code()
136
cov.stop()
137
138
# Context manager
139
with cov.collect():
140
code_to_measure()
141
```
142
143
### Data Management
144
145
Save, load, and manage coverage data with combining support for parallel execution.
146
147
```python { .api }
148
def save(self) -> None:
149
"""
150
Save collected coverage data to file.
151
152
Data is saved to the data file specified in constructor.
153
"""
154
155
def load(self) -> None:
156
"""
157
Load previously collected coverage data from file.
158
"""
159
160
def erase(self) -> None:
161
"""
162
Erase collected coverage data.
163
164
Clears both in-memory data and data file.
165
"""
166
167
def get_data(self) -> CoverageData:
168
"""
169
Get the collected coverage data.
170
171
Returns:
172
CoverageData: Data object for querying and analysis
173
"""
174
175
def combine(
176
self,
177
data_paths=None,
178
strict=False,
179
keep=False
180
) -> None:
181
"""
182
Combine coverage data from multiple files.
183
184
Parameters:
185
- data_paths (list[str] | None): Paths to data files or directories
186
- strict (bool): Raise error if no data files found
187
- keep (bool): Keep original data files after combining
188
"""
189
```
190
191
Usage example:
192
193
```python
194
import coverage
195
196
cov = coverage.Coverage()
197
198
# Basic data operations
199
cov.start()
200
# ... run code ...
201
cov.stop()
202
cov.save()
203
204
# Later, load and analyze
205
cov2 = coverage.Coverage()
206
cov2.load()
207
data = cov2.get_data()
208
209
# Combine parallel data files
210
cov.combine(['data1/.coverage', 'data2/.coverage'])
211
```
212
213
### Configuration Methods
214
215
Get and set configuration options programmatically.
216
217
```python { .api }
218
def get_option(self, option_name: str):
219
"""
220
Get a configuration option value.
221
222
Parameters:
223
- option_name (str): Name of the configuration option
224
225
Returns:
226
Configuration option value
227
"""
228
229
def set_option(self, option_name: str, value) -> None:
230
"""
231
Set a configuration option value.
232
233
Parameters:
234
- option_name (str): Name of the configuration option
235
- value: New value for the option
236
"""
237
```
238
239
Usage example:
240
241
```python
242
import coverage
243
244
cov = coverage.Coverage()
245
246
# Get current settings
247
branch_enabled = cov.get_option('run:branch')
248
source_dirs = cov.get_option('run:source')
249
250
# Modify settings
251
cov.set_option('run:branch', True)
252
cov.set_option('run:omit', ['*/tests/*'])
253
```
254
255
### Exclusion Management
256
257
Manage regex patterns for excluding lines from coverage measurement.
258
259
```python { .api }
260
def exclude(self, regex: str, which: str = 'exclude') -> None:
261
"""
262
Add a regex pattern for excluding lines from coverage.
263
264
Parameters:
265
- regex (str): Regular expression pattern
266
- which (str): Exclusion category ('exclude', 'partial', 'partial-always')
267
"""
268
269
def clear_exclude(self, which: str = 'exclude') -> None:
270
"""
271
Clear all exclusion patterns for a category.
272
273
Parameters:
274
- which (str): Exclusion category to clear
275
"""
276
277
def get_exclude_list(self, which: str = 'exclude') -> list[str]:
278
"""
279
Get list of exclusion patterns for a category.
280
281
Parameters:
282
- which (str): Exclusion category
283
284
Returns:
285
list[str]: List of regex patterns
286
"""
287
```
288
289
Usage example:
290
291
```python
292
import coverage
293
294
cov = coverage.Coverage()
295
296
# Add exclusion patterns
297
cov.exclude(r'pragma: no cover')
298
cov.exclude(r'def __repr__')
299
cov.exclude(r'raise NotImplementedError')
300
301
# Check current exclusions
302
patterns = cov.get_exclude_list()
303
print(f"Exclusion patterns: {patterns}")
304
305
# Clear exclusions
306
cov.clear_exclude()
307
```
308
309
### Analysis Methods
310
311
Analyze coverage results for individual modules or files.
312
313
```python { .api }
314
def analysis2(self, morf):
315
"""
316
Analyze coverage for a module or file.
317
318
Parameters:
319
- morf: Module object or filename string
320
321
Returns:
322
tuple: (filename, statements, excluded, missing, readable_filename)
323
"""
324
325
def branch_stats(self, morf) -> dict[int, tuple[int, int]]:
326
"""
327
Get branch coverage statistics for a file.
328
329
Parameters:
330
- morf: Module object or filename string
331
332
Returns:
333
dict: Mapping of line numbers to (branches_possible, branches_taken)
334
"""
335
```
336
337
Usage example:
338
339
```python
340
import coverage
341
import my_module
342
343
cov = coverage.Coverage(branch=True)
344
cov.start()
345
# ... run code ...
346
cov.stop()
347
348
# Analyze specific module
349
filename, statements, excluded, missing, readable = cov.analysis2(my_module)
350
print(f"File: {readable}")
351
print(f"Statements: {len(statements)}")
352
print(f"Missing: {len(missing)}")
353
354
# Branch statistics
355
branch_stats = cov.branch_stats(my_module)
356
for line, (possible, taken) in branch_stats.items():
357
print(f"Line {line}: {taken}/{possible} branches taken")
358
```
359
360
### Class Methods
361
362
Static methods for accessing the current Coverage instance.
363
364
```python { .api }
365
@classmethod
366
def current(cls):
367
"""
368
Get the most recently started Coverage instance.
369
370
Returns:
371
Coverage | None: The current instance or None if none started
372
"""
373
```
374
375
### System Information
376
377
Get debugging and system information.
378
379
```python { .api }
380
def sys_info(self):
381
"""
382
Return system information for debugging.
383
384
Returns:
385
Iterable[tuple[str, Any]]: System information key-value pairs
386
"""
387
```
388
389
### Utility Functions
390
391
Module-level utility functions for coverage operations.
392
393
```python { .api }
394
def process_startup(*, force: bool = False):
395
"""
396
Initialize coverage measurement in subprocess contexts.
397
398
Parameters:
399
- force (bool): Force initialization even if already started
400
401
Returns:
402
Coverage | None: Coverage instance or None if not configured
403
"""
404
```
405
406
Usage example:
407
408
```python
409
import coverage
410
411
# In a subprocess or multiprocessing context
412
cov = coverage.process_startup()
413
if cov:
414
print("Coverage started in subprocess")
415
```