Skip to main content

Testing and QA · Intermediate · 20 min

Measure code coverage without chasing 100 percent

By Padding · Updated 18 Nov 2026
Debian (python:3.15-slim) · Python 3.15 · coverage.py 7.17 · pytest-cov 7.1 · diff-cover 11.0 · pytest 9.2.0 · uv 0.13

You will measure line and branch coverage with coverage.py and pytest-cov, read the HTML report to find untested branches, exclude code honestly, and gate a Git branch on diff coverage with diff-cover instead of a global percentage.

On this page

Code coverage tells you which lines and branches of your code ran while your tests ran. It cannot tell you whether the tests checked anything. That gap is why a team that sets "100 percent coverage" as a target usually ends up with tests written to touch lines rather than to catch bugs, and with # pragma: no cover scattered wherever the number was hard to reach.

Used well, coverage is a map of what nobody has tested yet. In this tutorial you measure a small delivery-fee module with coverage.py through pytest-cov and use the report three ways:

  • branch coverage to find a decision your tests only ever took one way, even though every line ran;
  • honest exclusions for code that is not worth testing, written down in one place;
  • diff coverage with diff-cover, so a pull request is judged on the lines it changed rather than on a project-wide percentage.

Then you watch a fully covered module fail on a boundary case, which is the reason not to stop at the number. A short step at the end shows the same ideas in JavaScript with Vitest.

Step 1 · Create the project and install the tools

Make a throwaway project in a Git repository, and add pytest, pytest-cov, coverage.py and diff-cover as development dependencies. The ranges allow patch releases and nothing newer:

Bash
mkdir -p ~/coverage-demo
cd ~/coverage-demo
git init -b main
uv init --no-package
uv add --dev "pytest>=9.2,<9.3" "pytest-cov>=7.1,<7.2" "coverage>=7.17,<7.18" "diff-cover>=11.0,<11.1"
rm main.py
cat >> .gitignore <<'EOF'
.coverage
coverage.xml
htmlcov/
EOF
cat >> pyproject.toml <<'EOF'

[tool.pytest.ini_options]
pythonpath = ["."]
EOF
mkdir shop tests
touch shop/__init__.py

pytest-cov is the pytest plugin that starts coverage.py before your tests import anything and prints the report at the end. The three ignored paths are the data file, the XML report and the HTML report you create later. pythonpath = ["."] lets tests in tests/ import the shop package.

Check it worked

Bash
uv run coverage --version
uv run diff-cover --version

The first command prints Coverage.py, version 7.17.5 (or a later 7.17 release) followed by a line about the C extension. The second prints a version starting with 11.0.

Step 2 · Measure line coverage

The module works out a delivery fee in cents. Orders of 20,000 cents or more are meant to ship free unless they go express. Create shop/fees.py:

Bash
cat > shop/fees.py <<'PY'
FREE_DELIVERY_FROM = 20_000  # cents
BASE_FEE = 500
PER_KM = 100


def delivery_fee(subtotal, distance_km, express=False):
    """Delivery fee in cents.

    Orders of 20,000 cents or more ship free, unless sent express.
    """
    if subtotal <= 0:
        raise ValueError("subtotal must be positive")
    fee = BASE_FEE
    if distance_km > 5:
        fee += (distance_km - 5) * PER_KM
    if express:
        fee *= 2
    if subtotal > FREE_DELIVERY_FROM and not express:
        fee = 0
    return fee
PY

Now three tests that look reasonable at first glance, in tests/test_fees.py:

Bash
cat > tests/test_fees.py <<'PY'
import pytest

from shop.fees import delivery_fee


def test_long_express_trip_costs_double():
    assert delivery_fee(1_000, 8, express=True) == 1_600


def test_big_orders_ship_free():
    assert delivery_fee(25_000, 10) == 0


def test_rejects_empty_orders():
    with pytest.raises(ValueError):
        delivery_fee(0, 3)
PY
uv run pytest --cov=shop --cov-report=term-missing

--cov=shop measures the shop package and nothing else, so the tests themselves and the libraries they import do not pad the figure. --cov-report=term-missing adds a column listing the line numbers that never ran.

Check it worked

All three tests pass and the report ends like this:

Text
Name               Stmts   Miss  Cover   Missing
------------------------------------------------
shop/__init__.py       0      0   100%
shop/fees.py          14      0   100%
------------------------------------------------
TOTAL                 14      0   100%

Every statement ran. Keep that 100% in mind for the next step.

Step 3 · Turn on branch coverage

Line coverage asks "did this line run?". Branch coverage also asks "did each decision go both ways?". An if with no else can have its body run every time and its condition never be false, and line coverage cannot see that. Turn branch measurement on in pyproject.toml, so every run uses it without a flag:

Bash
cat >> pyproject.toml <<'EOF'

[tool.coverage.run]
branch = true
source = ["shop"]
EOF
uv run pytest --cov=shop --cov-report=term-missing

Check it worked

The report gains two columns, and the same tests now score 95%:

