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

pytest Architecture: Layout, Fixtures, Mocks

Python TestingđŸŸĸ Free Lesson

pytest Architecture: Layout, Fixtures, Mocks

A test suite that works at two hundred tests often collapses at two thousand. The collapse is rarely about assertions. It is about structure: fixtures defined in places nobody can find, tests that share hidden state through module-level objects, mocks pinned to private internals so that every refactor breaks twenty files, and a suite so slow that people stop running it locally and let CI discover the damage.

Architecture is what prevents that. It means deciding where tests live, which layer owns each fixture, what a test is allowed to touch, and where the boundary of a mock sits. Done well, the suite becomes a set of small, independent checks that communicate intent. Done poorly, it becomes a second application that must be maintained alongside the first.

What You'll Learn

  • 1Lay out a test tree whose structure mirrors the package it protects
  • 2Layer conftest files so fixtures are visible exactly where they are needed
  • 3Pick between monkeypatch, mock.patch, and a hand-written fake
  • 4Control suite runtime through scopes, markers, and isolation instead of skipping tests

Where tests live and what each layer owns

Start with a layout that answers questions without opening files. Unit tests sit close to the modules they exercise and touch nothing outside the process. Integration tests exercise real boundaries such as a database, a filesystem path, or an HTTP server, and they are marked so they can be selected or excluded deliberately. Shared fixtures live in the nearest conftest.py, never in a helpers module that tests import directly, because conftest is where pytest's discovery rules already look.

Architecture Diagram
tests/
    conftest.py            # app-wide fixtures: config, logging, temp roots
    unit/
        conftest.py        # fast, dependency-free fixtures
        test_pricing.py
        test_matching.py
    integration/
        conftest.py        # database, server, and file-backed fixtures
        test_checkout_api.py
    factories/
        __init__.py
        builders.py        # plain functions that build valid test data

Two rules keep this stable. Test file names mirror the package layout so a failing file points at the code instantly. Factories are plain functions returning dictionaries or dataclasses, not fixtures, so they can be called inside loops and parametrizations without pytest ceremony.

The test pyramid is a budget, not a religion. A healthy suite is mostly fast unit tests with a smaller band of integration tests that prove the wiring. If integration tests outnumber unit tests by a wide margin, the suite will be slow, flaky, and hard to debug, because every failure requires ruling out the infrastructure first.

Fixtures, scope, and the layering rule

A fixture is a dependency injection point. It exists so that setup code lives in one place and teardown is guaranteed. The scope argument decides how long the object lives: function scope is the default and the safest, class and module scope reuse expensive resources across many tests, and session scope is reserved for genuinely immutable, cheap-to-share things like a configuration object or a temporary directory tree.

Scope is a correctness decision, not only a speed one. A module-scoped database fixture shared by tests that mutate rows couples those tests together; the second one to run inherits the first one's leftovers. Reach for a wider scope only when the resource is read-only or when each test resets what it touches.

python
import pytest
from decimal import Decimal


@pytest.fixture(scope="session")
def price_book():
    return {"SKU-1": Decimal("9.99"), "SKU-2": Decimal("24.50")}


@pytest.fixture
def cart(price_book):
    return {"lines": [{"sku": "SKU-1", "qty": 2}], "book": price_book}


def line_total(cart):
    line = cart["lines"][0]
    return cart["book"][line["sku"]] * line["qty"]


def test_line_total(cart):
    assert line_total(cart) == Decimal("19.98")


@pytest.mark.parametrize("qty,expected", [(1, Decimal("9.99")), (3, Decimal("29.97"))])
def test_parametrized_totals(price_book, qty, expected):
    cart = {"lines": [{"sku": "SKU-1", "qty": qty}], "book": price_book}
    assert line_total(cart) == expected

Parametrization is the cheapest way to grow coverage without growing code. One test body, many cases, and pytest reports each case separately so a single failing combination is obvious in the output.

Choosing where the mock belongs

Mocking is about boundaries. Mock the thing on the far side of the boundary you are not testing: the network client, the clock, the random source, the database session. Mocking your own module's internals couples the test to the implementation and guarantees a refactor tax.

TechniqueBest forWeakness
monkeypatch.setattrSwapping one attribute for the duration of a testRequires knowing the attribute path
unittest.mock.patch as a decoratorPatching an import target with automatic cleanupTarget string must match the name used by the code under test
Hand-written fakeCollections of methods, or tests that need assertions on a whole protocolMore code to maintain
Dependency injectionAnything constructed inside the function under testRequires the production code to accept it

The most common patching bug is patching the wrong name. If the code under test does from client import fetch, patching client.fetch changes nothing, because the module already holds its own reference; the correct target is the name in the module that performs the lookup. When in doubt, patch where the name is looked up, not where it was defined.

python
from unittest.mock import patch, MagicMock


def fetch_profile(user_id, client):
    payload = client.get(f"/users/{user_id}")
    return {"id": user_id, "name": payload["name"]}


