How to measure and improve test coverage in a FastAPI project
pytest-cov, coverage report, branch coverage, .coveragerc, omitting files, coverage badge, what to prioritize covering, missing line numbers
Code Coverage with pytest-cov
Code coverage measures which lines of your application are executed by tests. It is a quality signal — not a target. 80% coverage with meaningful tests beats 100% coverage with trivial ones.
Install and run
pip install pytest-cov
# Run with coverage
pytest --cov=app --cov-report=term-missing
# Generate HTML report
pytest --cov=app --cov-report=html
open htmlcov/index.html
Configure with .coveragerc
[run]
source = app
omit =
app/migrations/*
app/database.py
*/tests/*
[report]
fail_under = 75
fail_under fails the test run if coverage drops below the threshold — useful in CI pipelines to prevent coverage regressions.
What to prioritize
Focus coverage on: business logic in CRUD functions, authentication edge cases (expired token, wrong password, inactive user), validation error paths (422 responses), and custom middleware. Skip: auto-generated migration files, configuration modules, and trivially obvious routes.
# Branch coverage catches missed conditional paths
pytest --cov=app --cov-branch --cov-report=term-missingBranch coverage (--cov-branch) reports whether both sides of conditionals were tested. A line can be covered while an if/else branch remains untested.
