Skip to content

Lesson 49 of 52Real projects

Testing Code That Touches the Outside World

Design code you can test, pick the right test double, and control time, randomness, the network, files and subprocesses without flaky tests.

15 min read0/5 questions

Here is a job that runs every morning: find unpaid invoices, email a reminder to anyone 1, 7 or 30 days overdue, and log what happened. The first version calls date.today(), opens a database connection, posts to an email API and writes to the real log, all inside one function. Its test patches four things, sleeps for a second to "let things settle", and fails every few weeks for reasons nobody can reproduce. This lesson is about fixing that properly. Testing with pytest gave you the basics of mocking, and pytest in Depth covered fixtures, unittest.mock and patch targets. Here you learn the design moves and the specific techniques that make code with real dependencies easy, fast and reliable to test.

Hard to test is a design smell

When a test needs a pile of patches, the test is not the problem. The code is hiding its dependencies. Look at what the morning job actually decides: given some invoices and a date, who gets an email and what does it say. That is a pure decision. The clock, the database and the email API are only how the inputs arrive and the outputs leave.

So split it in two. A pure core takes plain data in and returns plain data out. A thin imperative shell reads the clock, loads from the database, calls the core, and sends the emails. This pattern is often called "functional core, imperative shell".

Python
from dataclasses import dataclassfrom datetime import date, timedelta @dataclass(frozen=True)class Invoice: id: str email: str due: date paid: bool = False # Pure core: data in, decisions out. No clock, no network, no database.def reminders_due(invoices: list[Invoice], today: date) -> list[tuple[str, str]]: out = [] for inv in invoices: overdue = (today - inv.due).days if not inv.paid and overdue in (1, 7, 30): out.append((inv.email, f"Invoice {inv.id} is {overdue} day(s) overdue")) return out # Tests are plain calls with chosen dates. No patching anywhere.today = date(2026, 10, 22)invoices = [ Invoice("A1", "ada@example.com", today - timedelta(days=1)), Invoice("B2", "bo@example.com", today - timedelta(days=7), paid=True), Invoice("C3", "cy@example.com", today - timedelta(days=30)), Invoice("D4", "di@example.com", today - timedelta(days=2)),]for email, text in reminders_due(invoices, today): print(email, "|", text) assert reminders_due(invoices, date(2026, 1, 1)) == [] # nothing overdue yetprint("leap-year edge case:", reminders_due([Invoice("E5", "e@x.io", date(2028, 2, 28))], date(2028, 2, 29)))
Output
Press Run (⌘ Enter) to see what happens.

Every interesting rule (paid invoices are skipped, only days 1, 7 and 30 count, leap days work) is now tested by calling a function. These tests run in microseconds and can never be flaky, because nothing in them changes between runs. The shell that is left is so small that a couple of tests with fakes cover it.

Pure core, thin shell
Clock: date.today()Clockdate.today()Database: unpaid invoicesDatabaseunpaid invoicesShell: send_reminders()Shellsend_reminders()Core: reminders_due()Corereminders_due()Email API: HTTPEmail APIHTTPtodayrowsplain datadecisionssend

The core holds every business rule and touches nothing outside itself. Most of your tests live here, as plain function calls.

1/3

The second move is pass dependencies in instead of reaching out for them. A function that takes mailer as a parameter can be given a fake. A function that does import smtplib inside and builds its own connection can only be patched. Constructor injection (ReminderService(repo, mailer, clock)) is the same idea for classes. You do not need a dependency-injection framework, only parameters with sensible defaults.

The test double vocabulary

"Mock" is used loosely for any stand-in, but the precise words matter in code review and interviews, because each kind of double makes a different promise.

Match the pairs0/5 matched

Match each kind of test double to what it is.

Choose an item, then its match on the other side.

The trade-off is coupling. A mock-based test asserts how the code did its job: repo.save was called once with these arguments. Refactor to repo.save_many and the test fails even though the behaviour is identical. A fake-based test asserts what happened: after the run, the fake repository holds the right rows and the fake outbox holds one email. You can restructure the code freely and the test stays green, as long as the result is right.

