Lesson 15: Test Doubles, Mocking and pytest
Some code is hard to test because it talks to the outside world: it downloads a web page, reads the clock, writes to a database, or sends an email. You cannot rely on the network being up when your tests run, and you certainly do not want your tests sending real emails. The solution is a test double — a stand-in object that pretends to be the real thing. In Python, the standard tool for building stand-ins is unittest.mock, and its star is MagicMock, an object that accepts any method call and records what happened, so your test can check that the code asked for the right thing.
The example below tests a function that fetches a user's name from a web service. Instead of calling the real service, the test replaces the HTTP function with a mock that returns a fixed answer. The test then checks that the function built the right web address and returned the right name — all without touching the network. The patch helper swaps the real function for the mock only inside the with block, so the rest of the program is unaffected.
from unittest.mock import MagicMock, patch
def fetch_username(http_get, user_id):
response = http_get(f"https://example.com/users/{user_id}")
return response["name"]
fake_get = MagicMock(return_value={"name": "Ana"})
result = fetch_username(fake_get, 42)
assert result == "Ana"
fake_get.assert_called_once_with("https://example.com/users/42")
print("mock test passed")
pytest: the test runner most teams use
The standard library's unittest module is solid and always available, and the next lesson covers it in full. But most Python teams today run their tests with pytest, a third-party tool you install with pip. pytest lets you write tests as plain functions with plain assert statements — no classes, no special method names — and it finds and runs every file whose name starts with test_. It also gives far better failure messages: when an assert fails, pytest shows you the values on both sides, which often reveals the bug immediately.
pytest's other strength is fixtures: small helper functions, marked with @pytest.fixture, that set up the data or objects a test needs. A fixture that builds a fresh bank account for each test means every test starts from the same clean state, and a fixture can also clean up afterwards with a yield. Fixtures are how large test suites stay readable: the setup lives in one place, and each test reads as a short story about one behaviour. You do not need to choose between unittest and pytest forever — the two can even run side by side — but if you learn one test runner deeply, make it pytest.
Going further
pytest has a feature that removes one of the most tedious parts of testing: parametrisation. The @pytest.mark.parametrize decorator runs the same test function with many different inputs, so one test can check a dozen cases — empty lists, single items, negative numbers — without a dozen near-identical functions. Each case is reported separately, so a failure tells you exactly which input broke. It is the natural way to test the edge cases from the last lesson, and it keeps the test file short enough to read.
Fixtures deserve a second look too, because they solve a problem you will meet as soon as your tests grow: setup code repeated in every test. A fixture that creates a temporary directory (tmp_path, built into pytest) or a fresh database gives each test a clean, isolated environment, and pytest cleans it up afterwards. The key rule is that fixtures should be small and single-purpose, like the functions they support. A fixture that does too much becomes as hard to understand as the setup code it replaced.
Mocking has a boundary worth respecting: mock what your code depends on, not what your code is. If you mock the function you are testing, the test proves nothing; if you mock the network, the clock, or the database, the test proves that your logic handles whatever those services return. A good rule is to mock at the boundary of your program — the place where your code talks to the outside world — and to keep everything inside the boundary real. Tests written that way are honest: they check your code, not your mocks.
Key Terms
- Test double
- A stand-in object used in tests in place of a real dependency, such as a web service or database.
- Mock
- A test double that records how it was called, so a test can check the code asked for the right thing.
- MagicMock
- A mock from unittest.mock that accepts any attribute or method call and returns a configured value.
- patch
- A helper that temporarily replaces a real function or object with a mock, restoring it afterwards.
- pytest
- A popular third-party test runner: plain test functions, plain asserts, and detailed failure messages.
- Fixture
- A pytest helper that sets up the data or objects a test needs, optionally cleaning up afterwards.
- assert
- The statement that checks a condition in a test; a failed assert means the test failed.
Discussion Questions
- Why is it a bad idea for a test to call a real web service? What could go wrong even if the code is correct?
- A mock records how it was called. Why is checking the call itself useful, not just the return value?
- When would you use unittest, and when pytest? What does each one give you that the other does not?
Practice Questions
- What does
fake_get.assert_called_once_with("https://example.com/users/42")check? - Why does the test use a mock instead of the real web service?
- What does a pytest fixture do?
- How does pytest find your tests?
- Write a pytest-style test function that checks
average([2, 4]) == 3.
Show answers
- That the mock was called exactly once, with that exact web address. It verifies the code built the right address, not just that it returned the right name.
- So the test is fast, reliable and offline. Real network calls are slow, can fail for unrelated reasons, and might have side effects.
- It sets up the data or objects a test needs, and can clean up afterwards. Fixtures keep setup in one place so each test stays short and readable.
- It runs test functions in files whose names start with test_. Plain functions with plain asserts — no classes or special names required.
def test_average(): assert average([2, 4]) == 3pytest discovers the function by its test_ prefix and reports a clear failure if the assert is false.