The Coverage class

class coverage.Coverage(data_file: Optional[Union[str, DefaultValue]] = MISSING, data_suffix: Optional[Union[str, bool]] = None, cover_pylib: Optional[bool] = None, auto_data: bool = False, timid: Optional[bool] = None, branch: Optional[bool] = None, config_file: Union[str, bool] = True, source: Optional[Iterable[str]] = None, source_pkgs: Optional[Iterable[str]] = None, omit: Optional[Union[str, Iterable[str]]] = None, include: Optional[Union[str, Iterable[str]]] = None, debug: Optional[Iterable[str]] = None, concurrency: Optional[Union[str, Iterable[str]]] = None, check_preimported: bool = False, context: Optional[str] = None, messages: bool = False)

Programmatic access to coverage.py.

To use:

from coverage import Coverage

cov = Coverage()
cov.start()
#.. call your code ..
cov.stop()
cov.html_report(directory='covhtml')

Note: in keeping with Python custom, names starting with underscore are not part of the public API. They might stop working at any point. Please limit yourself to documented methods to avoid problems.

Methods can raise any of the exceptions described in Coverage exceptions.

__init__(data_file: Optional[Union[str, DefaultValue]] = MISSING, data_suffix: Optional[Union[str, bool]] = None, cover_pylib: Optional[bool] = None, auto_data: bool = False, timid: Optional[bool] = None, branch: Optional[bool] = None, config_file: Union[str, bool] = True, source: Optional[Iterable[str]] = None, source_pkgs: Optional[Iterable[str]] = None, omit: Optional[Union[str, Iterable[str]]] = None, include: Optional[Union[str, Iterable[str]]] = None, debug: Optional[Iterable[str]] = None, concurrency: Optional[Union[str, Iterable[str]]] = None, check_preimported: bool = False, context: Optional[str] = None, messages: bool = False) None

Many of these arguments duplicate and override values that can be provided in a configuration file. Parameters that are missing here will use values from the config file.

data_file is the base name of the data file to use. The config value defaults to “.coverage”. None can be provided to prevent writing a data file. data_suffix is appended (with a dot) to data_file to create the final file name. If data_suffix is simply True, then a suffix is created with the machine and process identity included.

cover_pylib is a boolean determining whether Python code installed with the Python interpreter is measured. This includes the Python standard library and any packages installed with the interpreter.

If auto_data is true, then any existing data file will be read when coverage measurement starts, and data will be saved automatically when measurement stops.

If timid is true, then a slower and simpler trace function will be used. This is important for some environments where manipulation of tracing functions breaks the faster trace function.

If branch is true, then branch coverage will be measured in addition to 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 the file 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 for these 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 located in the trees indicated by the file paths or package names will be measured.

source_pkgs is a list of package names. It works the same as source, but can be used to name packages where the name can also be interpreted as a file path.

include and omit are lists of file name patterns. Files that match include will be measured, files that match omit will not. Each will also accept a single string argument.

debug is a list of strings indicating what debugging information is desired.

concurrency is a string indicating the concurrency library being used in the measured code. Without this, coverage.py will get incorrect results 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.

If check_preimported is true, then when coverage is started, the already-imported files will be checked to see if they should be measured by coverage. Importing measured files before coverage is started can mean that code is missed.

context is a string to use as the static context label for collected data.

If messages is true, some messages will be printed to stdout indicating what is happening.

New in version 4.0: The concurrency parameter.

New in version 4.2: The concurrency parameter can now be a list of strings.

New in version 5.0: The check_preimported and context parameters.

New in version 5.3: The source_pkgs parameter.

New in version 6.0: The messages parameter.

analysis(morf: Union[module, str]) Tuple[str, List[int], List[int], str]

Like analysis2 but doesn’t return excluded line numbers.

analysis2(morf: Union[module, str]) Tuple[str, List[int], List[int], List[int], str]

Analyze a module.

morf is a module or a file name. It will be analyzed to determine its 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 from execution).

  • A readable formatted string of the missing line numbers.

