What is Coverage.py
Coverage.py is a powerful tool for analyzing code coverage in Python, helping developers identify which parts of their code are executed during testing and which remain unused. This tool is an essential part of the code quality assurance process and helps uncover potential gaps in test coverage.
The main goal of Coverage.py is to provide detailed insights into how thoroughly your tests cover your codebase. It analyzes program execution and generates reports showing coverage percentages for each file, module, or even individual lines of code.
Key Features of Coverage.py
Coverage.py offers a wide range of features for code coverage analysis:
Line coverage measurement — the core feature that tracks which lines of code were executed during testing.
Branch analysis — an advanced feature that checks whether all possible execution paths in conditional statements (if, elif, else) were tested.
Report generation — create detailed reports in various formats: text, HTML, XML, JSON.
Framework integration — seamless compatibility with popular testing frameworks like pytest, unittest, and nose.
Exclusion settings — ability to exclude specific files, folders, or lines from coverage analysis.
Installation and Initial Setup
Standard Installation
Install Coverage.py using pip:
pip install coverage
Installation with Extra Features
If you're using pytest, it's recommended to install the pytest-cov plugin:
pip install pytest-cov
For working with TOML configuration files:
pip install coverage[toml]
Verify Installation
After installation, make sure Coverage.py is working correctly:
coverage --version
Basic Commands and Usage
Running Coverage Analysis
Basic coverage analysis for a Python script:
coverage run my_script.py
Run with additional options:
coverage run --source=my_package my_script.py
Running with unittest
coverage run -m unittest discover
Running with pytest
coverage run -m pytest
Or using pytest-cov:
pytest --cov=my_module tests/
Viewing Coverage Reports
Terminal Text Report
coverage report
Example output:
Name Stmts Miss Cover
----------------------------------------
my_module.py 25 3 88%
utils.py 15 0 100%
main.py 20 5 75%
----------------------------------------
TOTAL 60 8 87%
Detailed Report with Missing Lines
coverage report --show-missing
HTML Report
coverage html
After running the command, open htmlcov/index.html in your browser to view the interactive report.
XML Report for CI/CD
coverage xml
JSON Report
coverage json
Managing Coverage Data
Clearing Data
Also in library
Recommendations