So prefer fakes for things you own an interface for (repositories, mailers, queues), and keep mocks for the edges where the interaction is the behaviour, such as "we must call the payment provider exactly once".

Python
from typing import Protocol class Mailer(Protocol): def send(self, to: str, subject: str, body: str) -> None: ... class FakeMailer: """A working in-memory implementation, not a script of expected calls.""" def __init__(self) -> None: self.outbox: list[dict[str, str]] = [] def send(self, to: str, subject: str, body: str) -> None: if "@" not in to: raise ValueError(f"bad address {to!r}") # behave like the real one self.outbox.append({"to": to, "subject": subject, "body": body}) class FakeInvoiceRepo: def __init__(self, rows: dict[str, dict]) -> None: self.rows = rows def unpaid(self) -> list[dict]: return [r for r in self.rows.values() if not r["paid"]] def mark_reminded(self, invoice_id: str) -> None: self.rows[invoice_id]["reminded"] = True # The imperative shell: wires the core to real (or fake) dependenciesdef send_reminders(repo, mailer: Mailer) -> int: sent = 0 for row in repo.unpaid(): if row.get("reminded"): continue mailer.send(row["email"], "Payment reminder", f"Invoice {row['id']} is overdue") repo.mark_reminded(row["id"]) sent += 1 return sent repo = FakeInvoiceRepo({ "A1": {"id": "A1", "email": "ada@example.com", "paid": False}, "B2": {"id": "B2", "email": "bo@example.com", "paid": True},})mailer = FakeMailer() print("first run:", send_reminders(repo, mailer))print("second run:", send_reminders(repo, mailer)) # must not email twiceprint([m["to"] for m in mailer.outbox])print(repo.rows["A1"])
Output
Press Run (⌘ Enter) to see what happens.

The second-run check is the kind of test that matters at work: a job that crashes halfway and is retried must not email customers twice. With a fake, that test is three lines.

A fake has one risk: it can drift from the real thing. The senior fix is a contract test, one set of tests that runs against both implementations through a parametrised fixture. If the fake and the real repository both pass test_unpaid_excludes_paid_invoices, you can trust the fake everywhere else.

tests/test_repo_contract.py
import pytest
 
from billing.repo import FakeInvoiceRepo, PostgresInvoiceRepo
 
 
@pytest.fixture(params=["fake", "postgres"])
def repo(request, pg_connection):   # pg_connection: a real test database fixture
    if request.param == "fake":
        return FakeInvoiceRepo({})
    return PostgresInvoiceRepo(pg_connection)
 
 
def test_unpaid_excludes_paid_invoices(repo):
    repo.add(id="A1", email="a@x.io", paid=False)
    repo.add(id="B2", email="b@x.io", paid=True)
    assert [r["id"] for r in repo.unpaid()] == ["A1"]

When you must patch, patch where it is looked up

Sometimes you cannot change the design: legacy code, or a third-party function called deep inside. Then you patch, and the rule from pytest in Depth applies. from billing import charge copies a reference into the importing module, so you must replace that reference. Here it is running for real:

Python
import sysimport typesfrom unittest import mock # Build two tiny modules in memory, as if they were billing.py and orders.pybilling = types.ModuleType("billing")exec("def charge(total):\n return f'REAL charge {total}'", billing.__dict__)sys.modules["billing"] = billing orders = types.ModuleType("orders")exec("from billing import charge\n" "def place(total):\n return charge(total)", orders.__dict__)sys.modules["orders"] = orders with mock.patch("billing.charge", return_value="fake"): print("patched billing.charge ->", orders.place(10)) # still real! with mock.patch("orders.charge", return_value="fake"): print("patched orders.charge ->", orders.place(10))
Output
Press Run (⌘ Enter) to see what happens.

The first patch "worked" (no error) and the real charge still ran. In a real suite that means a test that silently hits a payment sandbox, or production. Add autospec=True to every patch so a replaced function also keeps its real signature, and treat a growing number of patches in one test as a signal to refactor.

Time, randomness and IDs

These three break more tests than anything else, and they all have the same fix: make the source a parameter.

