How to Generate Coverage Report with pytest
To generate a coverage report with
pytest, install the pytest-cov plugin and run pytest --cov=your_package. Add --cov-report=term or --cov-report=html to see coverage in the terminal or as an HTML report.Syntax
Use the pytest command with the --cov option to specify the package or module to measure coverage. Add --cov-report to choose the report format.
--cov=PATH: Path to the code to measure coverage.--cov-report=term: Show coverage summary in the terminal.--cov-report=html: Generate an HTML report in ahtmlcovfolder.
bash
pytest --cov=your_package --cov-report=term pytest --cov=your_package --cov-report=html
Example
This example shows how to run pytest with coverage on a sample package named myapp. It runs tests and prints a coverage summary in the terminal and also creates an HTML report.
python
[test_sample.py] def add(a, b): return a + b def test_add(): assert add(2, 3) == 5 # Run this command in terminal: # pytest --cov=myapp --cov-report=term --cov-report=html
Output
============================= test session starts =============================
collecting ... collected 1 item
test_sample.py . [100%]
---------- coverage: platform linux, python 3.x.x ----------
Name Stmts Miss Cover
----------------------------------
myapp.py 3 0 100%
============================== 1 passed in 0.03s ==============================
# An HTML report is created in the htmlcov directory.
Common Pitfalls
Common mistakes when generating coverage reports include:
- Not installing
pytest-covplugin, so--covoption is not recognized. - Forgetting to specify the correct package or module path in
--cov=. - Running tests without coverage options, so no report is generated.
- Expecting coverage for code not imported or executed during tests.
bash
Wrong: pytest Right: pytest --cov=myapp --cov-report=term
Quick Reference
| Option | Description |
|---|---|
| --cov=PATH | Measure coverage for the specified path |
| --cov-report=term | Show coverage summary in terminal |
| --cov-report=html | Generate HTML coverage report |
| --cov-report=xml | Generate XML coverage report for CI tools |
| --cov-fail-under=MIN | Fail test if coverage is below MIN% |
Key Takeaways
Install pytest-cov plugin to enable coverage reporting with pytest.
Use --cov=your_package to specify which code to measure.
Add --cov-report=term or --cov-report=html to see coverage results.
Ensure tests execute the code you want coverage for.
Use --cov-fail-under to enforce minimum coverage thresholds.