0
# Configuration Management
1
2
Comprehensive configuration system supporting multiple file formats (pyproject.toml, .coveragerc), command-line options, and programmatic configuration. Manages source inclusion/exclusion, measurement options, and output settings.
3
4
## Capabilities
5
6
### Configuration Methods
7
8
Get and set configuration options programmatically through the Coverage class.
9
10
```python { .api }
11
def get_option(self, option_name: str):
12
"""
13
Get the value of a configuration option.
14
15
Parameters:
16
- option_name (str): Configuration option name in section:key format
17
18
Returns:
19
Value of the configuration option
20
"""
21
22
def set_option(self, option_name: str, value) -> None:
23
"""
24
Set the value of a configuration option.
25
26
Parameters:
27
- option_name (str): Configuration option name in section:key format
28
- value: New value for the configuration option
29
"""
30
```
31
32
Usage example:
33
34
```python
35
import coverage
36
37
cov = coverage.Coverage()
38
39
# Get configuration values
40
branch_enabled = cov.get_option('run:branch')
41
source_dirs = cov.get_option('run:source')
42
omit_patterns = cov.get_option('run:omit')
43
44
print(f"Branch coverage: {branch_enabled}")
45
print(f"Source directories: {source_dirs}")
46
47
# Set configuration values
48
cov.set_option('run:branch', True)
49
cov.set_option('run:source', ['src/', 'lib/'])
50
cov.set_option('run:omit', ['*/tests/*', '*/migrations/*'])
51
cov.set_option('report:precision', 2)
52
```
53
54
### Configuration File Reading
55
56
Read configuration from various file formats and sources.
57
58
```python { .api }
59
def read_coverage_config(
60
config_file=True,
61
warn=None,
62
debug=None,
63
check_preimported=False,
64
**kwargs
65
):
66
"""
67
Read coverage configuration from files and arguments.
68
69
Parameters:
70
- config_file (str | bool): Path to config file, True for auto-detection, False to disable
71
- warn (callable | None): Function to call with warning messages
72
- debug (callable | None): Function for debug output
73
- check_preimported (bool): Check for already imported modules
74
- **kwargs: Additional configuration options
75
76
Returns:
77
CoverageConfig: Configuration object
78
"""
79
```
80
81
Usage example:
82
83
```python
84
from coverage.config import read_coverage_config
85
86
# Read from default locations (.coveragerc, pyproject.toml, setup.cfg)
87
config = read_coverage_config()
88
89
# Read from specific file
90
config = read_coverage_config(config_file='custom.ini')
91
92
# Read with additional options
93
config = read_coverage_config(
94
config_file='pyproject.toml',
95
branch=True,
96
source=['src/']
97
)
98
99
# Disable config file reading
100
config = read_coverage_config(config_file=False, branch=True)
101
```
102
103
## Configuration File Formats
104
105
### pyproject.toml
106
107
Modern Python project configuration using TOML format:
108
109
```toml
110
[tool.coverage.run]
111
source = ["src"]
112
branch = true
113
omit = [
114
"*/tests/*",
115
"*/venv/*",
116
"*/.tox/*"
117
]
118
119
[tool.coverage.report]
120
exclude_lines = [
121
"pragma: no cover",
122
"def __repr__",
123
"raise AssertionError",
124
"raise NotImplementedError"
125
]
126
show_missing = true
127
skip_covered = true
128
precision = 2
129
130
[tool.coverage.html]
131
directory = "htmlcov"
132
show_contexts = true
133
134
[tool.coverage.xml]
135
output = "coverage.xml"
136
137
[tool.coverage.json]
138
output = "coverage.json"
139
pretty_print = true
140
```
141
142
### .coveragerc
143
144
Legacy INI-style configuration file:
145
146
```ini
147
[run]
148
source = src
149
branch = True
150
omit =
151
*/tests/*
152
*/venv/*
153
*/.tox/*
154
155
[report]
156
exclude_lines =
157
pragma: no cover
158
def __repr__
159
raise AssertionError
160
raise NotImplementedError
161
show_missing = True
162
skip_covered = True
163
precision = 2
164
165
[html]
166
directory = htmlcov
167
show_contexts = True
168
169
[xml]
170
output = coverage.xml
171
172
[json]
173
output = coverage.json
174
pretty_print = True
175
```
176
177
### setup.cfg
178
179
Configuration can also be placed in setup.cfg:
180
181
```ini
182
[coverage:run]
183
source = src
184
branch = True
185
omit =
186
*/tests/*
187
*/venv/*
188
189
[coverage:report]
190
show_missing = True
191
skip_covered = True
192
```
193
194
## Configuration Sections
195
196
### [run] Section
197
198
Controls coverage measurement behavior:
199
200
```python { .api }
201
# Measurement options
202
branch = True | False # Enable branch coverage
203
source = ["dir1", "dir2"] # Source directories/files to measure
204
omit = ["pattern1", "pattern2"] # File patterns to omit
205
include = ["pattern1"] # File patterns to include explicitly
206
207
# Data file options
208
data_file = ".coverage" # Coverage data file path
209
parallel = True | False # Enable parallel data collection
210
context = "context_name" # Static context label
211
212
# Execution options
213
cover_pylib = True | False # Measure Python standard library
214
timid = True | False # Use slower but more compatible tracer
215
concurrency = ["thread", "multiprocessing"] # Concurrency libraries
216
217
# Plugin options
218
plugins = ["plugin1", "plugin2"] # Coverage plugins to load
219
```
220
221
### [report] Section
222
223
Controls text report generation:
224
225
```python { .api }
226
# Output options
227
show_missing = True | False # Show missing line numbers
228
skip_covered = True | False # Skip files with 100% coverage
229
skip_empty = True | False # Skip files with no executable code
230
precision = 2 # Decimal places for percentages
231
232
# File filtering
233
omit = ["pattern1", "pattern2"] # File patterns to omit from report
234
include = ["pattern1"] # File patterns to include in report
235
236
# Line exclusion
237
exclude_lines = [ # Regex patterns for line exclusion
238
"pragma: no cover",
239
"def __repr__",
240
"raise NotImplementedError"
241
]
242
243
# Partial exclusion (for branch coverage)
244
partial_branches = [ # Regex patterns for partial branch exclusion
245
"pragma: no branch",
246
"if __name__ == .__main__.:"
247
]
248
249
# Sorting
250
sort = "name" | "stmts" | "miss" | "branch" | "brpart" | "cover"
251
```
252
253
### [html] Section
254
255
Controls HTML report generation:
256
257
```python { .api }
258
directory = "htmlcov" # Output directory for HTML files
259
title = "Coverage Report" # Title for HTML pages
260
show_contexts = True | False # Include context information
261
extra_css = "custom.css" # Additional CSS file
262
```
263
264
### [xml] Section
265
266
Controls XML report generation:
267
268
```python { .api }
269
output = "coverage.xml" # Output file path
270
```
271
272
### [json] Section
273
274
Controls JSON report generation:
275
276
```python { .api }
277
output = "coverage.json" # Output file path
278
pretty_print = True | False # Format JSON for readability
279
show_contexts = True | False # Include context information
280
```
281
282
### [lcov] Section
283
284
Controls LCOV report generation:
285
286
```python { .api }
287
output = "coverage.lcov" # Output file path
288
```
289
290
### [paths] Section
291
292
Configure path mapping for combining data from different environments:
293
294
```python { .api }
295
# Map paths for data combination
296
source = [
297
"/home/user/project/src", # Local development path
298
"/app/src", # Docker container path
299
"C:\\projects\\myapp\\src" # Windows path
300
]
301
```
302
303
## Advanced Configuration
304
305
### Dynamic Configuration
306
307
Modify configuration at runtime:
308
309
```python
310
import coverage
311
312
cov = coverage.Coverage()
313
314
# Get current configuration
315
config = cov.config
316
317
# Modify configuration
318
config.branch = True
319
config.source = ['src/', 'lib/']
320
config.omit = ['*/tests/*']
321
322
# Update configuration from dictionary
323
config.from_args(
324
branch=True,
325
source=['src/'],
326
omit=['*/test*']
327
)
328
```
329
330
### Environment Variables
331
332
Some configuration can be controlled via environment variables:
333
334
```bash
335
# Disable coverage measurement
336
export COVERAGE_PROCESS_START=""
337
338
# Set data file location
339
export COVERAGE_FILE=".coverage.custom"
340
341
# Enable debug output
342
export COVERAGE_DEBUG="trace,config"
343
```
344
345
### Configuration Validation
346
347
```python
348
from coverage.config import CoverageConfig, ConfigError
349
350
try:
351
config = CoverageConfig()
352
config.from_args(
353
branch=True,
354
source=['nonexistent/'],
355
invalid_option='value' # This will cause an error
356
)
357
except ConfigError as e:
358
print(f"Configuration error: {e}")
359
```
360
361
## Plugin Configuration
362
363
Configure plugins through dedicated sections:
364
365
```toml
366
[tool.coverage.myPlugin]
367
option1 = "value1"
368
option2 = true
369
list_option = ["item1", "item2"]
370
```
371
372
Plugin receives these options in the `coverage_init` function:
373
374
```python
375
def coverage_init(reg, options):
376
# options = {"option1": "value1", "option2": True, "list_option": ["item1", "item2"]}
377
plugin = MyPlugin(options)
378
reg.add_file_tracer(plugin)
379
```
380
381
## Configuration Priority
382
383
Configuration is resolved in this order (highest to lowest priority):
384
385
1. Programmatic options (`Coverage(branch=True)`)
386
2. Command-line options (`coverage run --branch`)
387
3. Configuration file options
388
4. Default values
389
390
### Configuration File Discovery
391
392
Coverage.py searches for configuration in this order:
393
394
1. Specified config file (`config_file='path'`)
395
2. `.coveragerc` in current directory
396
3. `setup.cfg` with `[coverage:*]` sections
397
4. `pyproject.toml` with `[tool.coverage.*]` sections
398
5. `.coveragerc` in user's home directory
399
400
## Complete Configuration Example
401
402
Here's a comprehensive configuration for a typical Python project:
403
404
```toml
405
# pyproject.toml
406
[tool.coverage.run]
407
# Source code to measure
408
source = ["src", "lib"]
409
410
# Enable branch coverage
411
branch = true
412
413
# Files to omit from measurement
414
omit = [
415
"*/tests/*",
416
"*/test_*.py",
417
"*/.tox/*",
418
"*/venv/*",
419
"*/migrations/*",
420
"*/setup.py",
421
"*/conftest.py"
422
]
423
424
# Concurrency support
425
concurrency = ["thread", "multiprocessing"]
426
427
# Plugins
428
plugins = ["coverage_pth"]
429
430
[tool.coverage.report]
431
# Reporting options
432
show_missing = true
433
skip_covered = false
434
skip_empty = true
435
precision = 2
436
sort = "cover"
437
438
# Exclude lines from coverage
439
exclude_lines = [
440
"pragma: no cover",
441
"def __repr__",
442
"def __str__",
443
"raise AssertionError",
444
"raise NotImplementedError",
445
"if __name__ == .__main__.:",
446
"if TYPE_CHECKING:",
447
"@abstract"
448
]
449
450
# Partial branch exclusion
451
partial_branches = [
452
"pragma: no branch",
453
"if __name__ == .__main__.:"
454
]
455
456
[tool.coverage.html]
457
directory = "htmlcov"
458
title = "My Project Coverage Report"
459
show_contexts = true
460
461
[tool.coverage.xml]
462
output = "reports/coverage.xml"
463
464
[tool.coverage.json]
465
output = "reports/coverage.json"
466
pretty_print = true
467
show_contexts = true
468
469
[tool.coverage.lcov]
470
output = "reports/coverage.lcov"
471
472
# Path mapping for different environments
473
[tool.coverage.paths]
474
source = [
475
"src/",
476
"/home/user/project/src/",
477
"/app/src/",
478
"C:\\Users\\user\\project\\src\\"
479
]
480
```
481
482
This configuration provides comprehensive coverage measurement with multiple output formats, appropriate exclusions, and support for different deployment environments.