Time. Pass in today (as above) or a clock callable, clock: Callable[[], datetime] = lambda: datetime.now(UTC). For code you cannot change, the time-machine library freezes or moves the clock for a test (@time_machine.travel(datetime(2026, 10, 22, 9, tzinfo=UTC))) and is faster than the older freezegun. Test the dates that break code: month ends, 29 February, the daylight-saving change, and midnight in a time zone that is not UTC.

Sleeping. Code that retries or polls calls time.sleep. Never let a test actually sleep: inject the sleep function and record what it was asked to do.

Python
import randomimport timefrom typing import Callable def fetch_with_retry( fetch: Callable[[], str], *, attempts: int = 4, base: float = 0.5, sleep: Callable[[float], None] = time.sleep, # real by default rng: random.Random | None = None,) -> str: rng = rng or random.Random() for attempt in range(attempts): try: return fetch() except ConnectionError: if attempt == attempts - 1: raise delay = base * 2 ** attempt sleep(delay + rng.uniform(0, delay / 10)) # backoff plus jitter # --- the test: no real waiting, no real randomness ---slept: list[float] = []replies = iter([ConnectionError(), ConnectionError(), "200 OK"]) def flaky_fetch() -> str: r = next(replies) if isinstance(r, Exception): raise r return r result = fetch_with_retry(flaky_fetch, sleep=slept.append, rng=random.Random(7))print(result)print([round(s, 3) for s in slept])
Output
Press Run (⌘ Enter) to see what happens.

The test takes no time at all, checks the backoff schedule exactly, and gives the same numbers on every run because the jitter comes from a seeded random.Random(7) that belongs to this call.

Randomness. Pass a random.Random instance, as above. Do not call random.seed() in tests: the global generator is shared by everything in the process, so seeding it in one test changes what every later test sees, and the order of your tests starts to matter.

IDs. uuid.uuid4() and uuid.uuid7() (3.14) are fine in production, but a test that asserts on output containing them needs an id_factory parameter, or assertions that ignore the ID field.

Predict the outputPython

Using fetch_with_retry and flaky_fetch from above, what does this print?

class NoJitter(random.Random):
  def uniform(self, a, b):
      return 0.0

slept = []
replies = iter([ConnectionError(), ConnectionError(), ConnectionError(), "ok"])
print(fetch_with_retry(flaky_fetch, base=1.0, sleep=slept.append, rng=NoJitter()), slept)
Need a nudge? Hints walk you through it.

The network

Unit tests must never call real services. The tools depend on your HTTP client:

  • httpx ships httpx.MockTransport. You hand the client a function that receives each request and returns a response, so nothing leaves the process. respx adds a routing layer on top.
  • requests has the responses library, which intercepts calls by URL and method.
  • A fake server such as pytest-httpserver runs a real local HTTP server. It is slower, but it exercises your real client code, timeouts and headers.
tests/test_rates.py
import httpx
import pytest
 
from shop.rates import RatesClient, RatesUnavailable
 
 
def test_converts_using_latest_rate():
    def handler(request: httpx.Request) -> httpx.Response:
        assert request.url.path == "/latest"
        assert request.headers["Authorization"] == "Bearer test-key"
        return httpx.Response(200, json={"EUR": 0.92})
 
    client = RatesClient(httpx.Client(transport=httpx.MockTransport(handler),
                                      base_url="https://rates.example.com"),
                         api_key="test-key")
    assert client.convert(100, "EUR") == 92
 
 
def test_raises_clear_error_on_503():
    client = RatesClient(httpx.Client(transport=httpx.MockTransport(
        lambda request: httpx.Response(503)), base_url="https://rates.example.com"),
        api_key="test-key")
    with pytest.raises(RatesUnavailable, match=r"503"):
        client.convert(100, "EUR")

Notice that RatesClient takes an httpx.Client, the same "pass it in" move again. Test the unhappy paths deliberately: 500s, timeouts, malformed JSON, an empty list. Those are the branches that fail in production and that nobody exercises by hand.

As a safety net, pytest-socket with --disable-socket makes any accidental real connection fail the test. Recording libraries such as vcrpy capture real responses once and replay them; they are handy for wide APIs but the cassettes go stale, so re-record on a schedule.

Files, environment, output and logs

pytest's built-in fixtures cover the rest of the outside world. The ones that matter here:

tests/test_export.py
import logging
 
import pytest
 
from shop.export import export_orders
 
 
def test_export_writes_csv_and_logs(tmp_path, monkeypatch, caplog, capsys):
    monkeypatch.setenv("EXPORT_DIR", str(tmp_path))     # restored after the test
    monkeypatch.delenv("S3_BUCKET", raising=False)       # force the local path
    caplog.set_level(logging.INFO)
 
    export_orders([{"id": 1, "total": 500}])
 
    assert (tmp_path / "orders.csv").read_text().splitlines() == ["id,total", "1,500"]
    assert "exported 1 orders" in caplog.text
    assert capsys.readouterr().out == ""                 # a library should not print
 
 
def test_rejects_negative_total():
    with pytest.raises(ValueError, match=r"total must be >= 0 \(got -5\)"):
        export_orders([{"id": 1, "total": -5}])

Two details catch people. match= is a regular expression searched in the message, so parentheses and dots must be escaped, or wrapped with re.escape(...). And pytest.warns(DeprecationWarning, match=...) checks warnings the same way.

For subprocesses, the same design move works: wrap the call in a small function that takes a run=subprocess.run parameter, and pass a fake that returns a subprocess.CompletedProcess. When you need the real call path, put a tiny fake executable in tmp_path and prepend that folder to PATH with monkeypatch.setenv. The pytest-subprocess plugin is a third option.

Quick check
A test has pytest.raises(ValueError, match="price (USD)") and the code raises ValueError("price (USD) missing"). What happens?
Need a nudge? A hint rules out a wrong answer.

Flaky tests

A flaky test passes and fails on the same code. It is worse than no test, because the team learns to click "re-run" and stops trusting red builds. The causes are almost always the same few:

  • Real time: a test that fails after 23:00 UTC, on the last day of the month, or on a slow CI machine that hits a timeout.
  • Shared state: a module-level cache, a global seed, a database row left behind by another test.
  • Order dependence: test B only passes because test A ran first and set something up.
  • Real network or real concurrency: a third-party sandbox that is down, or two threads whose timing differs per run.
  • Sleeps: time.sleep(1) to wait for something is a guess, and guesses fail under load. Wait on a condition with a deadline, or better, remove the asynchrony from the unit test.

The pytest-randomly plugin shuffles test order on every run and reseeds random per test. It prints the seed it used, so when a shuffle exposes an order dependence you can replay that exact order with --randomly-seed (check the plugin docs for the current options). Turning it on in an old suite is a quick way to find hidden coupling. Retry plugins like pytest-rerunfailures hide flakiness rather than fix it; use them only to quarantine a known flaky test while you fix the cause.

Put it in order5 steps

A test fails roughly one run in twenty on CI. Order a sensible investigation.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Snapshot and golden-file tests

Some outputs are large and structured: a rendered email, a CLI's help text, an API response with twenty fields. Writing assertions for every line is tedious, so snapshot tests store the expected output in a file the first time and compare against it after that. syrupy gives you a snapshot fixture (assert html == snapshot) and a --snapshot-update flag; inline-snapshot writes the expected value straight into your test source.

They are good at catching unintended changes in big outputs. Their failure mode is human: when a snapshot fails, it is very easy to run the update command without reading the diff, and then the test protects nothing. Keep snapshots small and readable, strip changing values (timestamps, IDs) before comparing, and review snapshot diffs in pull requests like code.

Quick check
Which change makes a test of a retry loop both fast and deterministic?
Need a nudge? A hint rules out a wrong answer.
Key terms
functional core, imperative shell
Keeping business rules in pure functions and pushing I/O into a thin outer layer.
dependency injection
Passing a function or object its collaborators (clock, client, repository) instead of letting it create them.
fake
A simplified working implementation used in tests, such as an in-memory repository.
contract test
One set of tests run against both a fake and the real implementation to keep them in agreement.
flaky test
A test that passes and fails on the same code, usually because of time, shared state, order or the network.
snapshot test
A test that compares output against a stored copy and flags any change.