LinuxCommandLibrary

coverage

TLDR

Run a Python script with coverage

$ coverage run [script.py]
copy
Run pytest with coverage
$ coverage run -m pytest
copy
Show coverage report in terminal
$ coverage report
copy
Generate HTML coverage report
$ coverage html
copy
Show only files with less than 80% coverage
$ coverage report --fail-under=80
copy
Combine coverage from multiple runs
$ coverage combine
copy
Erase collected coverage data
$ coverage erase
copy
Show coverage for specific file
$ coverage report --include=[path/to/file.py]
copy

SYNOPSIS

coverage command [options] [args]

DESCRIPTION

Coverage.py measures code coverage for Python programs, showing which lines and branches are executed during testing. It helps identify untested code paths and ensures comprehensive test suites.
The tool instruments Python bytecode to track execution. After running tests with coverage run, reports show percentage of lines covered per file. HTML reports provide visual highlighting of covered and uncovered lines.
Branch coverage (--branch) additionally tracks which conditional branches are taken, catching cases where both sides of an if statement aren't tested.

PARAMETERS

run [options] program

Run a program and collect coverage data.
report
Display coverage report in terminal.
html
Generate HTML report in htmlcov/.
xml
Generate Cobertura XML report.
json
Generate JSON report.
combine
Combine data from multiple coverage files.
erase
Delete collected coverage data.
-m module
Run library module as script (like python -m).
--source paths
Limit coverage to specified packages/directories.
--include patterns
Include only files matching patterns.
--omit patterns
Omit files matching patterns.
--branch
Enable branch coverage measurement.
--fail-under n
Exit with failure if coverage is below n%.

CONFIGURATION

Settings in pyproject.toml, setup.cfg, or .coveragerc:

$ [coverage:run]
source = mypackage
branch = True

[coverage:report]
fail_under = 80
copy

CAVEATS

Coverage measurement adds runtime overhead. Dynamic code generation and exec() may not be tracked correctly. 100% line coverage doesn't guarantee bug-free code. Branch coverage is more thorough but harder to achieve. Multiprocessing requires special configuration.

HISTORY

Coverage.py was created by Ned Batchelder and first released in 2004. It has become the standard code coverage tool for Python, integrated with test runners like pytest and unittest. The tool is widely used in CI/CD pipelines and is supported by coverage reporting services like Codecov and Coveralls.

SEE ALSO

Copied to clipboard