Learning center

Coverage marks a line as missed: did it really not run?

Before writing a test for a missed line, check how the code ran: lines run in a subprocess, or imported before coverage started, go unrecorded. Fix the measurement first, then write tests only for the lines that are still missed, and confirm those with a second tracer.

Coverage records only the code it was watching#

Coverage.py sees a line only if measurement was running in that process at the moment the line executed. Its documentation puts the requirement plainly: "For coverage measurement to work properly, coverage has to be involved at the very beginning and very end of the Python process." For child processes it adds: "Your main program is measured because you started it with coverage, but the subprocesses need to have coverage started on them also." Managing processes, coverage.py 7.17.5

Two ordinary test setups break that requirement. A test that runs a command-line tool with subprocess.run executes the tool in a fresh interpreter with no coverage. A test run under pytest-cov can import project code from a plugin before pytest-cov starts measuring. In both cases the code ran, the tests checked its output, and the report still lists the lines as missing. A new test written against such a report adds nothing.

A command-line tool tested through a subprocess shows 0%#

This constructed example is a small CSV exporter and one test that runs it the way a user would. The run used Python 3.11.18, pytest 9.2.0 and coverage.py 7.17.5. This is exporter.py, lines 1 to 17:

import csv
import sys


def main(argv):
    rows = [line.split("=", 1) for line in sys.stdin.read().splitlines() if line]
    if not rows:
        print("nothing to export", file=sys.stderr)
        return 2
    writer = csv.writer(sys.stdout)
    writer.writerow(["key", "value"])
    writer.writerows(rows)
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
# test_exporter.py
import subprocess
import sys


def test_export_writes_csv():
    out = subprocess.run(
        [sys.executable, "exporter.py"],
        input="a=1\nb=2\n", capture_output=True, text=True, check=True,
    ).stdout
    assert out.splitlines() == ["key,value", "a,1", "b,2"]

The test passes, and its assertion can only hold if main() ran and wrote the CSV. With source = . and the test file omitted in .coveragerc, coverage reports the exporter as never executed:

$ coverage run -m pytest -q
1 passed in 0.06s
.../coverage/control.py:964: CoverageWarning: No data was collected. (no-data-collected); see ...
$ coverage report -m
Name          Stmts   Miss  Cover   Missing
-------------------------------------------
exporter.py      13     13     0%   1-17

The warning is a clue. The pytest process never imported exporter.py, so it collected no data for it, and the 0% comes from static analysis of a file that was never measured in the process that ran it.

Fix the measurement, then read the report again#

Coverage.py's [run] patch setting has a subprocess option for this case. The configuration reference says: "Python sub-processes normally won't get coverage measurement. This patch configures Python to start coverage automatically", for processes started through subprocess, os.system and the exec and spawn functions. It also turns on parallel data files and "will require combining data files before reporting." Configuration reference, 7.17.5

$ cat .coveragerc
[run]
source = .
omit = test_*.py
patch = subprocess
$ coverage run -m pytest -q
1 passed in 0.14s
.../coverage/control.py:964: CoverageWarning: No data was collected. (no-data-collected); see ...
$ ls -a | grep '^.coverage'
.coverage.vm.pid12794.XivinqZx.H54nJ9V0Lsth
.coverage.vm.pid12795.XhSHlBkx.Hawqc5NMgJdh
.coveragerc
$ coverage combine
Combined 2 files
$ coverage report -m
Name          Stmts   Miss  Cover   Missing
-------------------------------------------
exporter.py      13      2    85%   8-9

The same test, unchanged, moves the exporter from 0% to 85%. The warning still prints because the pytest process itself ran no exporter code; the data came from the second process. So the warning alone does not show the measurement is broken. The process count and the combined report do.

This finding often appears after a dependency upgrade rather than a code change. The pytest-cov documentation records that "Subprocess support was removed in pytest-cov 7.0 due to various complexities resulting from coverage's own subprocess support" and asks projects to set patch = subprocess instead. pytest-cov 7.1.0, subprocess support A suite whose subprocesses pytest-cov measured before 7.0 can lose that coverage on upgrade with no test removed. Programs that use multiprocessing need different settings, concurrency = multiprocessing and sigterm, which the same processes page describes; this example did not exercise them.

