pip install coverage★Installs thecoverageCLI.pip install coverage[toml]on older Pythons forpyproject.tomlconfig (built-in on 3.11+).coverage run -m pytest★The core idea: replacepythonwithcoverage run. It launches and traces the process. Works with any runner:coverage run -m unittest,coverage run prog.py args.coverage run --source=mypkg -m pytest★Limit what's measured to your package — otherwise stdlib and dependencies inflate/pollute the numbers. Set once in config instead (card 4).coverage run --append ... · coverage erase--appendadds to existing data (multiple runs);erasewipes the.coveragefile to start clean.
coverage report -m★Terminal table of statements / missed / percent.-madds the missing line numbers — the fastest way to see what's untested.coverage html # -> htmlcov/index.html★Annotated source you can click through — green = run, red = missed. The best view for exploring gaps.coverage xml # Cobertura, for CI / Codecov coverage json · coverage lcov★Machine-readable outputs for CI dashboards (Codecov/Coveralls takexml/lcov).coverage report --skip-covered --sort=coverHide fully-covered files and sort by percentage — focus on the weakest spots.
coverage run --branch -m pytest★Measures both directions of every branch, not just whether a line ran. Catches anifwhoseelsepath is never taken — line coverage misses this.# report gains Branch / BrPart columns; -m shows e.g. 34->exit★Partial branches show as34->36/34->exitin the missing column — the line ran but one outgoing path never did.# enable permanently in config: branch = trueSet it in[tool.coverage.run]so every run measures branches (card 4). Branch coverage is the recommended default.