Pytest Coverage Report: Generate It in 5 Steps
This guide shows you how to generate a pytest code coverage report, which tells you which lines of your code are actually executed during tests and which are not. You’ll learn to create a terminal summary, an HTML report you can open in a browser, and an XML report for CI tools. You’ll need a Python project with pytest already installed and at least one test file.
What You’ll Need
- Python 3.7 or newer installed on your system
- pytest installed (check with
pytest --version) - The
pytest-covplugin installed (we’ll install it in Step 1) - A project directory containing your source code and tests
Step-by-Step
- Install pytest-cov
Open a terminal and run:pip install pytest-cov
This plugin adds coverage options to the pytest command. Verify it’s recognized by runningpytest --helpand looking for--covin the output. - Run pytest with basic coverage
From your project root, run:pytest --cov=your_package_name
Replaceyour_package_namewith the name of the module or package you want to measure (e.g.,--cov=srcif your code lives in asrcfolder). If you have multiple packages, list them separated by commas or use--cov=.to include everything in the current directory. - Read the terminal summary
After the test results, you’ll see a table with columns: Stmts (total statements), Miss (statements not executed), Branch (branch coverage if enabled), BrPart (partial branches), Cover (percentage covered). The final line shows the total coverage percentage. - Generate an HTML report
Run:pytest --cov=your_package_name --cov-report=html
This creates ahtmlcov/directory. Openhtmlcov/index.htmlin a browser to see a color-coded view of each file. Green lines are executed, red lines are missed, and yellow lines indicate partial branches. - Generate an XML report (for CI)
For tools like Jenkins or GitLab CI, run:pytest --cov=your_package_name --cov-report=xml
This produces acoverage.xmlfile in the project root, which CI systems can parse to track coverage over time. - Combine multiple report types
You can generate several reports at once:pytest --cov=your_package_name --cov-report=term --cov-report=html --cov-report=xml - Set a coverage threshold (optional)
To fail the build if coverage drops below a percentage, add--cov-fail-under=80(replace 80 with your desired minimum).
Common Mistakes
- Forgetting the package name – Running
pytest --covwithout a target measures nothing and often errors. Always specify--cov=your_package. - Measuring the wrong directory – If your code is in a
srcfolder but you run--cov=., you’ll include tests and configuration files, skewing the numbers. - Ignoring missing dependencies – The plugin must be installed in the same environment where you run pytest. If you use a virtual environment, install it there.
- Not excluding test files – Coverage will count your test files as part of the codebase unless you exclude them. Use
--cov=your_packageto target only the source code, or add--cov-report=term --cov=your_packageto avoid including tests. - Misreading the coverage percentage – 80% coverage means 80% of statements were executed, not that 80% of branches were tested. Branch coverage is separate and requires
--cov-branch.
Tips
- Enable branch coverage – Run
pytest --cov=your_package --cov-branchto see how many if/else paths are tested. This gives a more thorough picture. - Use a config file – Add coverage settings to
pyproject.tomlor.coveragercto avoid typing long commands. For example, inpyproject.tomlunder[tool.coverage.run], setbranch = trueandsource = ["your_package"]. - Generate a diff report – Use
--cov-report=term-missingto show which lines are missing in the terminal output, so you don’t have to open the HTML. - Integrate with pre-commit – Add a coverage threshold to your CI pipeline to prevent regressions. For example,
--cov-fail-under=90. - Clean old reports – The
htmlcovfolder can become stale. Delete it before regenerating to avoid confusion.
Troubleshooting
- “ModuleNotFoundError: No module named ‘pytest_cov’” – The plugin isn’t installed. Run
pip install pytest-covand ensure you’re in the correct virtual environment. - “No data to report” – This usually means the package you specified doesn’t exist or wasn’t imported by any test. Double-check the package name and that your tests actually import the code.
- Coverage shows 0% for all files – Your tests aren’t importing the code. Make sure your test files import the modules you’re measuring, and that the package path is correct.
- HTML report is outdated – Delete the
htmlcovfolder and rerun the command. The report is not automatically cleaned. - Coverage percentage is too low – Look at the missing lines in the terminal or HTML. Often it’s because you haven’t tested error paths or edge cases. Write more tests for those branches.
- Command works locally but fails in CI – Ensure the CI environment has pytest-cov installed and that you’re running the command from the project root where the package is importable.
Frequently Asked Questions
What is the difference between statement and branch coverage?
Statement coverage tells you which lines of code ran. Branch coverage tells you which if/else or loop branches were taken. Branch coverage is stricter and often reveals untested edge cases.
Can I exclude certain files from coverage?
Yes. Use --cov=your_package to only measure that package, or add omit patterns in a .coveragerc file, e.g., omit = */migrations/*.
How do I see which lines are missing in the terminal?
Add --cov-report=term-missing to your command. The terminal output will then show line numbers for missed statements.
Does coverage affect the test results?
No. Coverage measurement is passive; it only records which lines execute. Your tests run exactly the same way. However, adding coverage tracking can slightly slow down execution.
What is a good coverage percentage?
There’s no universal number. Many projects aim for 80-90% for critical code, but the right target depends on your domain. Focus on covering the most important logic rather than chasing a number.
Can I generate coverage for a single test file?
Yes. Run pytest test_file.py --cov=your_package to measure coverage only when running that specific test file. This is useful for debugging a particular module.
Related
Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.