Configuration reference
Coverage.py options can be specified in a configuration file. This makes iteasier to re-run coverage.py with consistent settings, and also allows forspecification of options that are otherwise only available in theAPI.
Configuration files also make it easier to get coverage testing of spawnedsubprocesses. SeeManaging processes for more details.
The default name for the configuration file is.coveragerc, in the samedirectory coverage.py is being run in. Most of the settings in theconfiguration file are tied to your source code and how it should be measured,so it should be stored with your source, and checked into source control,rather than put in your home directory.
A different location for the configuration file can be specified with the--rcfile=FILE command line option or with theCOVERAGE_RCFILEenvironment variable.
If.coveragerc doesn’t exist and another file hasn’t been specified, thencoverage.py will look for settings in other common configuration files, in thisorder: setup.cfg, tox.ini, or pyproject.toml. The first file found withcoverage.py settings will be used and other files won’t be consulted.
Coverage.py will read from “pyproject.toml” if TOML support is available,either because you are running on Python 3.11 or later, or because youinstalled with thetoml extra (pipinstallcoverage[toml]).
Syntax
The specific syntax of a configuration file depends on what type it is.All configuration files are assumed to be in INI format, unless their fileextension is .toml, which are TOML.
INI Syntax
A coverage.py configuration file is in classic .ini file format: sections areintroduced by a[section] header, and containname=value entries.Lines beginning with# or; are ignored as comments.
Strings don’t need quotes. Multi-valued strings can be created by indentingvalues on multiple lines.
Boolean values can be specified ason,off,true,false,1,or0 and are case-insensitive.
In setup.cfg or tox.ini, the section names have “coverage:” prefixed, so the[run] options described below will be found in the[coverage:run]section of the file.
TOML Syntax
TOML syntax uses explicit lists with brackets, and strings with quotes.Booleans aretrue orfalse.
Configuration must be within the[tool.coverage] section, for example,[tool.coverage.run]. Environment variable expansion in values isavailable, but only within quoted strings, even for non-string values.
Environment variables
Environment variables can be substituted in by using dollar signs:$WORDor${WORD} will be replaced with the value ofWORD in the environment.A dollar sign can be inserted with$$. Special forms can be used tocontrol what happens if the variable isn’t defined in the environment:
If you want to raise an error if an environment variable is undefined, use aquestion mark suffix:
${WORD?}.If you want to provide a default for missing variables, use a dash with adefault value:
${WORD-defaultvalue}.Otherwise, missing environment variables will result in empty strings with noerror.
Sample file
Here’s a sample configuration file, in each syntax:
- .coveragerc
- pyproject.toml
- setup.cfg or tox.ini
[run]branch=True[report]; Regexes for lines to exclude from considerationexclude_also=; Don't complain about missing debug-only code:def __repr__if self\.debug; Don't complain if tests don't hit defensive assertion code:raise AssertionErrorraise NotImplementedError; Don't complain if non-runnable code isn't run:if 0:if __name__== .__main__.:; Don't complain about abstract methods, they aren't run:@(abc\.)?abstractmethodignore_errors=True[html]directory=coverage_html_report
[tool.coverage.run]branch=true[tool.coverage.report]# Regexes for lines to exclude from considerationexclude_also=[# Don't complain about missing debug-only code:"def __repr__","if self\\.debug",# Don't complain if tests don't hit defensive assertion code:"raise AssertionError","raise NotImplementedError",# Don't complain if non-runnable code isn't run:"if 0:","if __name__ == .__main__.:",# Don't complain about abstract methods, they aren't run:"@(abc\\.)?abstractmethod",]ignore_errors=true[tool.coverage.html]directory="coverage_html_report"
[coverage:run]branch=True[coverage:report]; Regexes for lines to exclude from considerationexclude_also=; Don't complain about missing debug-only code:def __repr__if self\.debug; Don't complain if tests don't hit defensive assertion code:raise AssertionErrorraise NotImplementedError; Don't complain if non-runnable code isn't run:if 0:if __name__== .__main__.:; Don't complain about abstract methods, they aren't run:@(abc\.)?abstractmethodignore_errors=True[coverage:html]directory=coverage_html_report
The specific configuration settings are described below. Many sections andsettings correspond roughly to commands and options in thecommand-lineinterface.
[run]
These settings are generally used when running product code, though some applyto more than one command.
[run] branch
(boolean, default False) Whether to measurebranch coverage inaddition to statement coverage.
[run] command_line
(string) The command-line to run your program. This will be used if you runcoveragerun with no further arguments. Coverage.py options cannot bespecified here, other than-m to indicate the module to run.
Added in version 5.0.
[run] concurrency
(multi-string, default “thread”) The concurrency libraries in use by theproduct code. If your program usesmultiprocessing,gevent,greenlet,oreventlet, you must name that library in this option, or coverage.py willproduce very wrong results.
SeeManaging processes for details of multi-process measurement.
Before version 4.2, this option only accepted a single string.
Added in version 4.0.
[run] context
(string) The static context to record for this coverage run. SeeMeasurement contexts for more information
Added in version 5.0.
[run] core
(string, default depends on the Python version) Specify which measurement coreto use. Valid values are:
ctrace: the C implementation of a sys.settrace function. This was thedefault until Python 3.13.sysmon: thesys.monitoringimplementation.Only available in Python 3.12+, and the default in Python 3.14+. The sysmoncore does not yet support plugins, dynamic contexts, or some concurrencylibraries. In Python 3.12 and 3.13, it does not support branch coverage.pytrace: the pure Python implementation of a sys.settrace function.
This setting was previously only available as the COVERAGE_CORE environmentvariable.
Added in version 7.9.
[run] cover_pylib
(boolean, default False) Whether to measure the Python standard library.
[run] data_file
(string, default “.coverage”) The name of the data file to use for storing orreporting coverage. This value can include a path to another directory.
[run] disable_warnings
(multi-string) A list of warnings to disable. Warnings that can be disabledinclude a short string at the end, the name of the warning. SeeWarnings for specific warnings.
[run] debug
(multi-string) A list of debug options. Seethe run –debug option for details.
[run] debug_file
(string) A file name to write debug output to. Seethe run –debugoption for details.
[run] dynamic_context
(string) The name of a strategy for setting the dynamic context duringexecution. SeeDynamic contexts for details.
[run] include
(multi-string) A list of file name patterns, the files to include inmeasurement or reporting. Ignored ifsource is set. SeeSpecifying source files fordetails.
[run] omit
(multi-string) A list of file name patterns, the files to leave out ofmeasurement or reporting. SeeSpecifying source files for details.
[run] parallel
(boolean, default False) Append the machine name, process id and random numberto the data file name to simplify collecting data from many processes. SeeCombining data files: coverage combine for more information.
[run] patch
(multi-string) A list of patch names that coverage can apply to the runtimeenvironment to improve coverage measurement. The available patches correspondto Python features that could interfere with coverage. The patch insertscoverage-specific code to collect the correct data.
These must be requested in the configuration instead of being appliedautomatically because they could be invasive and produce undesirableside-effects.
Available patches:
execv: Theexecvfamily of functions end thecurrent program without giving coverage a chance to write collected data.This patch adjusts those functions to save the data before starting the nextexecutable. Not available on Windows._exit: Theos._exit()function exits theprocess immediately without calling cleanup handlers. This patch savescoverage data before exiting.fork: Forking a process normally continues measuring coverage properly.This patch stops the previous coverage and starts a new one in the childprocess for those times when the default handling isn’t enough.subprocess: Python sub-processes normally won’t get coverage measurement.This patch configures Python to start coverage automatically, and will applyto processes created withsubprocess,os.system(), or one of theexecvorspawnvfamilyof functions. If anexec*eorspawn*efunction is used, the newenvironment must copy over theCOVERAGE_PROCESS_STARTenvironmentvariable.The
subprocesspatch setsparallel = Trueand will require combining data files before reporting. SeeCombining data files: coverage combine for more details.
Added in version 7.10.
[run] plugins
(multi-string) A list of plugin package names. SeePlug-ins for moreinformation.
[run] relative_files
(boolean, default False) store relative file paths in the data file. Thismakes it easier to measure code in one (or multiple) environments, and thenreport in another. SeeCombining data files: coverage combine for details.
Note that settingsource has to be done in the configuration file ratherthan the command line for this option to work, since the reporting commandsneed to know the source origin.
Added in version 5.0.
[run] sigterm
(boolean, default False) if true, register a SIGTERM signal handler to capturedata when the process ends due to a SIGTERM signal. This includesProcess.terminate and otherways to terminate a process. This can help when collecting data in usualsituations, but can also introduce problems (seeissue 1310).
The signal handler is only registered on Linux and Mac. On Windows, thissetting has no effect.
Added in version 6.4:(in 6.3 this was always enabled)
[run] source
(multi-string) A list of packages or directories, the source to measure duringexecution. If set,include is ignored. SeeSpecifying source files for details.
[run] source_pkgs
(multi-string) A list of packages, the source to measure during execution.Operates the same assource, but only names packages, for resolvingambiguities between packages and directories.
Added in version 5.3.
[run] source_dirs
(multi-string) A list of directories, the source to measure during execution.Operates the same assource, but only names directories, for resolvingambiguities between packages and directories.
Added in version 7.8.
[run] timid
(boolean, default False) Use a simpler but slower trace method. This uses thePyTracer trace function core instead of CTracer, and is only needed in veryunusual circumstances.
[paths]
The entries in this section are lists of file paths that should be consideredequivalent when combining data from different machines:
- .coveragerc
- pyproject.toml
- setup.cfg or tox.ini
[paths]source=src//jenkins/build/*/srcc:\myproj\src
[tool.coverage.paths]source=["src/","/jenkins/build/*/src","c:\\myproj\\src",]
[coverage:paths]source=src//jenkins/build/*/srcc:\myproj\src
The names of the entries (“source” in this example) are ignored, you may chooseany name that you like. The value is a list of strings. When combining datawith thecombine command, two file paths will be combined if they startwith paths from the same list.
The first value must be an actual file path on the machine where the reportingwill happen, so that source code can be found. The other values can be filepatterns to match against the paths of collected data, or they can be absoluteor relative file paths on the current machine.
In this example, data collected for “/jenkins/build/1234/src/module.py” will becombined with data for “c:\myproj\src\module.py”, and will be reportedagainst the source file found at “src/module.py”.
If you specify more than one list of paths, they will be considered in order.A file path will only be remapped if the result exists. If a path matches alist, but the result doesn’t exist, the next list will be tried. The firstlist that has an existing result will be used.
Remapping will also be done during reporting, but only within the single datafile being reported. Combining multiple files requires thecombinecommand.
The--debug=pathmap option can be used to log details of the re-mapping ofpaths. Seethe –debug option.
SeeRe-mapping paths andFile patterns for more information.
[report]
Settings common to many kinds of reporting.
[report] exclude_also
(multi-string) A list of regular expressions. This setting is similar to[report] exclude_lines: it specifies patterns for lines to excludefrom reporting. This setting is preferred, because it will preserve thedefault exclude patterns likepragma:nocover instead of overwriting them.
See[report] exclude_lines for further details.
Added in version 7.2.0.
[report] exclude_lines
(multi-string) A list of regular expressions. Any line of your source codecontaining a match for one of these regexes is excluded from being reported asmissing. More details are inExcluding code from coverage.py. If you use this option, youare replacing all the exclude regexes, so you’ll need to also supply the“pragma: no cover” regex if you still want to use it. The[report] exclude_also setting can be used to specify patternswithout overwriting the default set.
You can exclude lines introducing blocks, and the entire block is excluded. Ifyou exclude adef line or decorator line, the entire function is excluded.
Be careful when writing this setting: the values are regular expressions thatonly have to match a portion of the line. For example, if you write...,you’ll exclude any line with three or more of any character. If you writepass, you’ll also exclude the linemy_pass="foo", and so on.
All of the regexes here and in[report] exclude_also are combinedinto one regex for processing, so you cannot use global flags like(?s) inyour regexes. Use the scoped flag form instead:(?s:...)
[report] fail_under
(float) A target coverage percentage. If the total coverage measurement isunder this value, then exit with a status code of 2. If you specify anon-integral value, you must also set[report]precision properly to makeuse of the decimal places. A setting of 100 will fail any value under 100,regardless of the number of decimal places of precision.
[report] format
(string, default “text”) The format to use for the textual report. The defaultis “text” which produces a simple textual table. You can use “markdown” toproduce a Markdown table, or “total” to output only the total coveragepercentage.
Added in version 7.0.
[report] ignore_errors
(boolean, default False) Ignore source code that can’t be found, emitting awarning instead of an exception.
[report] include
(multi-string) A list of file name patterns, the files to include in reporting.SeeSpecifying source files for details.
[report] include_namespace_packages
(boolean, default False) When searching for completely un-executed files,include directories without__init__.py files. These areimplicitnamespace packages, and are usually skipped.
Added in version 7.0.
[report] omit
(multi-string) A list of file name patterns, the files to leave out ofreporting. SeeSpecifying source files for details.
[report] partial_also
(multi-string) A list of regular expressions. This setting is similar to[report] partial_branches: it specifies patterns for branches toconsider fully covered even if they don’t exercise both destinations. Thissetting is preferred, because it will preserve the default exclude patternslikepragma:nobranch instead of overwriting them.
See[report] partial_branches for further details.
Added in version 7.10.0.
[report] partial_branches
(multi-string) A list of regular expressions. Any line of code that matchesone of these regexes is excused from being reported as a partial branch. Moredetails are inBranch coverage measurement. If you use this option, you are replacing allthe partial branch regexes so you’ll need to also supply the “pragma: nobranch” regex if you still want to use it. The[report] partial_also setting can be used to specify patternswithout overwriting the default set.
[report] precision
(integer) The number of digits after the decimal point to display for reportedcoverage percentages. The default is 0, displaying for example “87%”. A valueof 2 will display percentages like “87.32%”. This setting also affects theinterpretation of thefail_under setting.
[report] show_missing
(boolean, default False) When running a summary report, show missing lines.SeeCoverage summary: coverage report for more information.
[report] skip_covered
(boolean, default False) Don’t report files that are 100% covered. This helpsyou focus on files that need attention.
[report] skip_empty
(boolean, default False) Don’t report files that have no executable code (suchas__init__.py files).
[report] sort
(string, default “Name”) Sort the text report by the named column. Allowedvalues are “Name”, “Stmts”, “Miss”, “Branch”, “BrPart”, or “Cover”. Prefixwith- for descending sort (for example, “-cover”).
[html]
Settings particular to HTML reporting. The settings in the[report]section also apply to HTML output, where appropriate.
[html] directory
(string, default “htmlcov”) Where to write the HTML report files.
[html] extra_css
(string) The path to a file of CSS to apply to the HTML report. The file willbe copied into the HTML output directory. Don’t name it “style.css”. This CSSis in addition to the CSS normally used, though you can overwrite as many ofthe rules as you like.
[html] show_contexts
(boolean) Should the HTML report include an indication on each line of whichcontexts executed the line. SeeDynamic contexts for details.
[html] skip_covered
(boolean, defaulted from[report]skip_covered) Don’t include files in thereport that are 100% covered files. SeeCoverage summary: coverage report for more information.
Added in version 5.4.
[html] skip_empty
(boolean, defaulted from[report]skip_empty) Don’t include empty files(those that have 0 statements) in the report. SeeCoverage summary: coverage report for moreinformation.
Added in version 5.4.
[html] title
(string, default “Coverage report”) The title to use for the report.Note this is text, not HTML.
[xml]
Settings particular to XML reporting. The settings in the[report] sectionalso apply to XML output, where appropriate.
[xml] output
(string, default “coverage.xml”) Where to write the XML report.
[xml] package_depth
(integer, default 99) Controls which directories are identified as packages inthe report. Directories deeper than this depth are not reported as packages.The default is that all directories are reported as packages.
[json]
Settings particular to JSON reporting. The settings in the[report]section also apply to JSON output, where appropriate.
Added in version 5.0.
[json] output
(string, default “coverage.json”) Where to write the JSON file.
[json] pretty_print
(boolean, default false) Controls if the JSON is outputted with white spaceformatted for human consumption (True) or for minimum file size (False).
[json] show_contexts
(boolean, default false) Should the JSON report include an indication of whichcontexts executed each line. SeeDynamic contexts for details.
[lcov]
Settings particular to LCOV reporting (seeLCOV reporting: coverage lcov).
Added in version 6.3.
[lcov] output
(string, default “coverage.lcov”) Where to write the LCOV file.
[lcov] line_checksums
(boolean, default false) Whether to write per-line checksums as part of thelcov file. Because these checksums cover only lines with actual code onthem, and do not verify the ordering of lines, they provide only a weakassurance that the source code available to analysis tools (e.g.genhtml)matches the code that was used to generate the coverage data.
Added in version 7.6.2.