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

TDD, Mocking, and Test Organization with pytest

Python TestingTest StrategyđŸŸĸ Free Lesson

TDD, Mocking, and Test Organization with pytest

A test suite earns trust the same way a compiler does — by being boring, fast, and unmistakably wrong when the code is wrong. Suites lose that trust gradually: a test that fails on Mondays gets marked flaky, a test that asserts nothing gets deleted, and soon the whole run becomes a formality people click through before merging. The fixes are structural rather than clever. Write the test before the code so the design is shaped by how it will be verified, isolate the outside world behind a boundary you can substitute, and organize files so that a failure names the broken behaviour instead of the broken implementation detail.

This lesson covers the working practices that keep a pytest suite useful at ten tests and at ten thousand: the red-green-refactor loop, fixture scoping, mock boundaries, parametrisation, and a layout that lets you find the failing test by its name.


Red, green, refactor: why the order is the design

Test-driven development is often sold as a coverage trick, but its real product is an API that is pleasant to call. Writing the test first forces you to decide what the function is called, what it accepts, what it returns, and what happens on the error path — before you are committed to an implementation. The cycle is short and deliberately uncomfortable: add a test that cannot pass, write the least code that makes it pass, then improve the code with the test standing guard.

python
# test_orders.py — written first, fails with ImportError
import pytest
from myapp.pricing import total_for

@pytest.mark.parametrize(
    "items, expected",
    [
        ([], 0.0),
        ([("widget", 2, 5.0)], 10.0),
        ([("widget", 2, 5.0), ("gadget", 1, 3.5)], 13.5),
        ([("widget", 3, 5.0)], 15.0),          # placeholder: discount not implemented
    ],
)
def test_total_for(items, expected):
    assert total_for(items) == pytest.approx(expected)

The empty-list case in that parametrisation is not filler. Edge cases written at the same time as the happy path are cheap; retrofitting them later means redesigning the function to have somewhere to put them.

Fixtures: explicit setup, visible scope

Fixtures replace the setUp methods and global mutables of older frameworks with named, composable objects. The scope argument decides how long a fixture lives: function scope rebuilds state for every test, session scope builds once per run, and module scope sits in between. Choose the narrowest scope that keeps the suite fast — broad scopes are a performance optimisation that silently introduces shared state between tests.

python
import pytest

@pytest.fixture
def cart():
    from myapp.cart import Cart
    return Cart()                       # fresh instance per test

@pytest.fixture(scope="session")
def price_book(tmp_path_factory):
    path = tmp_path_factory.mktemp("data") / "prices.csv"
    path.write_text("sku,price\nA,5.00\nB,3.50\n", encoding="utf-8")
    return PriceBook.load(path)          # built once, reused everywhere

def test_empty_cart_totals_zero(cart):
    assert cart.total() == 0.0

def test_adding_lines_updates_total(cart, price_book):
    cart.add("A", 2, price_book)
    assert cart.total() == 10.0

Two habits prevent fixture rot. Keep fixtures small enough to read at a glance, and give them names that describe the state they provide rather than the function that builds it. A fixture called price_book tells a reader what the test depends on; a fixture called setup_stuff tells them nothing.

Mock only the boundary you do not own

Mocking is a tool for excluding the outside world, not for avoiding design work. Mock the network call, the clock, the database driver, the file system — things whose behaviour you cannot control — and never mock your own domain objects, because then you are testing the mock instead of the logic. Over-mocking is the reason so many suites pass while the application is broken: every collaborator is a stub, so the test verifies only that you wired the stubs together the way you expected.

python
from unittest.mock import patch, MagicMock

@patch("myapp.service.requests.get")
def test_service_marks_order_paid(mock_get):
    mock_get.return_value = MagicMock(
        status_code=200,
        json=lambda: {"status": "paid", "reference": "abc123"},
    )

    result = myapp.service.settle(order_id=41)

    assert result.state == "paid"
    mock_get.assert_called_once_with(
        "https://payments.internal/orders/41", timeout=5
    )

@patch("myapp.service.requests.get")
def test_service_raises_on_timeout(mock_get):
    import requests as rq
    mock_get.side_effect = rq.Timeout("too slow")

    with pytest.raises(PaymentUnavailable):
        myapp.service.settle(order_id=41)

Note the second test: it asserts the error contract, which is the half of behaviour most suites skip. If your code has a retry path, a timeout path, and a malformed-response path, each of those deserves a test — they are the paths production actually walks down.

