The Coverage class¶
- class
coverage.
Coverage
(data_file=None,data_suffix=None,cover_pylib=None,auto_data=False,timid=None,branch=None,config_file=True,source=None,omit=None,include=None,debug=None,concurrency=None)¶ Programmatic access to coverage.py.
To use:
fromcoverageimportCoveragecov=Coverage()cov.start()#.. call your code ..cov.stop()cov.html_report(directory='covhtml')
__init__
(data_file=None,data_suffix=None,cover_pylib=None,auto_data=False,timid=None,branch=None,config_file=True,source=None,omit=None,include=None,debug=None,concurrency=None)¶data_file is the base name of the data file to use, defaulting to”.coverage”.data_suffix is appended (with a dot) todata_file tocreate the final file name. Ifdata_suffix is simply True, then asuffix is created with the machine and process identity included.
cover_pylib is a boolean determining whether Python code installedwith the Python interpreter is measured. This includes the Pythonstandard library and any packages installed with the interpreter.
Ifauto_data is true, then any existing data file will be read whencoverage measurement starts, and data will be saved automatically whenmeasurement stops.
Iftimid is true, then a slower and simpler trace function will beused. This is important for some environments where manipulation oftracing functions breaks the faster trace function.
Ifbranch is true, then branch coverage will be measured in additionto the usual statement coverage.
config_file determines what configuration file to read:
- If it is ”.coveragerc”, it is interpreted as if it were True,for backward compatibility.
- If it is a string, it is the name of the file to read. If thefile can’t be read, it is an error.
- If it is True, then a few standard files names are tried(”.coveragerc”, “setup.cfg”, “tox.ini”). It is not an error forthese files to not be found.
- If it is False, then no configuration file is read.
source is a list of file paths or package names. Only code locatedin the trees indicated by the file paths or package names will bemeasured.
include andomit are lists of file name patterns. Files that matchinclude will be measured, files that matchomit will not. Eachwill also accept a single string argument.
debug is a list of strings indicating what debugging information isdesired.
concurrency is a string indicating the concurrency library being usedin the measured code. Without this, coverage.py will get incorrectresults if these libraries are in use. Valid strings are “greenlet”,“eventlet”, “gevent”, “multiprocessing”, or “thread” (the default).This can also be a list of these strings.
New in version 4.0:Theconcurrency parameter.
New in version 4.2:Theconcurrency parameter can now be a list of strings.
analysis
(morf)¶Likeanalysis2 but doesn’t return excluded line numbers.
analysis2
(morf)¶Analyze a module.
morf is a module or a file name. It will be analyzed to determineits coverage statistics. The return value is a 5-tuple:
- The file name for the module.
- A list of line numbers of executable statements.
- A list of line numbers of excluded statements.
- A list of line numbers of statements not run (missing fromexecution).
- A readable formatted string of the missing line numbers.
The analysis uses the source file itself and the current measuredcoverage data.
annotate
(morfs=None,directory=None,ignore_errors=None,omit=None,include=None)¶Annotate a list of modules.
Each module inmorfs is annotated. The source is written to a newfile, named with a ”,cover” suffix, with each line prefixed with amarker to indicate the coverage of the line. Covered lines have “>”,excluded lines have “-”, and missing lines have ”!”.
See
report()
for other arguments.
clear_exclude
(which='exclude')¶Clear the exclude list.
combine
(data_paths=None,strict=False)¶Combine together a number of similarly-named coverage data files.
All coverage data files whose name starts withdata_file (from thecoverage() constructor) will be read, and combined together into thecurrent measurements.
data_paths is a list of files or directories from which data shouldbe combined. If no list is passed, then the data files from thedirectory indicated by the current data file (probably the currentdirectory) will be combined.
Ifstrict is true, then it is an error to attempt to combine whenthere are no data files to combine.
New in version 4.0:Thedata_paths parameter.
New in version 4.3:Thestrict parameter.
erase
()¶Erase previously-collected coverage data.
This removes the in-memory data collected in this session as well asdiscarding the data file.
exclude
(regex,which='exclude')¶Exclude source lines from execution consideration.
A number of lists of regular expressions are maintained. Each listselects lines that are treated differently during reporting.
which determines which list is modified. The “exclude” list selectslines that are not considered executable at all. The “partial” listindicates lines with branches that are not taken.
regex is a regular expression. The regex is added to the specifiedlist. If any of the regexes in the list is found in a line, the lineis marked for special treatment during reporting.
get_data
()¶Get the collected data and reset the collector.
Also warn about various problems collecting data.
Returns a
coverage.CoverageData
, the collected coverage data.New in version 4.0.
get_exclude_list
(which='exclude')¶Return a list of excluded regex patterns.
which indicates which list is desired. See
exclude()
for thelists that are available, and their meaning.
get_option
(option_name)¶Get an option from the configuration.
option_name is a colon-separated string indicating the section andoption name. For example, the
branch
option in the[run]
section of the config file would be indicated with“run:branch”.Returns the value of the option.
New in version 4.0.
html_report
(morfs=None,directory=None,ignore_errors=None,omit=None,include=None,extra_css=None,title=None,skip_covered=None)¶Generate an HTML report.
The HTML is written todirectory. The file “index.html” is theoverview starting point, with links to more detailed pages forindividual modules.
extra_css is a path to a file of other CSS to apply on the page.It will be copied into the HTML directory.
title is a text string (not HTML) to use as the title of the HTMLreport.
See
report()
for other arguments.Returns a float, the total percentage covered.
load
()¶Load previously-collected coverage data from the data file.
report
(morfs=None,show_missing=None,ignore_errors=None,file=None,omit=None,include=None,skip_covered=None)¶Write a summary report tofile.
Each module inmorfs is listed, with counts of statements, executedstatements, missing statements, and a list of lines missed.
include is a list of file name patterns. Files that match will beincluded in the report. Files matchingomit will not be included inthe report.
Ifskip_covered is True, don’t report on files with 100% coverage.
Returns a float, the total percentage covered.
save
()¶Save the collected coverage data to the data file.
set_option
(option_name,value)¶Set an option in the configuration.
option_name is a colon-separated string indicating the section andoption name. For example, the
branch
option in the[run]
section of the config file would be indicated with"run:branch"
.value is the new value for the option. This should be a Pythonvalue where appropriate. For example, use True for booleans, not thestring
"True"
.As an example, calling:
cov.set_option("run:branch",True)
has the same effect as this configuration file:
[run]branch=True
New in version 4.0.
start
()¶Start measuring code coverage.
Coverage measurement only occurs in functions called after
start()
is invoked. Statements in the same scope asstart()
won’t be measured.Once you invoke
start()
, you must also callstop()
eventually, or your process might not shut down cleanly.
stop
()¶Stop measuring code coverage.
xml_report
(morfs=None,outfile=None,ignore_errors=None,omit=None,include=None)¶Generate an XML report of coverage results.
The report is compatible with Cobertura reports.
Each module inmorfs is included in the report.outfile is thepath to write the file to, “-” will write to stdout.
See
report()
for other arguments.Returns a float, the total percentage covered.
Starting coverage.py automatically¶
This function is used to start coverage measurement automatically when Pythonstarts. SeeMeasuring sub-processes for details.
coverage.
process_startup
()¶Call this at Python start-up to perhaps measure coverage.
If the environment variable COVERAGE_PROCESS_START is defined, coveragemeasurement is started. The value of the variable is the config fileto use.
There are two ways to configure your Python installation to invoke thisfunction when Python starts:
Create or append to sitecustomize.py to add these lines:
importcoveragecoverage.process_startup()
Create a .pth file in your Python installation containing:
importcoverage;coverage.process_startup()
Returns the
Coverage
instance that was started, or None if it wasnot started by this call.