@patch("myapp.service.client")
def test_fetch_profile(mock_client_module):
    fake = MagicMock()
    fake.get.return_value = {"name": "Ada"}
    mock_client_module.Client.return_value = fake

    result = fetch_profile(7, fake)

    assert result == {"id": 7, "name": "Ada"}
    fake.get.assert_called_once_with("/users/7")

Assert on behavior and observable output, not on how many internal methods were touched. A test that verifies inner_helper was called twice is describing the implementation; a test that verifies the returned value and the single outbound request is describing the contract.

Isolation is a property you design for

Tests that pass alone and fail together are reporting a real defect in the suite rather than in the product, and the defect is almost always shared state. Shared state takes many forms: a module-level dictionary that a fixture fills and a later test empties, a temporary file written to a fixed path, a class attribute patched in one test and left patched for the rest of the module, or a database sequence whose starting value depends on what ran before.

The design response is to give each test the smallest environment that supports it. A fixture that mutates must be function-scoped. Patches applied by hand should be cleaned up in a finally block, or replaced with the monkeypatch fixture that guarantees restoration. Fixed paths become unique temporary directories. Where a test genuinely needs order, it should say so with a marker rather than relying on the accidental order of file discovery, because that order changes when files are renamed.

Parallel execution is the fastest way to expose hidden coupling. Running the suite with a worker pool will surface any test that writes to a shared path or depends on another test having run first. That is uncomfortable the first time and invaluable afterwards, because it converts a latent source of flaky failures into a hard error you can fix once.

Assertions that describe the contract

An assertion is a specification of what the caller may rely on. Assertions on returned values, emitted events, and outbound requests describe the contract; assertions on internal attributes and private call sequences describe the implementation, and they turn every harmless refactor into a failure. The practical test is to ask whether a developer could rewrite the inside of the function, keep the same behavior, and keep the test green. If not, the test is coupled to something it should not be.

Precision matters as much as placement. A bare truthiness check proves almost nothing about a returned dictionary; comparing the whole structure proves exactly what is expected and prints a readable diff when it fails. For floating-point results, compare with a tolerance instead of equality, because the last bit varies with platform and compiler. For unordered results, sort before comparing or compare as sets, and say in the test name which guarantee you are asserting.

Keeping the suite fast and trustworthy

Speed is a feature of the suite. If the full run takes more than a minute or two, developers stop running it before committing, and feedback arrives too late to be useful. Mark slow tests, run the fast subset by default, and put the expensive ones behind an explicit marker selection in continuous integration.

Flakiness destroys trust faster than slowness. The usual sources are shared mutable state between tests, dependence on wall-clock time, network calls that are not mocked, and unordered iteration over a set or a database result. Fix them at the source: give each test its own fixtures, freeze or inject time, mock the network, and assert on sorted output when order is not part of the contract.

Coverage numbers are a map, not a target. Uncovered lines tell you where to look for gaps; chasing one hundred percent pulls effort toward trivial getters and away from the branches that actually fail in production. Read coverage as a list of questions, then write the test only if the answer matters.

Common Mistakes

Sharing a mutable module-scoped fixture across tests that modify it

Fix: Keep mutable state at function scope, or have every test reset the resource it touches before asserting

Patching the module where a function was defined instead of where it is looked up

Fix: Patch the name in the namespace the code under test actually reads from

Asserting on internal call sequences rather than outcomes

Fix: Assert on returned values, emitted events, and requests that leave the process; leave internals free to change

Letting tests reach the real network because it is usually fast

Fix: Mock the boundary or run it behind an integration marker so the default suite stays hermetic

Best Practices

  • Mirror the package layout inside the test tree so failures point at code directly
  • Put each fixture in the nearest conftest where it is used and no closer
  • Prefer parametrization over copy-pasted test bodies for variation
  • Mark slow or environment-dependent tests and keep the default run fast
  • Read coverage as a list of uncovered branches, never as a score to maximize

Interview Questions

Q1: What is the difference between monkeypatch and mock.patch?

monkeypatch is a pytest fixture that swaps an attribute and restores it at test end, scoped to the test automatically. mock.patch patches a target by dotted name and can be used as a decorator or context manager; it fails silently into the wrong target if the name is mistyped.

Q2: Why should a test avoid asserting on private attributes?

Private attributes are free to change during refactoring. Assertions on them convert harmless internal edits into failures, which trains the team to distrust the suite.

Q3: When is a hand-written fake better than a mock?

When the boundary has several methods, when the test needs to behave rather than be inspected, or when a mock's call spec would leak the production implementation into the test.

Key Takeaways

  • Structure the suite like the package so failures localize instantly
  • Scope fixtures by mutation: narrow for anything a test changes
  • Mock at the process boundary, never inside the unit under test
  • Parametrize for coverage, mark for speed, and keep the default run hermetic
  • Treat flakiness as a bug in the test's environment, not something to retry away
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