How to Use pytest-cov for Test Coverage Reporting
Use
pytest-cov by installing it with pip install pytest-cov and running tests with pytest --cov=your_package. This command measures code coverage and shows a summary report in the terminal.Syntax
The basic syntax to run pytest with coverage is:
pytest --cov=package_name: Runs tests and measures coverage for the specified package.--cov-report=type: Specifies the format of the coverage report (e.g.,term,html,xml).--cov-fail-under=percentage: Fails the test run if coverage is below the given percentage.
bash
pytest --cov=your_package --cov-report=term --cov-fail-under=80Example
This example shows how to run pytest with coverage on a simple package named calculator. It runs tests, shows coverage in the terminal, and creates an HTML report.
python
[calculator.py] def add(a, b): return a + b def subtract(a, b): return a - b [test_calculator.py] from calculator import add, subtract def test_add(): assert add(2, 3) == 5 def test_subtract(): assert subtract(5, 3) == 2 # Run this command in terminal: # pytest --cov=calculator --cov-report=term --cov-report=html
Output
============================= test session starts ==============================
collecting ... collected 2 items
test_calculator.py .. [100%]
---------- coverage: platform linux, python 3.x.x ----------
Name Stmts Miss Cover
----------------------------------
calculator.py 4 0 100%
============================== 2 passed in 0.03s ==============================
# An HTML report is generated in the 'htmlcov' folder.
Common Pitfalls
Common mistakes when using pytest-cov include:
- Not specifying the package/module name with
--cov, which causes no coverage data to be collected. - Running
pytestwithoutpytest-covinstalled, resulting in an unknown option error. - Forgetting to install
pytest-covviapip install pytest-cov. - Expecting coverage on files outside the specified package.
bash
# Wrong: no coverage collected pytest # Right: specify package for coverage pytest --cov=calculator # Wrong: pytest-cov not installed pytest --cov=calculator # Error: unknown option '--cov' # Right: install first pip install pytest-cov pytest --cov=calculator
Quick Reference
| Option | Description |
|---|---|
| --cov=package | Measure coverage for the specified package or module |
| --cov-report=term | Show coverage report in the terminal |
| --cov-report=html | Generate an HTML coverage report in 'htmlcov' folder |
| --cov-fail-under=NUM | Fail tests if coverage is below NUM percent |
| pip install pytest-cov | Install the pytest-cov plugin |
Key Takeaways
Install pytest-cov with pip before using coverage options.
Use --cov=package_name to specify which code to measure.
Add --cov-report=term or --cov-report=html to see coverage results.
Use --cov-fail-under to enforce minimum coverage thresholds.
Run pytest with coverage options to get detailed coverage reports.