🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Coverage, Mocking Boundaries, and Test Smells

Python TestingđŸŸĸ Free Lesson

Coverage, Mocking Boundaries, and Test Smells

A test suite is a confidence instrument, and confidence is only useful when it is calibrated. Two failures dominate real projects: a suite that reports ninety-five percent coverage while missing the branch that corrupts production data, and a suite full of mocks that agree with the implementation so completely it can never fail. Both problems are structural rather than tactical, and both are visible as soon as you read coverage as evidence instead of as a score.

What You'll Learn

  • 1Explain what statement and branch coverage measure and what neither measures
  • 2Configure coverage so the report excludes noise without hiding real gaps
  • 3Place mocks at the seam your code owns rather than inside it
  • 4Recognise the test smells that make a suite slow, brittle, and falsely green

What coverage actually measures

Statement coverage answers one narrow question: which lines executed while the tests ran. A line that ran may still have produced the wrong answer, and a line that did not run may be unreachable defensive code. Branch coverage is stricter — it tracks which side of every if, match, and, or, and comprehension condition was taken — and it catches the classic gap where the happy path runs and the error path never does.

Beyond those two sit stronger ideas that no default report gives you. Condition coverage checks each sub-expression of a compound condition independently. Mutation testing flips the source — changes an operator, deletes an assertion — and runs the suite to see whether the tests notice; a survivor is a test that passes without verifying anything. The honest reading of any coverage number is therefore an upper bound on what has been exercised, never a lower bound on what is correct.

MeasureWhat it tracksCatchesBlind to
StatementExecuted linesDead, untested codeWrong values on executed lines
BranchSides of each conditionUntaken error pathsSemantics inside a taken path
ConditionSub-expressionsShort-circuited operandsOrdering between conditions
MutationSurviving code changesVacuous assertionsEquivalent mutants

Configuring the report so it means something

Default reports drown real gaps under __repr__, raise NotImplementedError, and protocol boilerplate you deliberately do not test. Configure exclusions once, in the project, so numbers stay comparable between contributors.