Text
Name               Stmts   Miss Branch BrPart  Cover   Missing
--------------------------------------------------------------
shop/__init__.py       0      0      0      0   100%
shop/fees.py          14      0      8      1    95%   14->16
--------------------------------------------------------------
TOTAL                 14      0      8      1    95%

Branch is the number of possible jumps (two per if), BrPart the number of decisions that only went one way, and 14->16 the jump that never happened: from the if distance_km > 5: on line 14 straight to line 16. Both trips in the tests are longer than 5 km, so the short-trip price has never been checked. Branch coverage counts statements and branches together, which is why the figure drops by less than you might expect.

Step 4 · Read the HTML report to find untested branches

The terminal report gives line numbers. The HTML report shows the code itself, coloured, with each partial branch explained in words. Generate it:

Bash
uv run pytest -q --cov=shop --cov-report=html

Open htmlcov/index.html in your browser and click shop/fees.py. Green lines ran, red lines never ran, and yellow lines are partial branches. Line 14 is yellow. Hover over or click the note at the right of the line to read the reason.

The report is a small static folder with no server behind it. If your team reviews on phones or on metered mobile data, zip htmlcov/ and attach it to the CI run, so reviewers can open it without cloning the project and installing anything.

Now write the missing test. It is a real case a customer will hit, not a line-touching exercise:

Bash
cat >> tests/test_fees.py <<'PY'


def test_short_trip_pays_the_base_fee():
    assert delivery_fee(1_000, 3) == 500
PY
uv run pytest -q --cov=shop --cov-report=term-missing

Check it worked

In the HTML report, line 14 read "line 14 didn't jump to line 16 because the condition on line 14 was always true". After the new test, four tests pass and shop/fees.py shows 8 in Branch, 0 in BrPart and 100%.

Step 5 · Exclude code honestly

Some code is not worth testing: a block that only runs when a module is started by hand, a raise NotImplementedError in a base class, imports under if TYPE_CHECKING:. Add a small command-line entry point to shop/fees.py so you can try fees from the shell:

Bash
cat >> shop/fees.py <<'PY'


if __name__ == "__main__":
    import sys

    print(delivery_fee(int(sys.argv[1]), int(sys.argv[2])))
PY
uv run python -m shop.fees 1500 7
uv run pytest -q --cov=shop --cov-report=term-missing

It prints 700, and coverage falls to 89% with lines 24-26 missing. Those lines will never run under pytest, and testing them would prove nothing about fees.

Exclude the pattern once, in configuration, rather than with a comment on each block. exclude_also adds regular expressions to coverage.py's built-in exclusions (which already include # pragma: no cover). A matching line, and the block it opens, leave the count:

Bash
cat >> pyproject.toml <<'EOF'

[tool.coverage.report]
exclude_also = [
    'if __name__ == "__main__":',
]
EOF
uv run pytest -q --cov=shop --cov-report=term-missing

A rule of thumb for what belongs here: exclude code that is not meant to run in tests, never code that is hard to test. An error handler for a failed payment is hard to reach, and it is exactly where a bug hurts most. If you exclude it to lift the number, the report stops telling you the truth. Keeping exclusions in pyproject.toml means they show up in code review as one visible list.

Check it worked

shop/fees.py is back to 14 statements and 100%. In a fresh HTML report (uv run pytest -q --cov=shop --cov-report=html) the three __main__ lines are greyed out as excluded, not hidden, so anyone can see what was left out.

Step 6 · Gate a branch on diff coverage

A project-wide target has two problems. On an old codebase at 60%, a target of 80% blocks every pull request until someone writes tests for code they did not touch. On a well-tested codebase, a big new feature with no tests barely moves the total. Diff coverage asks a fairer question: of the lines this branch added or changed, how many did the tests run?

Commit the work so far on main, then start a feature branch that adds coupon codes with only one test:

Bash
git add -A
git commit -m "Delivery fees with tests"
git switch -c add-coupons
cat > shop/coupons.py <<'PY'
def apply_coupon(subtotal, code):
    """Return the subtotal in cents after a coupon code."""
    code = code.strip().upper()
    if code == "WELCOME10":
        return subtotal - subtotal // 10
    if code == "FLAT500":
        if subtotal < 2_000:
            raise ValueError("FLAT500 needs an order of 2,000 cents or more")
        return subtotal - 500
    raise ValueError(f"unknown coupon: {code}")
PY
cat > tests/test_coupons.py <<'PY'
import pytest

from shop.coupons import apply_coupon


def test_welcome_takes_ten_percent_off():
    assert apply_coupon(5_000, " welcome10 ") == 4_500
PY
git add -A
git commit -m "Add coupon codes"

diff-cover reads a Cobertura XML report, so ask pytest-cov for one, then compare the branch with main:

Bash
uv run pytest -q --cov=shop --cov-report=term-missing --cov-report=xml
uv run diff-cover coverage.xml --compare-branch=main --branch-coverage --fail-under=90 || echo "diff-cover failed the branch"

