Coverage
Coverage measures which lines (and optionally branches) ran during the test suite. coverage.py is the usual tool; pytest-cov wires it to pytest. A percentage is a hint, not a proof of quality.
Detailed Explanation
A test suite that never imports refund.py will not catch a bug there. Coverage tells you that. It does not tell you that the refund logic is correct. One test that calls a function with one input can paint every line green and still miss the zero-amount path if that path shares lines.
coverage run -m pytest then coverage report / coverage html is the raw workflow. pytest --cov=src --cov-report=term-missing is the integrated one. Configuration lives in .coveragerc or pyproject.toml under [tool.coverage]. Omit tests/*, generated code, and **/migrations/**.
Branch coverage (branch = true) tracks whether both sides of an if ran. It is stricter and more useful than line coverage. A line return a if cond else b can be "covered" with only cond true unless you measure branches.
Fail-under gates (--cov-fail-under=80) keep the number from sliding. They also encourage people to write junk tests that execute lines without asserting. Review the new tests, not only the badge.
Coverage is measured on the process that ran the tests. Code that only runs in a child process needs concurrency = multiprocessing or a combine step. Code that only runs on a thread is usually seen. Async code is seen if the tests await it.
Do not chase 100% on a web app. Chase it on a parser or a money function. Exclude defensive if TYPE_CHECKING: and pragma: no cover sparingly, with a reason.
Code Examples
# pyproject.toml
[tool.coverage.run]
source = ["shop"]
branch = true
omit = ["*/tests/*"]
[tool.coverage.report]
fail_under = 80
show_missing = truepython -m pytest --cov=shop --cov-report=term-missingdef abs_cents(cents: int) -> int:
if cents < 0:
return -cents # a branch; one test with cents=1 misses it
return centsCommon Gotchas
Treating 100% as done
untested branches can share lines. Turn on branch coverage.
Coverage of a child process is missing by default
enable concurrency or you will "lose" multiprocessing code.
Green lines that never assert
a smoke import is not a test. Read the test, not the HTML colour.