Lesson 6 of 9 · 23m
Coverage That Means Something
Use line and branch coverage as a missing-test detector, understand what coverage cannot prove, and set thresholds that guide rather than perform.
Coverage is the most abused number in testing. Teams chase 90 percent, write tests that touch code without asserting behavior, and end up with a green badge over an empty suit. Coverage is useful only when you treat it as evidence about what is missing, not proof of what is correct.
Measure with pytest-cov
pip install pytest-cov
pytest --cov=src --cov-report=term-missingTypical output:
Name Stmts Miss Cover Missing
--------------------------------------------------------
src/billing/service.py 84 7 92% 41-47
src/billing/webhooks.py 52 21 60% 12-29
--------------------------------------------------------
TOTAL 136 28 79%Missing is the actionable part. Open those lines and ask what behavior lives there. Do not start by asking how to make the number go up.
Line coverage is not branch coverage
A line can execute while one side of a decision never does:
def price(user, amount):
if user.is_vip:
return amount * 0.8
return amountIf every test uses a VIP user, both return lines may never both execute — but simplistic tests can still make coverage look healthier than the decision logic deserves. Enable branch coverage:
# pyproject.toml
[tool.coverage.run]
branch = true
source = ["src"]Branch coverage asks whether each edge was taken. It is more meaningful, especially around error handling.
Coverage cannot see assertion quality
This test produces coverage and proves almost nothing:
def test_invoice():
invoice = create_invoice()
assert invoice is not NoneThe code ran. The behavior may still be wrong. Mutation testing tools like mutmut exist because high coverage and weak assertions coexist constantly. You do not need mutation testing everywhere, but you should understand the hole it exposes.
Thresholds should protect the floor, not decorate the ceiling
A practical configuration:
[tool.coverage.report]
fail_under = 80
show_missing = true
exclude_also = [
"if TYPE_CHECKING:",
"raise NotImplementedError",
]Set the threshold slightly below current reality, then raise it when the team intentionally improves weak areas. Do not demand 100 percent. The last few percent often contain defensive crashes, platform branches, and glue that integration environments cover better.
Field notes
- Exclude generated code, migration scripts, and one-off management commands or they will distort the metric.
- Coverage on tests themselves is noise; measure the application source only.
- A sudden coverage drop is useful CI signal. A stable high number is not a quality certification.
- HTML reports (
--cov-report=html) are better than terminal output for exploring large gaps. - Read uncovered lines as a todo list written by the codebase.
Was this lesson helpful?