Sub topic 15
Measuring coverage with pytest-cov
This chapter assumes you can write and run pytest tests, and that you work inside a virtual environment where you can install packages with pip.
What coverage tells you
Coverage measures which lines of your code ran while the tests ran. A line that never ran has no test exercising it. A line that did run is not proven correct, because a test may run it without checking the result. Treat coverage as a way to find untested code, not as a score for test quality.
The pytest-cov plugin connects pytest to the coverage package. Install it into your environment:
pip install pytest-covRunning a coverage report
Use the cart.py module from earlier chapters. Suppose it has grown a second function that no test calls:
# cart.py
def total(prices, tax_rate=0.0):
if tax_rate < 0:
raise ValueError("tax_rate must be non-negative")
return sum(prices) * (1 + tax_rate)
def discount(amount, percent):
return amount * (1 - percent / 100)Run pytest with the --cov option, naming the module or package to measure:
pytest --cov=cart --cov-report=term-missingThe output ends with a table like this:
Name Stmts Miss Cover Missing
---------------------------------------
cart.py 6 1 83% 8
---------------------------------------
TOTAL 6 1 83%The columns mean:
| Column | Meaning |
|---|---|
| Stmts | Executable statements in the file |
| Miss | Statements that never ran |
| Cover | Percentage of statements that ran |
| Missing | Line numbers that never ran (shown by `term-missing`) |
The exact counts depend on your file. The Missing column is the useful part: it points to the lines that need a test.
Closing the gap
The report shows that the body of discount never ran. Add a test for it:
# test_discount.py
import pytest
from cart import discount
def test_discount_takes_percent_off():
assert discount(200, 25) == pytest.approx(150.0)Run the same command again and cart.py reports 100%.
Branch coverage
By default, coverage counts statements. A line like if x: counts as covered even if the condition was never false. Add --cov-branch to track whether each branch of a decision was taken:
pytest --cov=cart --cov-branch --cov-report=term-missingMissing branches appear in the Missing column as arrows, for example 5->7, meaning the jump from line 5 to line 7 never happened.
Making coverage a gate
You can fail the run when coverage drops below a threshold:
pytest --cov=cart --cov-fail-under=90Pytest then exits with a non-zero status if total coverage is under 90%. This suits continuous integration. Pick a threshold your suite already meets, and raise it gradually. A very high target tempts people to write tests that run lines without asserting anything.
Common errors
- No data collected: the
--covtarget does not match an imported module name. - Tests counted as source: if you point
--covat the whole project directory, test files appear in the report. Name your source package instead. - Unexpected misses: code that only runs at import time, such as module-level statements, may appear covered or uncovered depending on import order. Use a package name to keep results consistent.
Exercise
Your report shows cart.py at 90% with Missing listing 4, where line 4 is raise ValueError(...). Which test would cover it, and which command would show missing branches too?
Show answer
A test that calls total with a negative rate inside pytest.raises(ValueError), for example total([1], tax_rate=-0.5). Run pytest --cov=cart --cov-branch --cov-report=term-missing to include branch coverage.