# .coveragerc
[run]
source = myapp
branch = True
omit =
    tests/*
    myapp/cli/*

[report]
exclude_lines =
    pragma: no cover
    if TYPE_CHECKING:
    raise NotImplementedError
    if __name__ == .__main__.:
precision = 1
show_missing = True
skip_covered = True

Turn branch = True on and keep it on; a suite that has never measured branches cannot tell you which error paths are missing. show_missing is what makes the report actionable, because "line 84 not covered" leads to a conversation while "87%" leads to a status update. The habit worth building is to review coverage diffs on the pull request rather than the absolute number: new code without new coverage is a discussion, whereas a stable legacy module at sixty percent is often a rational equilibrium.

Where the mock belongs

Mocks exist to isolate the unit under test from a dependency you do not control — the network, the clock, the filesystem, another team's service. The seam is the boundary your own code defines: patch the client class you wrote, not the third-party call it makes internally, and never patch the function you are testing.

python
import pytest
from unittest.mock import patch

from myapp.orders import PriceQuote
from myapp import shipping


class FakeCarrier:
    def __init__(self, rate):
        self.rate = rate

    def quote(self, weight_kg):
        return self.rate * weight_kg


def test_quote_uses_carrier_rate():
    with patch.object(shipping, "carrier", FakeCarrier(rate=2.5)):
        quote = PriceQuote(weight_kg=4)
    assert quote.total == 10.0


def test_quote_rejects_negative_weight():
    with patch.object(shipping, "carrier", FakeCarrier(rate=2.5)):
        with pytest.raises(ValueError, match="weight"):
            PriceQuote(weight_kg=-1)


def test_missing_carrier_is_a_configuration_error():
    with patch.object(shipping, "carrier", None):
        with pytest.raises(RuntimeError, match="carrier"):
            PriceQuote(weight_kg=1)

Notice what is not mocked: the arithmetic inside PriceQuote, which is the thing being verified. A test that patches the module's own calculation and then asserts on a value produced by that calculation is circular. The other useful rule is that mocks should be dumb — a fake object with a return value, not a script that reimplements the dependency's logic. Once your mock has branching, it has become a second implementation waiting to drift.

Fixtures, parametrization, and where test data lives

Fixtures give you one place to express what a test needs, and parametrization lets a single assertion cover a table of cases. The strategy that scales is to keep fixtures small and composable: a factory fixture that builds a valid record with overridable fields beats a directory of copy-pasted dictionaries, and a fixture that yields rather than returns can set up and tear down in one place.

python
import pytest


@pytest.fixture
def make_order():
    counter = {"n": 0}

    def _make(**overrides):
        counter["n"] += 1
        defaults = {
            "ref": f"ORD-{counter['n']:04d}",
            "qty": 1,
            "unit_price": "9.99",
            "status": "pending",
        }
        defaults.update(overrides)
        return defaults

    return _make


@pytest.mark.parametrize("qty,expected", [(1, "9.99"), (3, "29.97"), (10, "99.90")])
def test_bulk_total(make_order, qty, expected):
    order = make_order(qty=qty)
    total = order["qty"] * float(order["unit_price"])
    assert f"{total:.2f}" == expected

Parametrized cases read as data, which makes it obvious when a colleague adds a row without an expectation. Keep the fixture returning a plain record rather than a live model instance when you can, so tests do not accidentally depend on database state they never intended to share.

Test smells that rot a suite

SmellSymptomThe fix
Assertion-free testPasses whatever happensAssert a value or an observable effect
Test touching the real networkFlaky CI, slow feedbackFake at your own client boundary
One test covering ten featuresFailure points at nothingSplit by behaviour, share fixtures
Setup duplicated across filesFixtures nobody trustsOne factory fixture, overridable fields
Mocks with branching logicA second implementation in the testDumb fakes; assert on your own code
Suite takes twenty minutesTests get skipped or ignoredMark slow tests, run fast subset first

The speed smell deserves special attention because it is self-reinforcing: a slow suite gets run less often, gaps accumulate, the next failure surprises everyone, and the response is to add more tests to an already slow suite. Time the suite in CI, publish the number, and treat a doubling as a defect.

Isolation, so a green run means something

A test that depends on whatever the previous test left behind is not a test, it is a sequence. Two sources of hidden state dominate: the database, where an uncommitted row from an earlier case changes a count assertion, and the module registry, where a patch that was never undone leaks into the next test. The fix for the first is transactional fixtures — each test runs inside a transaction that is rolled back on teardown, so the database starts from the same state every time and no test can observe another's writes. The fix for the second is context-managed patching: with patch(...) restores the original the moment the block exits, even when the body raises.

Global configuration deserves the same treatment. Environment variables, working directories, and random seeds are all ambient state; a fixture that sets and restores them makes runs reproducible, and a fixed seed turns a flaky property test into a reproducible one. When a test genuinely needs a fresh process — for interpreter-level state such as sys.modules caching — mark it, isolate it, and keep it out of the fast suite.

Organising tests so people actually read them

Mirror the package layout of the source so a failing path maps directly to a module, name files after the behaviour rather than the class, and prefer many small tests with one reason to fail over a few scenario scripts. Keep integration tests in their own directory with their own marker so the fast unit suite stays fast. Most importantly, make the failure message part of the design: an assertion that reports the expected and actual totals teaches the next reader more in five seconds than a stack trace ever will.

Common Mistakes

Treating a coverage percentage as a quality gate

Fix: Review the coverage diff on the pull request and read uncovered branches; the number alone rewards line-touching tests

Patching the third-party function your code calls deep inside

Fix: Patch the client object your own module owns, so the seam stays inside your code and survives library upgrades

Mocking the behaviour you are supposed to be asserting

Fix: Leave the unit under test real and fake only its dependencies; a mock that produces the expected answer proves nothing

Writing a test with no assertion because it 'exercises the code'

Fix: Assert an observable effect or use pytest.raises; an assertion-free test can only ever report a crash

Best Practices

  • Turn branch coverage on and keep show_missing enabled so gaps name their lines
  • Write a factory fixture once and parametrize over data instead of copying test cases
  • Keep mocks dumb: return values and raised exceptions, never branching logic
  • Separate slow integration tests with markers so the fast suite runs on every save
  • Assert values, not the absence of exceptions; assert on results a human would recognise from the ticket

Interview Questions

Q1: What does ninety percent statement coverage tell you?

That ninety percent of statements executed during the run. It says nothing about whether those statements produced correct results, and the uncovered ten percent may contain the only error path in the module.

Q2: Where should a mock be placed?

At the seam your code owns — the client class or function you wrote — never inside the unit under test and never so deep in a dependency that an upgrade silently breaks the test.

Q3: How does mutation testing differ from coverage?

Coverage asks what the tests executed; mutation testing asks whether the tests notice when the source is subtly broken. A surviving mutant is an assertion too weak to detect the change.

Q4: Why is a slow test suite a correctness problem?

Because it stops being run. Developers fall back to running a subset locally, so regressions outside the subset reach review and production, and the suite's reported confidence no longer matches reality.

Key Takeaways

  • Coverage is an upper bound on exercised code, not a measure of correctness
  • Branch coverage and coverage diffs are far more informative than a headline percentage
  • Mocks belong at the boundary your code owns, and they must be dumber than the code under test
  • Factory fixtures plus parametrization beat copy-pasted data and keep expectations visible
  • Suite speed is a quality attribute: a suite that takes too long stops being trusted and stops being run
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement