Learning center

Patch coverage says the changed line is covered: did any test check its result?

Coverage records that a line ran and says nothing about assertions. Break the covered line on purpose: if every test still passes, no test checks it, and the coverage number is no evidence that the change works.

What coverage.py counts as covered#

Coverage.py describes its execution phase in one sentence: "Coverage.py runs your code, and monitors it to see what lines were executed." The analysis phase then "examines your code to determine what lines could have run", and the report is the difference between the two. How coverage.py works, 7.17.5 Nothing in either phase looks at a test's assertions. A line counts as covered when the interpreter executed it while measurement was on, whether the test that ran it compared the result with anything or threw it away.

Branch measurement narrows the gap without closing it. The documentation defines a branch by line transitions: "Where a line in your program could jump to more than one next line, coverage.py tracks which of those destinations are actually visited." Branch coverage measurement, 7.17.5 A conditional expression that fits on one line has no second destination line, so both of its arms count as one covered line even when only one arm ever ran.

A line at 100% that no test checks#

The module below is a constructed example: a price quote with a coupon and a shipping rule. Its tests were written to pass a patch coverage gate. The run used Python 3.11.18, pytest 9.2.0 and coverage.py 7.17.5. This is pricing.py, lines 1 to 6:

def quote(items, coupon=None):
    subtotal = sum(price * qty for price, qty in items)
    if coupon == "SAVE10":
        subtotal = subtotal * 0.9
    shipping = 0 if subtotal >= 50 else 5
    return {"lines": len(items), "total": round(subtotal + shipping, 2)}
# test_pricing.py
from pricing import quote

def test_quote_counts_lines():
    q = quote([(20.0, 1), (15.0, 2)], coupon="SAVE10")
    assert q["lines"] == 2
    assert "total" in q

def test_quote_without_coupon():
    q = quote([(10.0, 1)])
    assert q["total"] > 0

Measured with branches, every statement and every branch is covered:

$ coverage run --branch -m pytest -q
$ coverage report -m --include=pricing.py
Name         Stmts   Miss Branch BrPart  Cover   Missing
--------------------------------------------------------
pricing.py       6      0      2      0   100%

Now break line 4, the discount, by changing 0.9 to 0.8, and run the same tests:

$ sed -i 's/subtotal \* 0.9/subtotal * 0.8/' pricing.py
$ python -m pytest -q
2 passed in 0.01s

The coupon now takes 20 percent off and nothing fails. Delete __pycache__ (or set PYTHONDONTWRITEBYTECODE=1) before each run of a mutant: in a rerun of these steps, the 0.8 edit keeps the file's size, it landed in the same second as the previous test run, Python reused the cached bytecode, and even the strong test added below passed. The test that ran line 4 asserts the number of lines and that a total key exists, neither of which depends on the discount.

The shipping rule on line 5 is weaker still. Both tests produce a subtotal under 50 (45 and 10), so the free-shipping arm has never run, yet the report shows 0 missing branches because the conditional expression sits on one line. Changing that arm from 0 to 99 also leaves the tests green:

$ sed -i 's/shipping = 0 if/shipping = 99 if/' pricing.py
$ python -m pytest -q
2 passed in 0.01s

Find the tests that ran the line, then read their assertions#

A coverage report can say which tests executed each line. Coverage.py calls this a dynamic context, and the setting dynamic_context = test_function starts "a new dynamic context for every test function". Measurement contexts, 7.17.5 With it in .coveragerc, coverage json --show-contexts lists them per line:

$ coverage run -m pytest -q
$ coverage json --show-contexts --include=pricing.py -o cov.json
$ python -c "import json; d = json.load(open('cov.json'))['files']['pricing.py']['contexts']
for k in sorted(d, key=int): print(k, d[k])"
1 ['']
2 ['test_pricing.test_quote_counts_lines', 'test_pricing.test_quote_without_coupon']
3 ['test_pricing.test_quote_counts_lines', 'test_pricing.test_quote_without_coupon']
4 ['test_pricing.test_quote_counts_lines']
5 ['test_pricing.test_quote_counts_lines', 'test_pricing.test_quote_without_coupon']
6 ['test_pricing.test_quote_counts_lines', 'test_pricing.test_quote_without_coupon']

Line 1, the def, ran at import, outside any test, so its context is empty. Only one test ran the discount on line 4. Reading it shows no assertion on total, which predicts the result of the mutation before you run it. For a large suite this step turns "is this line tested?" into a short list of test functions to read. coverage html --show-contexts shows the same lists in the HTML report.

The disconfirmation: a covered line whose result is checked#

Add one test that states what the coupon should do, restore 0.9, and repeat the same mutation:

def test_coupon_takes_ten_percent():
    q = quote([(20.0, 1), (15.0, 2)], coupon="SAVE10")
    assert q["total"] == 50.0  # 50 * 0.9 + 5 shipping
$ python -m pytest -q
3 passed in 0.01s
$ sed -i 's/subtotal \* 0.9/subtotal * 0.8/' pricing.py
$ python -m pytest -q
>       assert q["total"] == 50.0  # 50 * 0.9 + 5 shipping
E       assert 45.0 == 50.0
FAILED test_pricing.py::test_coupon_takes_ten_percent - assert 45.0 == 50.0
1 failed, 2 passed in 0.02s

The coverage report is identical before and after this test, still 100 percent with 0 missing. Only the mutation run tells the two suites apart. That is the evidence that settles the finding: a covered line whose deliberate breakage fails a named test is checked; a covered line whose breakage passes is only executed.

The same third test also shows the limit of one mutation. Its subtotal is 45, so the free-shipping arm on line 5 still never runs, and the 99 mutation still passes all three tests. Each changed line needs its own break.

Choose the break that matches the change#

A useful mutation changes what the line is for, in the way a plausible bug would. For arithmetic, change a constant or an operator. For a comparison, move the boundary (>= to >). For a guard, invert the condition or delete the early return. For a call, drop the argument the change added. If a pull request changed one line, the break is usually the inverse of the change: put the old line back and run the tests. A suite that passes on both the old and the new line does not test the change.

Mutation tools such as mutmut automate this across a whole module and report the mutants no test killed. Their output needs its own reading, because some surviving mutants cannot change behavior at all; the guide to surviving mutants covers that case.

Decide from what the break shows#

What the finding saysEvidence to collectDecision
Changed line covered, gate passesBreak the line (or restore the old line) and run the tests that cover itIf a test fails, accept the coverage; if none fails, add an assertion on the line's result
Changed line covered by many testsdynamic_context = test_function and the per-line contextsRead the assertions of the listed tests before running mutations
100% branch coverage on a line with a conditional expression or and/orThe inputs the covering tests pass, checked against each armTreat each arm as unmeasured until a test reaches it and a break of it fails
Mutation of the line fails a named testThe failing assertion and the value it comparedRecord the test name with the coverage result; no new test needed
Line covered only by a test with no assertions (smoke or import test)The test bodyCount the line as executed, not tested, whatever the report says

When the suggestion to add a test came from a reviewer rather than a coverage gate, the guide to weak-assertion comments uses the same break-it-and-run method. For the opposite report, a line marked uncovered although a test ran it, see the guide to uncovered lines that ran.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading