Sub topic 15
Measuring coverage with pytest-cov
This chapter assumes you can write and run pytest tests, use pytest -v and -k, and edit pyproject.toml. The earlier chapters on running pytest and configuration cover these. You also need a virtual environment where you can install packages.
What coverage measures
Code coverage records which parts of your source code ran while the test suite executed. It answers one question: which code did no test touch? It cannot tell you whether the tests check anything useful.
Two measures matter in practice:
- Line (statement) coverage reports which statements ran at least once.
- Branch coverage reports whether each decision point went both ways. An
ifhas a "true" path and a "false" path, and both count.
The tool that does the measuring is coverage.py. The plugin pytest-cov connects it to pytest, starts measurement before your code is imported, and prints reports at the end of the run.
Installing and running
Install the plugin into the same environment as pytest:
pip install pytest-covThen ask for coverage of a module or package. This is the command from the earlier chapters:
pytest --cov=cart --cov-report=term-missing--cov=cart names what to measure. Use an importable package or module name, or a directory path. --cov-report=term-missing prints a table in the terminal and adds a column listing the line numbers that never ran.
Suppose test_cart.py contains only test_total_without_tax. The report looks like this:
Name Stmts Miss Cover Missing
---------------------------------------
cart.py 4 1 75% 4
---------------------------------------
TOTAL 4 1 75%cart.py has four statements: the def, the if, the raise, and the return. Line 4 is the raise ValueError(...). No test sent a negative tax rate, so that line never ran. Adding test_negative_tax_rate_is_rejected brings the file to 100%.
Read the Missing column before you read the percentage. It tells you exactly which behavior has no test.
Line coverage can hide gaps
Here is a function with a conditional discount:
# discount.py
def apply_discount(price, coupon=None):
if coupon:
price = price - 5
return priceAnd a single test:
# test_discount.py
from discount import apply_discount
def test_coupon_reduces_price():
assert apply_discount(20, coupon="SAVE5") == 15Every line runs, so line coverage reports 100%. But the case where no coupon is given was never tested. If someone later changes return price into something that breaks that case, no test fails. Branch coverage exposes this:
pytest --cov=discount --cov-branch --cov-report=term-missingName Stmts Miss Branch BrPart Cover Missing
---------------------------------------------------------
discount.py 4 0 2 1 83% 2->4
---------------------------------------------------------
TOTAL 4 0 2 1 83%Branch counts the possible jumps. BrPart counts decision points where only one outcome was seen. The entry 2->4 means that the jump from line 2 (the if) straight to line 4 (the return) never happened. The percentage combines both kinds of counts: (4 statements + 1 branch taken) out of (4 statements + 2 branches) is about 83%.
Turn on branch coverage for any real project. It costs little and finds gaps that line coverage cannot.
flowchart TDThe block above is not a valid diagram fence, so here is the diagram in the required form:
Choosing report formats
You can request several reports in one run by repeating the option:
| Option | Output | Typical use |
|---|---|---|
| `--cov-report=term` | Table in the terminal | Quick check |
| `--cov-report=term-missing` | Table plus missing line numbers | Daily work |
| `--cov-report=term-missing:skip-covered` | Same, hiding files at 100% | Large projects |
| `--cov-report=html` | Browsable pages in `htmlcov/` | Reading uncovered code in context |
| `--cov-report=xml` | `coverage.xml` | Upload to CI services |
The HTML report highlights each source line in green or red, and with branch coverage it marks partial branches. For a hard-to-read Missing list, open htmlcov/index.html in a browser.
Configuring coverage in pyproject.toml
Typing long options every time is error-prone. Put the stable choices in pyproject.toml. Pytest options go in [tool.pytest.ini_options], and coverage.py has its own tables:
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --cov=cart --cov-report=term-missing"
[tool.coverage.run]
branch = true
source = ["cart"]
[tool.coverage.report]
show_missing = true
skip_covered = false
exclude_lines = [
"pragma: no cover",
"if __name__ == .__main__.:",
"raise NotImplementedError",
]With this in place, a plain pytest run reports branch coverage for cart. A few notes on the settings:
branch = trueis the same as passing--cov-branch.sourcelimits measurement to your own code, so tests and third-party packages stay out of the numbers.exclude_linesholds regular expressions. A line matching one is left out of the totals, and so is the whole block it introduces.pragma: no coveris the default, so keeping it in the list preserves that behavior.
You can mark individual lines or blocks yourself:
def debug_dump(data): # pragma: no cover
print(data)Use this sparingly. Every exclusion is a place where you chose not to look. Prefer excluding code that cannot be tested in a unit test, such as a __main__ guard. Do not exclude code merely because it is awkward to test.
Enforcing a minimum
Coverage becomes a safety net when a run fails if the number drops. Use --cov-fail-under:
pytest --cov=cart --cov-branch --cov-fail-under=90If total coverage is below 90%, pytest exits with a non-zero status even though every test passed. A CI system treats that as a failed build. You can also set fail_under = 90 under [tool.coverage.report].
Pick a threshold your project already meets, then raise it gradually. A threshold set far above the current level only teaches people to ignore the failure. Be careful with fail_under when you run a subset such as pytest -k total. A partial run covers less code and fails the check for reasons unrelated to quality.
Common errors
- "Module was never imported" or "No data was collected." The name given to
--covdoes not match what your tests import. Check whether you wrote a file path where a module name is needed, or the reverse, and whether the package is installed or onsys.path. - Module-level code shows as missed. Coverage must start before your module is imported. If something imports your code before pytest-cov starts, such as a plugin or an early import in a
conftest.pyloaded too soon, definitions at module level can appear unexecuted. Running throughpytest --covrather than starting coverage by hand avoids most of these cases. - Subprocesses are not measured. Code that runs in a separate process is only counted if coverage is also configured for that process. If your tests spawn processes and you need their coverage, check the
pytest-covdocumentation on subprocess support. - A high percentage and a buggy program. A test with no
assertstill raises the number. Coverage proves code ran, not that its result was checked.
Using the number well
Treat coverage as a map of untested code. A low number in a core module is a useful warning. A rising number says nothing about test quality, and chasing 100% invites tests that execute code without asserting anything. Review the Missing list when you add a feature, ask whether each missed line is a behavior you care about, and write a test for it if so.
Exercise
A test file calls apply_discount(20, coupon="SAVE5") and nothing else. Line coverage for discount.py is 100%, but the branch report shows 2->4 as missing. What does that mean, and which test would fix it?
Show answer
The if coupon: on line 2 was only ever true. The path where it is false and execution jumps directly to return price on line 4 was never exercised. Add a test that calls apply_discount(20) without a coupon and asserts the result is 20. Running with --cov-branch then shows no partial branches.
Exercise
Write the pyproject.toml lines that turn on branch coverage, limit measurement to the cart package, and make pytest fail when coverage is below 85%.
Show answer
Under [tool.coverage.run] set branch = true and source = ["cart"]. Under [tool.coverage.report] set fail_under = 85. Alternatively, pass --cov-fail-under=85 in addopts under [tool.pytest.ini_options].