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.
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".
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.
The core holds every business rule and touches nothing outside itself. Most of your tests live here, as plain function calls.
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 each kind of test double to what it is.
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".
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.
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:
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.
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.
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)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.respxadds a routing layer on top. - requests has the
responseslibrary, which intercepts calls by URL and method. - A fake server such as
pytest-httpserverruns a real local HTTP server. It is slower, but it exercises your real client code, timeouts and headers.
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:
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.
pytest.raises(ValueError, match="price (USD)") and the code raises ValueError("price (USD) missing"). What happens?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.
A test fails roughly one run in twenty on CI. Order a sensible investigation.
- Tap the steps below in the right order.
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.
- 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.