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

Property-Based Testing, Fixtures, and Smart Mocks

Python TestingAdvanced TestingđŸŸĸ Free Lesson

Property-Based Testing, Fixtures, and Smart Mocks

Example-based tests answer a narrow question: does the function behave on the inputs I thought of? Property-based testing answers a broader one — does this law hold for every input in a shape you can describe? — and then hands you the smallest counterexample it can find. That inversion changes what a test suite covers, because the generator explores combinations no human would enumerate: empty lists, duplicates, values at the boundary of an integer range, strings with unusual Unicode.

This lesson pairs that technique with the two other levers that decide whether an advanced suite stays trustworthy: fixtures with deliberately chosen lifecycles, and mocks that verify the boundary contract without hollowing out the code under test.


Properties, not just examples

A property is a statement that must be true for a whole class of inputs: sorting is idempotent, serialising then parsing returns the original value, adding an element to a set changes the membership test and nothing else. Writing these as properties multiplies coverage per line of test code, and — more importantly — encodes the invariant rather than the output of one lucky run.

python
from hypothesis import given, strategies as st, settings, HealthCheck

@given(st.lists(st.integers()))
@settings(max_examples=500, suppress_health_check=[HealthCheck.too_slow])
def test_sort_is_idempotent(values):
    once = sorted(values)
    assert sorted(once) == once

@given(st.text())
def test_roundtrip_json_string(value):
    import json
    assert json.loads(json.dumps(value)) == value

@given(st.dictionaries(st.text(min_size=1), st.integers(), min_size=0))
def test_merge_with_empty_is_identity(base):
    assert {**base, **{}} == base

The first property is worth pausing on: it would take hundreds of hand-written examples to convince yourself that sorting twice never changes the result, and even then you would not have covered adversarial inputs. As a property it is one line, and the framework supplies the adversarial inputs for free.

Strategies, shrinking, and the art of a readable failure

A strategy is a recipe for generating values, and composing them is where the technique earns its keep. st.lists(...) around another strategy, st.one_of for union types, st.builds for object graphs, and st.fixed_dictionaries for structured payloads let you describe the shape of valid domain data in a few lines. Crucially, when a generated case fails, the engine shrinks it — the failing list becomes shorter, the number moves toward zero, the string loses characters — until it presents a minimal reproducer you can paste into a bug report.

python
from hypothesis import given, strategies as st, example

@given(
    st.lists(st.integers(min_value=-1000, max_value=1000), min_size=1),
    st.integers(min_value=-1000, max_value=1000),
)
@example(values=[0], target=0)
def test_binary_search_finds_every_present_element(values, target):
    ordered = sorted(set(values))
    index = binary_search(ordered, target)
    if target in ordered:
        assert ordered[index] == target
    else:
        assert index == -1

Three habits keep properties honest. Constrain the strategy to values your domain accepts, so the test does not spend its budget on inputs you would reject at the boundary anyway. Use @example to pin any counterexample the engine has already found — shrinking is powerful, but a pinned regression case guarantees the bug stays covered even if the generator changes. And avoid properties that merely restate the implementation; if the assertion could be derived from the code under test by reading it aloud, it proves nothing.

Fixture lifecycles and where state leaks

Advanced suites live or die on fixture discipline. The scope argument controls how long a fixture object survives, and the decision is about state, not speed: a session-scoped database that any test may mutate is a cross-test dependency disguised as an optimisation. The safe pattern is to share immutable or read-only fixtures broadly and build mutable state as narrowly as the test needs.

python
import pytest

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

@pytest.fixture
def ledger(db_session):
    ledger = Ledger(session=db_session)
    yield ledger
    db_session.rollback()                # every test starts from a clean slate

@pytest.fixture
def frozen_clock(monkeypatch):
    class Clock:
        def now(self):
            return datetime(2024, 3, 2, 12, 0, 0)
    monkeypatch.setattr("myapp.timekeeper.datetime", Clock)

The yield fixture is the workhorse: everything before the yield is setup, everything after is teardown, and teardown runs even when the test raises. monkeypatch is even better for substitution because it reverts automatically — a manual setattr in setup that is forgotten in teardown is one of the classic sources of order-dependent flakiness.

Mocks that describe the contract

Mocking gets a bad reputation because it is usually done at the wrong layer. Mock the things you do not own — HTTP clients, clocks, filesystems, third-party SDKs — and let your own domain objects execute for real; otherwise the test verifies only the wiring you just wrote. Beyond the basics, three features make mocks precise: autospec mirrors the real object's signature, side_effect simulates sequences and exceptions, and explicit call assertions turn an assumed protocol into a checked one.

python
from unittest.mock import patch, MagicMock, call

@patch("myapp.billing.gateway.capture", autospec=True)
def test_capture_called_once_with_idempotency_key(mock_capture):
    mock_capture.return_value = MagicMock(status="captured")

    receipt = billing.capture_amount(order_id=41, amount=1250, key="idem-9")

    assert receipt.status == "captured"
    mock_capture.assert_called_once_with(
        amount=1250, currency="USD", idempotency_key="idem-9"
    )

@patch("myapp.billing.gateway.capture", autospec=True)
def test_capture_retries_then_succeeds(mock_capture):
    import requests as rq
    mock_capture.side_effect = [
        rq.Timeout("first"),
        MagicMock(status="captured"),
    ]

    receipt = billing.capture_amount(order_id=41, amount=1250, key="idem-9")

    assert receipt.status == "captured"
    assert mock_capture.call_count == 2
    assert mock_capture.call_args_list[0] == mock_capture.call_args_list[1]

The second test encodes something hand-written assertions often miss: the retry must reuse the same idempotency key, or a flaky network produces double charges. Comparing call_args_list entries expresses that requirement directly, and it would fail the moment a retry generated a fresh key.

Hunting mutants rather than lines

Line coverage says which code ran; it does not say whether any test would notice if that code changed. Mutation testing closes the gap by introducing small faults — swapping an operator, deleting a branch, returning a constant — and measuring how many survive. A surviving mutant is a missing assertion, usually on a branch nobody thought worth covering.

SignalWhat it tells youAction
100 % line coverage, surviving mutantsLines ran, assertions were weakAdd cases for the mutated branches
Coverage below 80 % on a moduleUntested surfaceDecide: cover it, or delete it
Coverage that jumps after a refactorTests may be coupled to structureRe-check that assertions still target behaviour
Property tests with 3 examplesBudget too small for the domainRaise max_examples, constrain strategies
Flaky tests found by repeated runsHidden order or time dependenceIsolate state, freeze the clock
# mutation testing in practice — slow, so run it on changed modules, not everything
mutmut run --paths-to-mutate myapp/pricing
mutmut results

Run mutation testing on the modules where a silent bug is expensive, and treat the score as a guide to where to add assertions rather than as a target to maximise.

Controlling flakes before they become culture

A flaky test is worse than no test, because it trains everyone to ignore red. The usual causes are shared mutable state, uncontrolled time, network access, and dependence on ordering. Each has a direct countermeasure: function-scoped fixtures for state, a frozen clock for time, mocks for the network, and independent tests for order. When a test fails only under -x-less full runs, run the suite ten times in a loop before merging anything else — a flake that reproduces once in ten is still a bug, in the test or in the code.

The last lever is what the suite is allowed to assert about the outside world. A suite that reaches for the network, the clock, or the real file system inherits the volatility of all three. Keep the outer shell of the system — the adapters that touch those resources — thin and covered by a handful of integration tests, and push everything else into pure functions with property tests. The result is a pyramid that is cheap to run, fast to diagnose, and honest about what it has actually verified.

Common Mistakes

Writing properties that restate the implementation

Fix: State invariants a reader would agree with independently of the code

Session-scoped fixtures that any test can mutate

Fix: Share read-only data broadly and roll back mutable state per test

Mocking your own domain services

Fix: Mock only external boundaries; let domain logic run for real

Accepting high line coverage as proof of quality

Fix: Add assertions for surviving mutants, especially on error branches

Ignoring flaky tests until the next release

Fix: Reproduce with a loop on the day it appears — order and time bugs only grow

Best Practices

  • Pin every discovered counterexample with @example so it stays covered
  • Use yield fixtures for teardown that must run even when the test fails
  • Prefer monkeypatch over manual setattr — reversion is automatic and complete
  • Assert on call arguments, not just call counts, whenever a protocol matters
  • Run mutation testing on high-risk modules and read survivors as missing tests

Key Takeaways

  • Properties test laws across a whole class of inputs and shrink failures to a minimal case
  • Fixture scope is a state-isolation decision before it is a performance one
  • Mock external boundaries with autospec, and verify arguments, not just invocation
  • Coverage measures execution; mutation testing measures whether anyone would notice a change
  • Flakiness is a defect — reproduce it with a loop the day it appears
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