Parametrise behaviour, not copy-paste

Repetition in tests hides the one line that differs, and it makes a change to the fixture setup a fifty-line edit. pytest.mark.parametrize keeps the scenario table visible and names each case in the failure output, so you learn exactly which input broke.

TechniqueUse whenAvoid when
parametrizeSame logic, many inputs or expectationsThe cases need very different setup
Fixture factoryObjects must be built with varying attributesA single fixed object would do
pytest.mark.skipifBehaviour genuinely absent on this platformThe test is temporarily failing
pytest.xfailKnown bug with an expected failureYou want a passing mark to hide it
Sub-tests via pytest.param idsA handful of cases need readable namesEvery case would need a custom id
python
import pytest

CASES = [
    pytest.param("STANDARD10", 100.0, 90.0, id="standard-10pct"),
    pytest.param("VIP25", 100.0, 75.0, id="vip-25pct"),
    pytest.param("EXPIRED", 100.0, 100.0, id="expired-code-ignored"),
    pytest.param("UNKNOWN", 100.0, 100.0, id="unknown-code-ignored"),
]

@pytest.mark.parametrize("code, subtotal, expected", CASES)
def test_discount_code(code, subtotal, expected):
    basket = Basket(subtotal)
    assert basket.apply_code(code) == pytest.approx(expected)

When a parametrised case fails, pytest prints its id in the test name — that is the whole point. test_discount_code[expired-code-ignored] tells you more than a stack trace ever will.

Organise by behaviour so failures are findable

A practical layout mirrors the way you talk about the system: one file per module or feature, with the test names describing observable behaviour rather than method names. test_totals_after_discount tells a reader what regressed; test_total_method does not. Keep helpers in a conftest.py near the tests that use them, and resist the urge to build a shared "test utilities" package that eventually becomes an undocumented second framework.

Architecture Diagram
tests/
  conftest.py            # shared fixtures: price_book, client, freezer
  pricing/
    test_total_for.py
    test_discounts.py
  cart/
    test_adding_items.py
    test_persistence.py
  service/
    test_settle_order.py

Each directory should be runnable on its own with pytest tests/pricing, which keeps feedback local while you are working in one area and makes it obvious which suite a new test belongs in.

Boundaries between files matter as much as names. A test that reaches into another module's private helper creates a coupling you did not intend: refactoring that helper then breaks tests in a directory that has nothing to do with the change. When you notice a test importing two layers deep to construct its subject, that is a signal the object is hard to build — fix the factory or the constructor rather than importing your way to a solution.

Keeping the suite fast enough to always run

A suite that takes six minutes gets run before release instead of before every commit, and the difference in feedback quality is enormous. Targets worth holding: the whole suite under two minutes on a developer machine, no test doing real network I/O, database fixtures scoped narrowly or replaced with an in-memory double, and slow tests marked so they can be excluded with a -m "not slow" flag during development.

Speed and isolation reinforce each other. Tests that share state take longer to reason about and longer to debug when they fail, because the failing assertion may be caused by a test that ran three files earlier. Make every test independent, make every failure specific, and the suite stays something developers trust rather than something they tolerate.

Common Mistakes

Mocking your own domain classes so the test passes without real logic

Fix: Mock only external boundaries — HTTP, clock, filesystem — and let domain objects run for real

Session-scoped fixtures that mutate shared state

Fix: Drop to function scope, or return a factory so each test gets a fresh instance

Asserting only the happy path

Fix: Add cases for timeouts, empty inputs, and malformed responses alongside every success test

Copy-pasted tests that differ by one constant

Fix: Collapse them into a parametrised table with descriptive ids

Test names that mirror method names

Fix: Name tests after the behaviour they prove so failures are self-explanatory

Best Practices

  • Write the failing test first, then the minimum code that satisfies it
  • Keep fixtures narrow in scope and descriptive in name; build state as close to the test as possible
  • Run the suite on every commit and keep it under two minutes on a laptop
  • Mark genuinely slow tests instead of letting the whole suite drift upward
  • Treat a skipped or xfailed test as debt that needs a linked issue

Key Takeaways

  • Red-green-refactor is a design tool first and a safety net second
  • Fixture scope is a correctness decision, not only a performance one
  • Mock external boundaries; never mock the code under test
  • Parametrisation keeps scenario tables visible and failure names readable
  • A suite is only valuable if it is fast and isolated enough to run constantly
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