The analysis uses the source file itself and the current measured coverage data.

annotate(morfs: Optional[Iterable[Union[module, str]]] = None, directory: Optional[str] = None, ignore_errors: Optional[bool] = None, omit: Optional[Union[str, List[str]]] = None, include: Optional[Union[str, List[str]]] = None, contexts: Optional[List[str]] = None) None

Annotate a list of modules.

Note

This method has been obsoleted by more modern reporting tools, including the html_report() method. It will be removed in a future version.

Each module in morfs is annotated. The source is written to a new file, named with a “,cover” suffix, with each line prefixed with a marker 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: str = 'exclude') None

Clear the exclude list.

combine(data_paths: Optional[Iterable[str]] = None, strict: bool = False, keep: bool = False) None

Combine together a number of similarly-named coverage data files.

All coverage data files whose name starts with data_file (from the coverage() constructor) will be read, and combined together into the current measurements.

data_paths is a list of files or directories from which data should be combined. If no list is passed, then the data files from the directory indicated by the current data file (probably the current directory) will be combined.

If strict is true, then it is an error to attempt to combine when there are no data files to combine.

If keep is true, then original input data files won’t be deleted.

New in version 4.0: The data_paths parameter.

New in version 4.3: The strict parameter.

classmethod current() Optional[Coverage]

Get the latest started Coverage instance, if any.

Returns: a Coverage instance, or None.

New in version 5.0.

erase() None

Erase previously collected coverage data.

This removes the in-memory data collected in this session as well as discarding the data file.

exclude(regex: str, which: str = 'exclude') None

Exclude source lines from execution consideration.

A number of lists of regular expressions are maintained. Each list selects lines that are treated differently during reporting.

which determines which list is modified. The “exclude” list selects lines that are not considered executable at all. The “partial” list indicates lines with branches that are not taken.

regex is a regular expression. The regex is added to the specified list. If any of the regexes in the list is found in a line, the line is marked for special treatment during reporting.

get_data() CoverageData

Get the collected data.

Also warn about various problems collecting data.

Returns a coverage.CoverageData, the collected coverage data.

New in version 4.0.

get_exclude_list(which: str = 'exclude') List[str]

Return a list of excluded regex strings.

which indicates which list is desired. See exclude() for the lists that are available, and their meaning.

get_option(option_name: str) Optional[Union[bool, int, float, str, List[str]]]

Get an option from the configuration.

option_name is a colon-separated string indicating the section and option 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. The type depends on the option selected.

As a special case, an option_name of "paths" will return an dictionary with the entire [paths] section value.

New in version 4.0.

html_report(morfs: Optional[Iterable[Union[module, str]]] = None, directory: Optional[str] = None, ignore_errors: Optional[bool] = None, omit: Optional[Union[str, List[str]]] = None, include: Optional[Union[str, List[str]]] = None, extra_css: Optional[str] = None, title: Optional[str] = None, skip_covered: Optional[bool] = None, show_contexts: Optional[bool] = None, contexts: Optional[List[str]] = None, skip_empty: Optional[bool] = None, precision: Optional[int] = None) float

Generate an HTML report.

The HTML is written to directory. The file “index.html” is the overview starting point, with links to more detailed pages for individual 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 HTML report.

See report() for other arguments.

Returns a float, the total percentage covered.

Note

The HTML report files are generated incrementally based on the source files and coverage results. If you modify the report files, the changes will not be considered. You should be careful about changing the files in the report folder.

json_report(morfs: Optional[Iterable[Union[module, str]]] = None, outfile: Optional[str] = None, ignore_errors: Optional[bool] = None, omit: Optional[Union[str, List[str]]] = None, include: Optional[Union[str, List[str]]] = None, contexts: Optional[List[str]] = None, pretty_print: Optional[bool] = None, show_contexts: Optional[bool] = None) float

Generate a JSON report of coverage results.

Each module in morfs is included in the report. outfile is the path to write the file to, “-” will write to stdout.

