Testing: unit, integration and mocking¶
What you'll be able to do¶
- Write small pytest tests that explain a function's behavior and catch regressions.
- Choose a unit, integration, or end-to-end test for a risk, and replace slow dependencies with suitable test doubles.
- Make tests repeatable when code uses files, time, randomness, or external services.
Why keep tests¶
A test runs code with a chosen input and checks an observable result. It gives fast feedback when a change breaks a contract. It also makes refactoring safer: you can change the inside of a function while checking that callers still see the same behavior. A well-named test is executable documentation; unlike a comment, it fails when the documented behavior stops working.
Fixing a bug after release means reproducing it, locating it, possibly repairing affected data or helping users, deploying, and verifying. Catching it while editing avoids much of that work. Shorter feedback loops reduce the code and context you must investigate.
Tests are also a design tool. If testing a text converter requires starting a server or patching five globals, its dependencies are too tightly coupled. Pass what it needs as arguments. The code becomes easier to test and reuse.
Your first pytest tests¶
Pytest discovers files named test_*.py and functions named test_*. A plain assert checks the result; when it fails, pytest shows the compared values. Structure each test as Arrange, Act, Assert: set up input, call the code, check the behavior.
def normalize_text(s):
return " ".join(s.lower().split())
def test_normalize_text_collapses_whitespace():
source = " Red fox\n" # Arrange
result = normalize_text(source) # Act
assert result == "red fox" # Assert
From the project directory, python -m pytest tests -q runs tests with quieter output. Run one with python -m pytest tests/test_lab.py::test_normalize_text_collapses_whitespace; add -x to stop on the first failure, or -k whitespace to select names containing whitespace. Run the full suite before calling work done.
When several inputs share one contract, use @pytest.mark.parametrize instead of copying the test. pytest.raises checks exceptions. pytest.approx checks floats with a tolerance; 0.1 + 0.2 is not generally exact in binary floating point.
import pytest
from lab import moving_average, normalize_text
@pytest.mark.parametrize("source, expected", [
(" A B ", "a b"),
("\tC\n", "c"),
])
def test_normalize_text(source, expected):
assert normalize_text(source) == expected
def test_invalid_window():
with pytest.raises(ValueError):
moving_average([1, 2], window=0)
def test_average():
assert moving_average([1, 2], window=2) == pytest.approx([1.5])
A fixture supplies setup to tests. By default pytest creates its value separately for each test; a fixture with a wider scope can share one value across tests. Pytest's tmp_path fixture gives each test a temporary directory, so a file test need not touch a shared file. A custom fixture can create a fresh cache:
import pytest
from lab import fetch_with_cache
@pytest.fixture
def cache():
return {}
def test_cache_hit_skips_fetch(cache):
cache["key"] = "saved"
assert fetch_with_cache(lambda key: "new", cache, "key") == "saved"
Pick the right test size¶
The test pyramid is a budgeting guide, not a quota. Keep many fast, deterministic unit tests for individual functions; add integration tests where components meet; keep a smaller set of end-to-end tests for critical user paths. Wider tests catch wiring mistakes but are slower and harder to diagnose.
| Level | Runs with | Good at finding |
|---|---|---|
| Unit | One function and controlled dependencies | Edge cases, calculations, validation |
| Integration | Two or more real components, such as app and test database | Data format and interface mismatches |
| End-to-end | A full user workflow through real system boundaries | Broken workflows and cross-component wiring |
For example, unit-test a price calculation with inputs in memory; integration-test that its result is stored and read correctly; end-to-end-test that a user can complete checkout. A hundred unit tests cannot prove the database is configured correctly. One end-to-end test cannot explain which arithmetic branch failed. A test database also does not prove production configuration works; a small smoke test in the deployed environment catches environment-specific failures.
Replace dependencies carefully¶
A test double stands in for a dependency. The names describe different jobs: a dummy fills an unused argument; a stub returns fixed answers; a fake has a small working behavior, such as an in-memory cache; a spy records calls; and a mock sets expectations about calls. Libraries often use “mock” for all of them; focus on what the double does.
Prefer passing a fake through an argument (dependency injection) over patching module globals. For a cache test, pass a dictionary and a fake fetch function. Then check the returned value and that fetch was called once across two reads. This tests the contract without a network. Inject a clock or sleep function when timing matters, and inject or seed randomness when output must repeat. Patching is useful when an existing API cannot accept a dependency, but it can hide the dependency from readers.
Never replace the function you are trying to verify. If every collaborator is mocked and the test only asserts that each mock was called exactly as the implementation calls it, a green result proves little about user-visible behavior. Keep a few integration tests with real collaborators to check the boundary your unit tests replaced.
Make failures repeatable¶
A deterministic test gives the same result for the same inputs. Use a local seeded random generator, rather than relying on random state shared with other tests. Pass a fixed clock value instead of reading today's date. Use tmp_path for files, fresh fixtures for mutable containers, and fakes for network calls in unit tests. Tests should pass alone and in any order; one test must not prepare hidden state for another.
A good test has a name that states the behavior, one reason to fail, and an assertion that explains the expected outcome. test_cached_none_skips_fetch points at a subtle bug: cache.get(key) mistakes a stored None for a miss. An assertion message can add the reason: assert calls == 1, "a cached value must avoid another fetch".
Coverage tells you which lines ran, not whether their outputs were checked. A test that calls a function without asserting anything can raise line coverage while missing a wrong answer. Use coverage to find unvisited areas, then choose assertions from the contract and failure risks. When a bug is found, first write a regression test that reproduces it and fails; only then fix the code. That failing result proves the test can catch the bug.
Red, green, refactor¶
Test-driven development repeats a short cycle. Suppose return s.strip().lower() leaves internal whitespace unchanged. Start with a failing test (red):
Make the smallest behavior change (green): return " ".join(s.lower().split()). Run that test, then the suite. Finally, tidy the code without changing its contract (refactor): name the intermediate words if that makes the function clearer, and rerun tests. Red verifies the test detects the missing behavior; green verifies the fix; refactor keeps the design readable. Skipping red risks adding a test that would have passed even before the repair.
For AI engineers¶
For AI engineers
Your training script includes deterministic scaffolding: preprocessing, tokenization wrappers, metrics, data validation, and shape contracts. Test those with ordinary unit tests. For model code, check output shape; when the API returns a single-label class distribution, check that its probabilities sum approximately to 1; check permutation invariance only when the task requires it; add a tiny overfit case and same-seed repeatability where the operations permit it. Golden or snapshot outputs can catch changes, but compare numeric results with tolerances and review intentional updates. In unit tests for an LLM app, fake the model API; keep a few optional, marked real-call integration tests. Whether an LLM answer is good cannot be captured by one assert answer == expected; Evals as tests develops that separate question.
Common mistakes¶
- Asserting exact equality on computed floats instead of a meaningful tolerance.
- Reading today's date, using unseeded randomness, or sharing mutable state so tests depend on order.
- Mocking every call until the test merely repeats the implementation.
- Packing many unrelated behaviors into one giant test, making failures hard to locate.
- Testing private helpers or call sequences instead of the public behavior callers rely on.
- Fixing a bug before proving a regression test fails, or leaving a flaky test to “rerun until green.”
Check yourself¶
A test calls calculate_score with a fake database, then verifies only that database.save was called. What important check is missing?
It should assert the observable result or saved value, not just that a call happened. A wrong score could still produce a green test.
A split function passes alone but fails after a different test. What would you inspect first?
Look for shared mutable input, global random state, a reused file or cache, or another test changing the environment. Give each test fresh state and seed or inject randomness.
You changed a text normalizer after a bug report. What is the red-green-refactor sequence?
Write a test with the reported input and expected output; confirm it fails on the old implementation; make the smallest fix and confirm it passes; tidy the code and run the suite again.
Your unit tests pass, but the app cannot read from its database after deploy. Which test level was missing?
An integration test with the real database interface, plus a smoke test in the deployed environment to catch configuration differences. Unit fakes cannot verify actual wiring.
Lab¶
Build five small functions for text cleanup, moving averages, retries, caching, and seeded train/validation splits. Work in code/testing-basics/; read tests/test_lab.py as examples of parametrization, exceptions, fakes, fixtures, and approximate comparisons. Start with starter/lab.py and use the failing tests as your short feedback loop. Run cd code/testing-basics && PYTHONPATH=starter python -m pytest tests -q. Done means the supplied tests pass without changing them, including edge cases and repeatability. For a stretch exercise, add three of your own moving-average tests in tests/test_mine.py, then run python mutate.py to see whether they catch changed implementations.
Go deeper¶
- Pytest documentation for fixtures, parametrization, and command-line options.
- Designed to Scale: testing for another pass through test levels.
- Software Engineering at Google for testing in larger codebases.