Code that ran before measurement started#

The second cause is start order. The coverage.py FAQ answers the symptom directly: when function bodies show as executed but their def lines do not, "it's because coverage.py has started after the functions are defined." FAQ, 7.17.5 With pytest-cov the usual trigger is a pytest plugin that imports the code under test. Its documentation says pytest "doesn't allow controlling the order in which the plugins load" and advises: "You should change your test invocations to use coverage run -m pytest ... instead." pytest-cov 7.1.0, plugin coverage

This constructed reproduction loads a one-line plugin, myplugin.py, containing import exporter, and a test that calls exporter.main() in process. Under pytest-cov 7.1.0 the imports and the def line are missing although the body is covered:

$ PYTHONPATH=. pytest -q -p myplugin --cov=. --cov-report=term-missing
Name           Stmts   Miss  Cover   Missing
exporter.py       13      7    46%   1-5, 8-9, 16-17
1 passed in 0.03s

Run the same tests under coverage run, which starts measurement before pytest loads anything:

$ PYTHONPATH=. coverage run --source=. -m pytest -q -p myplugin
1 passed in 0.01s
$ coverage report -m --include=exporter.py
Name          Stmts   Miss  Cover   Missing
-------------------------------------------
exporter.py      13      3    77%   8-9, 17

Lines 1 to 5 and 16 move to covered. A missed def, import or class line next to a covered body is the signature of this cause, and a test cannot fix it, because a test runs after the import has happened.

The disconfirmation: lines that truly never ran#

After both fixes, lines 8 and 9 are still missed in every run. They are the empty-input path, and no test sends empty input. Before you write the test, confirm with a tracer that does not depend on coverage's process setup. The standard library's trace module has a --missing option that will "mark lines which were not executed with >>>>>>". trace, Python 3.11.18 Replaying the test's input through it:

$ printf 'a=1\nb=2\n' | python -m trace --count --missing -C tr exporter.py
key,value
a,1
b,2
$ sed -n 5,13p tr/exporter.cover
    1: def main(argv):
    4:     rows = [line.split("=", 1) for line in sys.stdin.read().splitlines() if line]
    1:     if not rows:
>>>>>>         print("nothing to export", file=sys.stderr)
>>>>>>         return 2
    1:     writer = csv.writer(sys.stdout)
    1:     writer.writerow(["key", "value"])
    1:     writer.writerows(rows)
    1:     return 0

Two independent measurements agree that lines 8 and 9 never ran, so this finding is real, and the fix is a test that sends empty input and asserts the exit status 2. Line 17 under coverage run is the other true miss: the in-process test calls main() directly, so the __main__ guard's body does not run there. In the first example, which runs the file as a script, the patched run covers it.

Decide what the missed line needs#

What the finding saysEvidence to collectDecision
A whole file at 0% although a test checks its outputWhether the test starts a subprocess; the no-data-collected warning; the number of .coverage.* filesSet patch = subprocess, run coverage combine, and read the report again before writing tests
Coverage dropped after a pytest-cov upgradeThe pytest-cov version and whether tests spawn Python processesFix the configuration; record that no test was removed
def, import or class lines missed beside covered bodiesWhether a plugin or conftest imports the package; a run under coverage run -m pytestChange how coverage starts; no new test
Lines still missed after the measurement is fixedA second tracer, or a temporary print, on the same inputWrite a test for that path and assert its result
Lines missed in code that only runs in a multiprocessing workerconcurrency = multiprocessing, sigterm, and whether the pool is closed and joinedFix the settings and shutdown first; then treat the remainder as real

When the line is reported covered and the question is whether any test checks it, the guide to covered but unasserted lines applies. When a reviewer, rather than a coverage gate, asks for a test, the guide to "add a test" comments covers that request.

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