pretty_print is a boolean, whether to pretty-print the JSON output or not.

See report() for other arguments.

Returns a float, the total percentage covered.

New in version 5.0.

lcov_report(morfs: Optional[Iterable[Union[module, str]]] = None, outfile: Optional[str] = None, ignore_errors: Optional[bool] = None, omit: Optional[Union[str, List[str]]] = None, include: Optional[Union[str, List[str]]] = None, contexts: Optional[List[str]] = None) float

Generate an LCOV report of coverage results.

Each module in ‘morfs’ is included in the report. ‘outfile’ is the path to write the file to, “-” will write to stdout.

See :meth ‘report’ for other arguments.

New in version 6.3.

load() None

Load previously-collected coverage data from the data file.

report(morfs: Optional[Iterable[Union[module, str]]] = None, show_missing: Optional[bool] = None, ignore_errors: Optional[bool] = None, file: Optional[IO[str]] = None, omit: Optional[Union[str, List[str]]] = None, include: Optional[Union[str, List[str]]] = None, skip_covered: Optional[bool] = None, contexts: Optional[List[str]] = None, skip_empty: Optional[bool] = None, precision: Optional[int] = None, sort: Optional[str] = None, output_format: Optional[str] = None) float

Write a textual summary report to file.

Each module in morfs is listed, with counts of statements, executed statements, missing statements, and a list of lines missed.

If show_missing is true, then details of which lines or branches are missing will be included in the report. If ignore_errors is true, then a failure while reporting a single file will not stop the entire report.

file is a file-like object, suitable for writing.

output_format determines the format, either “text” (the default), “markdown”, or “total”.

include is a list of file name patterns. Files that match will be included in the report. Files matching omit will not be included in the report.

If skip_covered is true, don’t report on files with 100% coverage.

If skip_empty is true, don’t report on empty files (those that have no statements).

contexts is a list of regular expression strings. Only data from dynamic contexts that match one of those expressions (using re.search) will be included in the report.

precision is the number of digits to display after the decimal point for percentages.

All of the arguments default to the settings read from the configuration file.

Returns a float, the total percentage covered.

New in version 4.0: The skip_covered parameter.

New in version 5.0: The contexts and skip_empty parameters.

New in version 5.2: The precision parameter.

New in version 7.0: The format parameter.

save() None

Save the collected coverage data to the data file.

set_option(option_name: str, value: Union[bool, int, float, str, Iterable[str], None, Mapping[str, Optional[Union[bool, int, float, str, Iterable[str]]]]]) None

Set an option in the configuration.

option_name is a colon-separated string indicating the section and option 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 an appropriate Python value. For example, use True for booleans, not the string "True".

As an example, calling:

cov.set_option("run:branch", True)

has the same effect as this configuration file:

[run]
branch = True

As a special case, an option_name of "paths" will replace the entire [paths] section. The value should be a dictionary.

New in version 4.0.

start() None

Start measuring code coverage.

Coverage measurement only occurs in functions called after start() is invoked. Statements in the same scope as start() won’t be measured.

Once you invoke start(), you must also call stop() eventually, or your process might not shut down cleanly.

stop() None

Stop measuring code coverage.

switch_context(new_context: str) None

Switch to a new dynamic context.

new_context is a string to use as the dynamic context label for collected data. If a static context is in use, the static and dynamic context labels will be joined together with a pipe character.

Coverage collection must be started already.

New in version 5.0.

xml_report(morfs: Optional[Iterable[Union[module, str]]] = None, outfile: Optional[str] = None, ignore_errors: Optional[bool] = None, omit: Optional[Union[str, List[str]]] = None, include: Optional[Union[str, List[str]]] = None, contexts: Optional[List[str]] = None, skip_empty: Optional[bool] = None) float

Generate an XML report of coverage results.

The report is compatible with Cobertura reports.

Each module in morfs is included in the report. outfile is the path to write the file to, “-” will write to stdout.

See report() for other arguments.

Returns a float, the total percentage covered.