Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Worked example · 15 min · revision 3

Reading Coverage and Choosing Test Levels

Run a branch-coverage report over the reading-list suite, decode line versus branch numbers, close one real gap and consciously explain the ones you leave.

Contentsand lesson path

What you will learn

  • Choose the test level (unit, integration, end-to-end) for a behavior and use a coverage report to find untested branches.

Prerequisites: Python Foundations

01. The task

The endpoint lab left a service with 22 passing tests, and a question every suite must answer eventually: what do these tests actually reach? Coverage answers it by recording, while the suite runs, which lines and branches of the code were executed. Coverage is a map of what is untested, not a score to maximise — and reading it well is what this worked example practises.

The work runs on the project from the endpoint lab. Add the plugin that collects the numbers (7.1.0 used here), then ask for a branch report:

Terminal
uv pip install --python .venv/bin/python pytest-cov==7.1.0
.venv/bin/pytest -q --cov=app --cov-branch --cov-report=term-missing
Expected output (the coverage table; a line with the run time follows)
Name                Stmts   Miss Branch BrPart  Cover   Missing
---------------------------------------------------------------
app/main.py            31      2      6      2    89%   28, 38, 51->50
app/repository.py      18      2      0      0    89%   15, 18
app/validation.py      17      0      6      0   100%
---------------------------------------------------------------
TOTAL                  66      4     12      2    92%

02. Step 1: line coverage can hide untaken turns

The Missing column mixes two notations: plain line numbers, and pairs like 51->50 joined by an arrow. The distinction is line coverage versus branch coverage. Line coverage asks: did this line ever run? Branch coverage also asks: did each way through every decision run? A one-line difference in a tiny function shows why that matters:

Python · shelf.py
def pick_label(copies: int) -> str:
    label = "on the shelf"
    if copies == 0:
        label = "on the wait list"
    return label

Give it a single test, for the zero-copies case only, and run the same kind of report in that folder: pytest -q --cov=shelf --cov-branch --cov-report=term-missing.

Python · test_shelf.py
from shelf import pick_label


def test_no_copies_goes_on_the_wait_list() -> None:
    assert pick_label(0) == "on the wait list"
Expected output (the coverage table; a line with the run time follows)
Name       Stmts   Miss Branch BrPart  Cover   Missing
------------------------------------------------------
shelf.py       5      0      2      1    86%   3->5
------------------------------------------------------
TOTAL          5      0      2      1    86%

Every line ran — Miss is zero — because the single test took the if branch. But the test never once skipped the if, and the arrow 3->5 says so: the jump from line 3 straight to line 5, the leave-it-on-the-shelf path, never happened. A reader who only saw "100% line coverage" would believe the function fully tested; branch coverage refuses to let that pass quietly. Line counts what ran; branch counts what could happen.

03. Step 2: act on the report

Back in the reading-list report, four entries ask for decisions. Two are real gaps to close now:

  • main.py:38 is the 409 CONFLICT raise for a duplicate book. Nothing tests it, yet a client's retry button makes duplicates a daily event. Add a test for the behaviour.
  • main.py 51->50 is subtler. In read_book, the branch "checked a book, it did not match, moved on" never ran: the 200 test matched the only book immediately, and the 404 test searched an empty repository, so the loop body never executed at all. The report just exposed that the 404 test never proved skipping past a stored book works.
Python · tests/test_api.py (one test improved, one added)
def test_read_unknown_book_answers_404(client: TestClient) -> None:
    client.post(
        "/books", json={"title": "Refactoring", "author": "Martin Fowler"}
    )

    response = client.get("/books/unknown-slug")

    assert response.status_code == 404
    assert response.json() == {"detail": "book not found"}


def test_adding_the_same_book_twice_answers_409(
    client: TestClient,
) -> None:
    payload = {"title": "Refactoring", "author": "Martin Fowler"}
    first = client.post("/books", json=payload)

    second = client.post("/books", json=payload)

    assert first.status_code == 201
    assert second.status_code == 409
    assert second.json() == {"detail": "book already in the list"}
Expected output (rerun, the table rows; 23 tests now pass)
app/main.py            31      1      6      0    97%   28
app/repository.py      18      2      0      0    89%   15, 18
app/validation.py      17      0      6      0   100%
TOTAL                  66      3     12      0    96%

The loop branch and the 409 raise are gone from the report. What remains is deliberate, and you should be able to say why for each:

  • main.py:28 returns the default repository wiring. Under tests the dependency override replaces this wiring with a fresh isolated fake, so exercising the production wiring belongs to integration tests that verify real component assembly, not a unit-suite gap.
  • repository.py:15,18 are the raise NotImplementedError bodies of the base class. They exist to declare the interface; the fake subclasses them. Nothing is untested there — the behaviour is tested through the fake.

Explaining your remaining gaps, rather than chasing each of them, is the deliverable the practice task for this skill asks for.

04. Step 3: the report as a map, the pyramid as the route

A coverage report also tells you where each behaviour lives. validation.py at 100% says every line and branch of the slug and rating rules ran; the unit tests from the earlier lessons are what exercise those rules directly, so they live at unit level, in fast tests with exact failure messages. main.py below 100% tells you which wiring is not exercised in-process. And some checks the report cannot even see as code: whether the deployed service starts, or whether a browser journey works end to end — those belong to the levels this skill's first lesson mapped out, with journeys driven by real browsers in the frontend end-to-end lesson.

The pairing to hold onto: when a branch is uncovered, first decide which level should own it. A discount rule belongs at unit level; a database constraint belongs in an integration test; a checkout journey belongs end to end. Only then write the test. Pushing checks to the cheapest level that can catch the regression keeps the suite fast and its failures precise, which is the habit that makes coverage a planning tool rather than a scoreboard.

How often to look follows from that. The suite runs on every save and every push; the coverage report does not need to. Most teams run it on demand while planning work, and let the continuous-integration pipeline record it for each branch, so a change that darkens a region shows up in review. The report you want is the one you can read: file by file, with a Missing column narrow enough that every entry is either a test you owe or a sentence you can say out loud.

05. Misreading the number

06. Check your understanding

Practice check · 3 questions

Reading reports, choosing levels

Three moments with a coverage report in hand.

Q1. Branch coverage says validation.py is fully covered, yet a reader finds a title that crashes the endpoint. What did 100% actually mean?
Q2. The only gap left in main.py is the line returning the shared production repository. What is the sound response?
Q3. A report shows the 422 branch runs only inside one 40-second browser journey. Where should the check live?
Practice only: not graded, not saved, not evidence.

07. Apply it

Finish the practice task for this skill: run a branch-coverage report over your suite and, for every gap, either close it with a test at the level that can see it or write one sentence explaining why it stays. Then find one check that lives at the wrong level — a pure rule tested through the whole app, or wiring only exercised by a slow journey — and move it. Re-run the report and note what changed besides the number.

08. Review prompt

Without looking back: explain the difference between line and branch coverage, and what the notation 51->50 names in a Missing column. Describe a gap you would close immediately and one you would leave, with the reason for each. Finally, say why a high coverage percentage cannot certify that inputs are handled, and what question you should ask before writing any test for an uncovered branch.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check