--compare-branch=main matters: diff-cover compares against origin/main by default, and this demo has no remote. In CI, the default is usually what you want. --branch-coverage counts a partly covered decision as uncovered, to match the branch measurement you turned on earlier. --fail-under=90 makes it exit with a non-zero status below 90%, which is what fails a CI job.

Read the two reports side by side. The project total is around 73%, which a typical global target of 70% would have let through. diff-cover reports Failure. Coverage is below 90%. and points at shop/coupons.py (33.3%) with Missing lines 4,6-10. Lines 6 to 10, the whole FLAT500 path and the unknown-code error, never ran. Line 4 did run, but its if was never false, so --branch-coverage counts it as missing too. Without that flag the same branch scores 44%.

Add tests for the cases a customer will meet, commit, and run the gate again:

Bash
cat >> tests/test_coupons.py <<'PY'


def test_flat500_takes_500_off():
    assert apply_coupon(3_000, "FLAT500") == 2_500


def test_flat500_needs_a_minimum_order():
    with pytest.raises(ValueError, match="2,000"):
        apply_coupon(1_500, "flat500")


def test_unknown_codes_are_rejected():
    with pytest.raises(ValueError, match="unknown coupon"):
        apply_coupon(3_000, "FREEBIE")
PY
git add -A
git commit -m "Test every coupon path"
uv run pytest -q --cov=shop --cov-report=xml
uv run diff-cover coverage.xml --compare-branch=main --branch-coverage --fail-under=90

If you also want a floor for the whole project, set it low and below where you are today (for example fail_under = 70 under [tool.coverage.report]), so it only catches a large drop. Let diff coverage do the day-to-day work.

Check it worked

The second diff-cover run ends with shop/coupons.py (100%), Missing: 0 lines and Coverage: 100%, and exits with status 0. Run echo $? straight after it to see the 0.

Step 7 · See 100 percent coverage miss a bug

Every line and every branch in shop has now run. Go back to the rule in the docstring: orders of 20,000 cents or more ship free. No test uses exactly 20,000. Add one:

Bash
cat >> tests/test_fees.py <<'PY'


def test_orders_of_exactly_the_threshold_ship_free():
    assert delivery_fee(20_000, 3) == 0
PY
uv run pytest -q --cov=shop --cov-report=term-missing || echo "a test failed"

The test fails with assert 500 == 0, and the coverage table above the failure still says 100% for every file. The code uses > where the rule says "or more". Coverage counted the line as tested because 25_000 ran through it; no test sat on the boundary.

Fix the comparison. The whole file is rewritten so the change is exact:

Bash
cat > shop/fees.py <<'PY'
FREE_DELIVERY_FROM = 20_000  # cents
BASE_FEE = 500
PER_KM = 100


def delivery_fee(subtotal, distance_km, express=False):
    """Delivery fee in cents.

    Orders of 20,000 cents or more ship free, unless sent express.
    """
    if subtotal <= 0:
        raise ValueError("subtotal must be positive")
    fee = BASE_FEE
    if distance_km > 5:
        fee += (distance_km - 5) * PER_KM
    if express:
        fee *= 2
    if subtotal >= FREE_DELIVERY_FROM and not express:
        fee = 0
    return fee


if __name__ == "__main__":
    import sys

    print(delivery_fee(int(sys.argv[1]), int(sys.argv[2])))
PY
uv run pytest -q --cov=shop --cov-report=term-missing

Coverage measures what ran, not what was checked. A test with a weak assertion, or no assertion at all, counts the same as a precise one. Mutation testing closes that gap: it makes small changes such as >= to > and checks that some test fails. The bug you just fixed is exactly the kind of change it would have flagged.

Check it worked

All nine tests pass and the total is still 100%. The number did not move at any point in this step, while the module went from wrong to right.

Step 8 · Do the same in JavaScript with Vitest

The ideas carry over. In a Vitest 5 project, install the V8 coverage provider at the same version as Vitest:

Bash
npm install --save-dev vitest@5.1.2 @vitest/coverage-v8@5.1.2

Set the provider and an include pattern in vitest.config.ts. Without include, files that no test imports are left out of the report, which hides exactly the untested code you want to see:

TypeScript
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    coverage: {
      provider: 'v8',
      include: ['src/**/*.{ts,tsx}'],
      reporter: ['text', 'html'],
    },
  },
})
Bash
npx vitest run --coverage

The text table shows statements, branches, functions and lines per file with uncovered line numbers, and coverage/index.html is the browsable version. Honest exclusions use comments such as /* v8 ignore next -- @preserve */ (the @preserve stops the TypeScript build stripping the comment). For changed-line gating, point diff-cover at a Cobertura report from Vitest by adding 'cobertura' to reporter.

Check it worked

In your own Vitest project, the --coverage run prints a table with a % Branch column, and a file under src/ that no test imports still appears in it, at 0%.

Step 9 · Clean up

Remove the demo project when you are done. Python, uv and Git stay installed:

Bash
cd ~
rm -rf ~/coverage-demo

Check it worked

ls ~/coverage-demo reports that the folder does not exist.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.