Coverage: Measuring What Your Tests Miss

Coverage: Measuring What Your Tests Miss in Python: "Are my tests good enough?" is unanswerable by staring at them.

Concept Explanation

"Are my tests good enough?" is unanswerable by staring at them. Code coverage answers a narrower but concrete version: which lines of my code ran while the test suite was running?

The tool imports your code with a tracer attached, records every line executed, and reports the ones that never were. Those un-executed lines are, by definition, untested — nothing you wrote asserts anything about them.

Setup

pip install pytest-cov

pytest --cov=myapp --cov-report=term-missing
Name                  Stmts   Miss  Cover   Missing
---------------------------------------------------
myapp/__init__.py         2      0   100%
myapp/orders.py          48      6    88%   34-37, 61, 79
myapp/payments.py        31     14    55%   18-24, 40-46
---------------------------------------------------
TOTAL                    81     20    75%

The Missing column is the only part that matters. 75% is a number; payments.py lines 18-24 is a to-do list.

Line Coverage vs Branch Coverage

This is the distinction that makes coverage genuinely useful:

def apply_discount(total, is_member):
    if is_member:
        total *= 0.9
    return total

A single test with is_member=True executes every line — 100% line coverage. But the if was never false, so the "not a member" path is untested. Turn on branch coverage and the gap appears:

pytest --cov=myapp --cov-branch --cov-report=term-missing

Always use --cov-branch. Line coverage flatters you; branch coverage tells the truth.

Configuration Belongs in a File

# pyproject.toml
[tool.coverage.run]
source = ["myapp"]
branch = true
omit = ["*/tests/*", "*/migrations/*", "*/__main__.py"]

[tool.coverage.report]
show_missing = true
skip_covered = true
fail_under = 80
exclude_lines = [
    "pragma: no cover",
    "if TYPE_CHECKING:",
    "raise NotImplementedError",
    "if __name__ == .__main__.:",
]

fail_under = 80 makes the suite exit non-zero below that threshold, which is how coverage becomes a CI gate rather than a report nobody opens.

What Coverage Does Not Tell You

This is the important half of the lesson. Consider:

def test_divide():
    divide(10, 2)          # no assert at all

100% coverage of divide. Zero verification. Coverage measures execution, not assertion. It cannot tell you:

  • whether you asserted anything useful,
  • whether your assertions are correct,
  • whether the combinations of inputs matter,
  • whether the untested path is the one that loses money.

A codebase at 95% coverage with weak assertions is worse than one at 70% with sharp ones — and coverage will rank them the other way round.

Mutation Testing: The Honest Check

If you want to know whether your assertions bite, use mutmut or cosmic-ray. They deliberately change your code — flip a < to <=, replace a return value with None — and check whether any test notices. A surviving mutant is a line your tests execute but do not actually verify.


Code Example #1 (Basic)

Finding a real gap.

# shipping.py
def shipping_cost(weight_kg, country, express=False):
    if weight_kg <= 0:
        raise ValueError("Weight must be positive")

    base = 5.00 if country == "UK" else 12.00
    if weight_kg > 10:
        base += (weight_kg - 10) * 0.75
    if express:
        base *= 1.8
    return round(base, 2)
# test_shipping.py
from shipping import shipping_cost

def test_uk_standard():
    assert shipping_cost(2, "UK") == 5.00
pytest --cov=shipping --cov-branch --cov-report=term-missing
Name           Stmts   Miss Branch BrPart  Cover   Missing
-------------------------------------------------------------
shipping.py        9      1      6      3    67%   3, 7->9, 9->10

The report is a checklist: line 3 is the raise (no test passes a bad weight), and the two partial branches are the heavy-item surcharge and the express multiplier. Four more tests take this to 100% branch coverage — and each one is a real case a customer will hit.

Code Example #2 (Intermediate)

Coverage as a CI gate, with honest exclusions.

# reporting.py
from typing import TYPE_CHECKING

if TYPE_CHECKING:                          # never executes at runtime
    from myapp.models import Order         # pragma: no cover

def summarise(orders):
    total = sum(o.amount for o in orders)
    return {"count": len(orders), "total": total}

def _debug_dump(orders):                   # pragma: no cover
    """Developer-only helper; deliberately excluded from coverage."""
    for o in orders:
        print(o)

def main():                                # pragma: no cover
    import sys
    print(summarise(load(sys.argv[1])))

if __name__ == "__main__":                 # pragma: no cover
    main()
# .github/workflows/tests.yml
name: tests
on: [push, pull_request]

jobs:
  pytest:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: "3.12"
      - run: pip install -e ".[dev]"

      # fail_under in pyproject.toml makes this the gate
      - run: pytest --cov --cov-branch --cov-report=xml --cov-report=term-missing

      - uses: actions/upload-artifact@v4
        if: always()
        with:
          name: coverage
          path: coverage.xml

Two habits worth adopting: put # pragma: no cover only on code that genuinely cannot be tested meaningfully (entry points, type-checking imports, debug helpers), and generate the HTML report locally when you are actually hunting gaps:

pytest --cov=myapp --cov-branch --cov-report=html
# then open htmlcov/index.html -- uncovered lines are highlighted in red

The HTML view is far more useful than the terminal summary. Red lines in a file you thought was well tested is a genuinely informative experience.


Common Mistakes

  1. Chasing 100%: the last 10% is usually error handlers and entry points, and forcing tests for them produces tests that assert nothing. 80–90% branch coverage with strong assertions is a healthier target.
  2. Reporting line coverage only: without --cov-branch, an if with no else looks fully covered when half of it never ran.
  3. Treating coverage as a quality score: it measures execution. A test with no assert covers everything and verifies nothing.
  4. Including test files in the measurement: your tests will always be ~100% covered, which inflates the total and hides real gaps. omit them.
  5. Sprinkling # pragma: no cover to hit a threshold: at that point you are editing the thermometer, not the temperature.
  6. Measuring the installed package instead of your source: without source = ["myapp"], coverage may report on site-packages and show a misleadingly high total.
  7. Ignoring "partial branch" warnings: 7->9 means the condition on line 7 only ever went one way. That is precisely the case you have not tested.

Best Practices

  • Always enable branch = true: it is the difference between a vanity metric and a diagnostic.
  • Read Missing, not Cover: the percentage is for dashboards; the line numbers are for you.
  • Set fail_under slightly below current coverage: a ratchet that prevents regression without blocking every PR.
  • Use the HTML report to hunt: --cov-report=html then open htmlcov/index.html.
  • *Never let coverage go down in a PR*: new code should arrive with its tests. Most CI providers can enforce this on the diff alone, which is a far better signal than the project total.
  • Cover the paths that cost money first: payments, authorisation, and data deletion deserve tests before the logging helper does.
  • Run mutation testing occasionally: mutmut run on your best-covered module is a humbling and useful hour.
  • Never use coverage as a performance target for people: any number becomes reachable by writing assertion-free tests, and then you have made the suite worse on purpose.

Practice Exercises

  1. The Gap Hunt: Run pytest --cov --cov-branch --cov-report=html on any project you have, open the HTML report, and write down the three uncovered lines you would consider most dangerous. Add a test for each.
  2. The Branch Proof: Write a function with one if/else and a single test covering only the if. Show that line coverage reports 100% while branch coverage does not, and explain the difference in a comment.
  3. The Empty Test: Write a test that calls a function and asserts nothing. Confirm it reports full coverage of that function, then use mutmut (or hand-edit the function to return a wrong value) to prove the test cannot detect a bug. Write two sentences on what this means for coverage targets.