01B.8 Testing with pytest
The aitoolkit you have been building across this module — settings, validated models, an HTTP client, a concurrency helper, a retry wrapper, a FastAPI service — is about to meet its safety net. This lesson teaches pytest, the test runner the whole Python ecosystem uses, together with the testing habits that make AI-engineering code trustworthy: fakes instead of mocks where you can, no network in the fast suite, async tests that don't sleep, HTTP tests that never leave the process, and coverage and CI wired so a broken change can't merge quietly. Everything here runs offline; nothing needs an API key.
What you'll learn
- Why tests matter more, not less, in AI code — and the difference between a test (deterministic, fast, offline) and an eval (statistical, model-dependent)
- pytest from zero: discovery rules, plain
assertand assertion rewriting,pytest.raises/approx/warns, running subsets, exit codes,conftest.pyandpyproject.tomlconfiguration - Fixtures: scopes,
yieldteardown, the built-ins (tmp_path,monkeypatch,capsys,caplog), parametrised fixtures, factories andautouse— and when fixtures hide too much - Parametrisation and test design: table-driven tests, arrange–act–assert, property-based testing with
hypothesis, snapshot tests, markers and flaky tests - Fakes, stubs, mocks and spies: which double to reach for, a
ScriptedBackendfake you will reuse for the rest of the module,unittest.mock(patch,autospec,side_effect), and how to control time, randomness, environment and the filesystem - Blocking the network in tests — a socket guard you write yourself, and
pytest-socket - Testing async code with
pytest-asyncioand theanyioplugin, without sleeps - Testing HTTP clients and APIs:
httpx.MockTransport,respx(and thehttpx2trap), FastAPITestClientand dependency overrides, SSE streams, and retry behaviour - Coverage with
pytest-cov(including[tool.coverage]settings andpragma: no cover), test speed and safety nets withpytest-xdist,pytest-timeoutand random ordering, and a CI job that runs the suite on every push - Red–green–refactor in practice, and the complete
aitoolkit/tests/suite
What you don't need
- Any API key, provider account or local model. Every test in this lesson runs offline. The only thing that ever "calls a model" is a fake that returns canned text.
- Prior pytest experience — this lesson starts from
assertand builds up. If you have usedunittest,jestor JUnit, the "Coming from another stack" callouts map the ideas across. - Deep pytest plugin knowledge. Plugins are introduced where they earn their place, each named exactly as it appears on PyPI so you can look it up.
Setup
The samples assume the aitoolkit project from 01B.1 — continue in the project you built there (uv init aitoolkit --package --python 3.13, a src/-layout installable package). If you don't have it yet:
uv init aitoolkit --package --python 3.13 && cd aitoolkitLessons 01B.5–01B.7 already added httpx, pydantic, pydantic-settings and fastapi as runtime dependencies. This lesson adds the test tools as dev dependencies (they ship with the project but aren't needed by the code it installs):
uv add --dev pytest pytest-asyncio pytest-cov \
pytest-xdist pytest-socket respx hypothesis \
time-machine
# or, without uv: pip install pytest pytest-asyncio pytest-cov \
# pytest-xdist pytest-socket respx hypothesis time-machineThese samples were checked against pytest 9.2 (released on 2026-10-27, so brand new), pytest-asyncio 1.4, pytest-cov 7.1, pytest-xdist 3.8, pytest-socket 0.8, respx 0.23, hypothesis 6.170 and time-machine 3.6 as of November 2026. An unversioned install gives you the newest releases, which may rename an option or change a default; check uv pip list for what you got and the plugin's changelog if a sample does not match. No .env file is needed: nothing here calls a provider.
What you must be able to do after this lesson#
- Explain the difference between a test and an eval
- Write pytest tests with plain assert and pytest.raises
- Share setup with fixtures and use tmp_path and monkeypatch
- Cover many cases with parametrize
- Replace a model or HTTP call with a fake and block the real network
- Test async code with pytest-asyncio
- Measure coverage and run the suite in CI
Why this matters for an AI engineer#
LLM code fails in more ways than ordinary code: the model can return malformed JSON, refuse, truncate, hallucinate a field, or change behaviour between provider releases. You can't test "the model gives a good answer" with a unit test — that's what evals are for (Module 10A). But everything around the model — the request you build, the response you parse, the errors you map, the retries you attempt, the stream you reassemble — is ordinary deterministic code, and it is exactly where the bugs that cost money live.
| You'll hear... | You'll understand it after... |
|---|---|
| "Did you write tests for the retry logic?" | Part 5 and 7.5 |
| "This test hits the real API — it'll be flaky and expensive." | 1.3 Tests vs evals and 5.5 |
"Why is async def test_... being skipped?" |
6.1 pytest-asyncio |
| "The mock didn't intercept the SDK call." | 7.2 respx and the httpx2 trap |
| "Our suite takes nine minutes." | 8.2 Speed |
| "What's branch coverage vs line coverage?" | 8.1 pytest-cov |
| "I mocked my own function and now the test tests nothing." | 5.1 The four doubles |
| "How do I test code that needs a key I don't have?" | 5.2 The ScriptedBackend fake |
| "The eval suite and the unit tests are different things, right?" | 1.3 Tests vs evals |
| "Should this be a fixture or just built in the test?" | 3.4 When fixtures hide too much |
Part 1: Why test, and what "tested" means for AI code#
1.1 What tests buy you#
Three things, and they compound:
- Regression safety. Every bug you fix should leave behind a test that would have caught it. Six months later, when a refactor reintroduces it, the suite fails before a user does. Your tests are executable memory of every mistake the project has already made.
- Design feedback. Code that is painful to test is usually painful to use: it reaches for globals, builds its own HTTP clients, reads the environment at import time, or hides its dependencies inside functions. Writing the test is often the fastest way to discover the seam you should have built.
- Refactoring confidence. With a green suite you can rename, split and rewire code knowing immediately if behaviour changed. Without one, every change is a guess.
The cost is real: tests take time to write and maintain, and a bad suite (slow, flaky, testing implementation details) costs more than it saves. The rest of this lesson is mostly about keeping the suite in the "cheap and trustworthy" quadrant.
1.2 The test pyramid, tuned for LLM applications#
The classic test pyramid says: many cheap unit tests at the bottom, fewer expensive integration tests at the top. LLM applications bend it, because the expensive layer isn't just slow — it costs money per call and can return a different answer each run. Lesson 03.10, Part 7 maps seven levels of realism for code that calls an LLM; 11C.2, 1.3 draws the pyramid for the whole system. This lesson teaches the mechanics those lessons rely on.
flowchart TD
subgraph top ["Few, scheduled, costs money"]
L5["Live smoke tests<br/>real provider, tiny budget"]
L4["Contract tests<br/>real HTTP server / local stand-in"]
end
subgraph mid ["Some, every push, no network"]
L3["Transport tests<br/>MockTransport / respx under the real SDK"]
L2["Component tests<br/>your code + ScriptedBackend / fakes"]
end
subgraph bottom ["Many, every save, milliseconds"]
L1["Unit tests<br/>pure functions: prompts, parsers, validators, maths"]
end
L1 --> L2 --> L3 --> L4 --> L5| Level | What is real | What is fake | Speed/cost | This lesson covers |
|---|---|---|---|---|
| 1. Unit | Your pure functions | Everything else absent | ms, free | Parts 2–4 |
| 2. Component | Your orchestration, validation, retry logic | The model/backend (ScriptedBackend) |
ms, free | Parts 5, 7.5 |
| 3. Transport | The real httpx client (or SDK) |
The network (MockTransport, respx) |
ms, free | Part 7 |
| 4. Contract | A real HTTP server speaking the wire format | The model behind it | seconds, free | 7.3–7.4, link 03.10 |
| 5. Live | Everything | Nothing | slow, money | Markers + CI only; 03.10 owns the design |
The discipline that makes this work: the fast levels must be able to catch every bug the slow levels would. If a bug can only be caught by a live call, it is either a provider change (schedule it, don't gate on it) or a missing fake (build one).
1.3 Tests vs evals#
This distinction trips up almost everyone new to AI engineering, so it gets its own section.
| Tests (this lesson) | Evals (Module 10A) | |
|---|---|---|
| Question answered | "Does the code do what I specified?" | "Is the model's answer good enough?" |
| Determinism | Must be deterministic — same code, same result, every run | Inherently statistical — the model samples |
| Speed | Milliseconds to seconds | Minutes to hours, often money |
| Network | Never (the fast suite) | Always — it is the model |
| Failure meaning | A bug in your code | A quality regression, a prompt problem, or model drift |
| Typical assertions | Parses, validates, routes, retries, maps errors, shapes | Scores, win-rates, judge verdicts, thresholds |
The rule of thumb: test everything except the model's answer. Whether the classification is correct is an eval question; whether your code handled the classification correctly — parsed it, validated it, retried the right errors, logged without secrets — is a test question. 03.10 applies exactly this split to LLM callers; 10A.8 shows eval suites running inside CI as statistical gates — a different tool for a different job.
1.4 What to test in an AI app#
A checklist for the aitoolkit-shaped code you will write throughout this path:
- Request building — the messages list, parameters, auth header, base URL: snapshot or assert the exact request your client would send (03.10 does request snapshots for SDK calls; for your own
httpxcode, aMockTransporthandler can capture theRequestobject). - Response parsing — every outcome, not just the happy path: valid JSON, malformed JSON, refusal, truncation, empty body, wrong content-type.
- Validation and repair — Pydantic acceptance and rejection, error messages, the "fix it and retry" path.
- Error mapping — status codes and exceptions mapped to your domain errors; which are retryable and which are permanent.
- Retries — attempt counts, backoff calls, giving up correctly, never retrying permanent errors.
- Concurrency — limits respected, results in order, partial failures collected, cancellation propagates.
- Streaming — frame parsing,
[DONE]/sentinel handling, disconnect mid-stream, partial JSON. - Config — env vars parsed, missing secrets fail fast,
SecretStrnever appears inrepr/logs. - Cost accounting — token counts aggregated correctly (you can't test the provider's count, but you can test your arithmetic).
Part 2: pytest fundamentals#
2.1 Anatomy of a test: discovery and assertion rewriting#
A pytest test is an ordinary Python function with three conventions:
- Its file is named
test_*.py(or*_test.py). - Its name starts with
test— thepython_functionsdefault is the prefixtest. (Files may end_test, but a function ending_testis not collected unless you setpython_functions = ["test", "*_test"].) - It takes no arguments — or arguments that are fixtures pytest fills in (Part 3).
# tests/test_cart.py — pytest finds this file because it matches test_*.py
def add_item(cart, sku, qty):
"""The code under test (normally imported from your package)."""
cart[sku] = cart.get(sku, 0) + qty
def test_add_item_accumulates_quantities():
cart = {}
add_item(cart, "MUG-1", 2)
add_item(cart, "MUG-1", 3)
assert cart == {"MUG-1": 5}A test class is named Test* (note the capital T) and must not define __init__. pytest collects its test_* methods. Everything else — module-level helpers, classes not starting with Test, functions not starting with test — is ignored by the runner but importable by the tests.
The magic is in the assert. Plain Python's assert x == y tells you only "AssertionError" when it fails. Assertion rewriting is pytest's feature that rewrites your assert statements at collection time so the failure report shows the values of every sub-expression. Suppose a typo in the expected dictionary ("MUG-2" instead of "MUG-1") made the test above fail. Example output (illustrative — your exact output will differ):
________________ test_add_item_accumulates_quantities ________________
def test_add_item_accumulates_quantities():
cart = {}
add_item(cart, "MUG-1", 2)
add_item(cart, "MUG-1", 3)
> assert cart == {"MUG-2": 5}
E AssertionError: assert {'MUG-1': 5} == {'MUG-2': 5}
E Left contains 1 more item:
E {'MUG-1': 5}
E Right contains 1 more item:
E {'MUG-2': 5}
E Use -v to get more diff
tests/test_cart.py:12: AssertionErrorThat level of detail is why pytest tests are readable even when they fail in CI at 2 a.m. Assertion rewriting only applies to test modules and plugins registered with pytest — asserts inside your library code behave normally (they still raise AssertionError, just without the pretty diff). If you need the pretty diff inside helpers, put helpers in the test file or mark the module for rewriting.
2.2 Running pytest: selection, output and exit codes#
uv run pytest # whole suite, from the project root
uv run pytest tests/test_cart.py # one file
uv run pytest tests/test_cart.py::test_add_item_accumulates_quantities # one test (a "node id")
uv run pytest -v # verbose: one line per test
uv run pytest -q # quiet: dots and a summary
uv run pytest -x # stop at first failure
uv run pytest --lf # last failed: re-run only what failed last time
uv run pytest --ff # failed first: failures, then the rest
uv run pytest -k "cart or refund" # substring match on test names
uv run pytest -m "not live" # by marker (see 2.4)
uv run pytest --collect-only # list what would run, don't run it
uv run pytest -s # don't capture stdout/stderr (see capsys in 3.3)
uv run pytest --tb=short # short tracebacks; --tb=long / --tb=no also exist
uv run pytest --durations=10 # the 10 slowest tests/setup/teardown
uv run pytest --maxfail=3 # give up after 3 failures-k matches against the test's node id, so -k "add_item" also matches parametrised variants like test_parse[add_item-billing]. You can combine -k expressions with and, or, not and parentheses.
The exit code matters for scripts and CI — it is part of pytest's public API:
| Exit code | Meaning |
|---|---|
0 |
All collected tests passed |
1 |
Tests ran, some failed |
2 |
Interrupted by the user (Ctrl-C) |
3 |
Internal error, or a plugin raised while importing |
4 |
Command-line usage error (bad flag, missing -c file, plugin not found, broken conftest.py) |
5 |
No tests were collected |
6 |
Maximum number of warnings exceeded (--max-warnings) |
A 5 in CI usually means your testpaths or file naming is wrong — pytest collected nothing, so nothing was checked. A plain uv run pytest step already fails on 5, which is what you want: a suite that collects zero tests protects nothing. (pytest --collect-only -q is the quick way to check what a run will see.)
2.3 The assertion toolkit#
Beyond bare assert, pytest ships helpers for the cases a bare assert can't express:
import pytest
def divide(a: float, b: float) -> float:
if b == 0:
raise ZeroDivisionError("cannot divide by zero")
return a / b
def test_divide_by_zero_raises():
with pytest.raises(ZeroDivisionError, match="cannot divide"):
divide(1.0, 0.0)
def test_raises_gives_you_the_exception():
with pytest.raises(ValueError) as excinfo:
int("not a number")
assert excinfo.type is ValueError
assert "invalid literal" in str(excinfo.value)
def test_float_comparison_needs_approx():
assert divide(10.0, 3.0) == pytest.approx(3.333333, rel=1e-4)
assert divide(1.0, 3.0) == pytest.approx(0.333, abs=0.001)
def test_warnings_are_assertable():
import warnings
with pytest.warns(UserWarning, match="deprecated"):
warnings.warn("this API is deprecated", UserWarning)pytest.raises(exc, match=...)—matchis a regex searched in the exception message (not a full match).excinfogives you.type,.valueand.tbfor finer assertions. If the block doesn't raise, the test fails; if it raises a different exception, the test errors — both are failures, but the report differs.pytest.approx— for floats. Defaultrel=1e-6; useabsfor values near zero. Never writeassert abs(a - b) < 0.001—approxalso handlesnancomparisons withnan_ok=True.pytest.warns— asserts a warning is emitted; pair withpytest.ini'sfilterwarnings(below) so warnings don't rot silently.pytest.skip("reason"),pytest.xfail("reason"),@pytest.mark.skipif(cond, reason=...)— runtime and declarative skipping; covered in 4.5.pytest.fail("msg")— explicit failure when a condition can't be an assert (e.g. inside a helper that must abort the test).pytest.importorskip("pyarrow")— import-or-skip, the clean way to make optional-dependency tests disappear gracefully.
2.4 Configuration: pyproject.toml, conftest.py and markers#
Almost everything pytest needs can live in [tool.pytest.ini_options] in pyproject.toml — the same file uv already manages. If you built the aitoolkit project in 01B.1, you already have this table with three keys: testpaths = ["tests"], asyncio_mode = "auto" and addopts = "-q". Edit that table in place; do not paste a second [tool.pytest.ini_options] heading, because TOML rejects a repeated table and a repeated key, and pytest then refuses to start:
# pyproject.toml (excerpt) — the final table; `addopts` REPLACES 01B.1's `-q`
[tool.pytest.ini_options]
testpaths = ["tests"]
addopts = "-ra --strict-markers"
asyncio_mode = "auto"
python_files = ["test_*.py", "*_test.py"]
filterwarnings = [
"error", # warnings become errors...
"ignore::DeprecationWarning:google.genai.*", # ...except known ones
]
markers = [
"live: calls a real provider API (needs keys; excluded from the default run)",
"integration: needs a local server or external service",
"slow: takes more than a second",
]What each piece does:
testpaths— where a barepytestlooks. Without it, pytest walks from the rootdir and may collect examples insidenode_modules-style directories or misstests/entirely.addopts— options prepended to every invocation. Replace theaddopts = "-q"line from 01B.1 with the one above rather than adding a secondaddoptskey (-qonly makes output terser; add it back to the new value if you miss it, as in"-q -ra --strict-markers").-raprints a summary of skips/xfails at the end (you want to see your skips).--strict-markers(or thestrict_markersini option) makes an unregistered@pytest.mark.fooan error instead of a silent no-op — important once you havelive/integrationmarkers that gate network access.asyncio_mode = "auto"— tellspytest-asyncioto handle everyasync def test_*without per-test marks (6.1).python_files/python_classes/python_functions— discovery patterns; defaults aretest_*.py/Test*/test*. The excerpt'spython_filesandfilterwarningsare optional extras; theaitoolkitproject needs onlytestpaths,asyncio_mode,addoptsandmarkers.filterwarnings— entries are checked in order and the last matching ini line wins, which is why broad rules go first and specific exceptions after (the same ordering thewarningsmodule applies once pytest has sorted it)."error"turns every warning into a test failure, which is how you stopDeprecationWarnings accumulating; carve out exceptions for warnings you can't fix (third-party noise) by module pattern.markers— registers custom marks so--strict-markersaccepts them and-m livecan select them. Undocumented markers are how suites accidentally grow@pytest.mark.slowthat nobody remembers.
conftest.py is pytest's per-directory plugin file: fixtures and hooks defined there are visible to every test in that directory and below. It is imported by pytest before collection, so it must stay importable — no side effects, no network, no reading files that might not exist. Common uses: shared fixtures (ScriptedBackend), the socket guard (5.5), marker registration helpers, and collection hooks. pytest_plugins = ["my_plugin"] in a conftest.py pulls in a plugin module from your own code.
Part 3: Fixtures#
3.1 What fixtures are and how they resolve#
A fixture is a function that prepares something a test needs, registered under a name. The test asks for it by declaring a parameter with the same name — pytest sees the parameter, finds the fixture, calls it, and passes the result in:
import pytest
@pytest.fixture
def backend():
"""Every test that asks for `backend` gets a fresh, empty fake."""
return {"calls": [], "replies": []}
def test_backend_starts_empty(backend):
assert backend["calls"] == []
def test_backend_records_calls(backend):
backend["calls"].append("hello")
assert backend["calls"] == ["hello"]Two properties make fixtures different from "just call a helper in the test":
- Caching per scope. Within one test, asking for
backendtwice gives you the same object — pytest calls the fixture once and caches the result for the scope. - Teardown. A fixture can clean up after the test, via
yieldor a finalizer — the equivalent oftearDown/afterEach, but composable and scoped.
3.2 Scopes and yield teardown#
Fixtures run at one of five scopes, narrowest to widest:
| Scope | Created | Torn down | Use for |
|---|---|---|---|
function (default) |
Once per test | After each test | Almost everything: fresh state per test |
class |
Once per test class | After the last test in the class | Expensive per-class setup |
module |
Once per test file | After the last test in the file | A shared resource for one file |
package |
Once per __init__.py package |
After the package's tests | Rare; package-wide resources |
session |
Once per pytest run |
At the end of the run | A browser, a DB container, a big fixture file |
@pytest.fixture(scope="session")
def golden_responses():
"""Load 10 MB of recorded API responses once, share across the whole run."""
with open("tests/fixtures/responses.jsonl") as f:
yield [json.loads(line) for line in f]
# nothing to clean up here, but yield still marks the end of setupThe yield form splits the fixture into setup (before yield) and teardown (after yield). Teardowns run in reverse order of setup — fixtures torn down LIFO, like a stack. This is how you guarantee an AsyncClient closes even when a test fails:
@pytest.fixture
async def api_client():
transport = httpx.MockTransport(handler)
async with httpx.AsyncClient(transport=transport, base_url="https://tickets.example") as client:
yield client
# the async with exits here — client closed — even if the test raised3.3 The built-in fixtures you will actually use#
pytest ships a set of built-ins; these are the ones AI code reaches for:
| Fixture | Gives you | Typical use |
|---|---|---|
tmp_path |
A pathlib.Path to a fresh temp dir, deleted after |
File I/O tests, writing fake .env, cache dirs |
tmp_path_factory |
Factory for session-scoped temp dirs | Shared fixtures that need temp space |
monkeypatch |
Scoped patching of env vars and attributes | setenv, setattr, delenv; auto-undone |
capsys |
Captures Python-level sys.stdout/sys.stderr |
Testing print output |
capfd |
Captures file-descriptor-level output | Testing C-level writes, subprocess output |
caplog |
Captures logging records |
Asserting log messages without secrets |
request |
The current test's context | Access parametrised args, node name, fixtures by name |
pytestconfig |
The pytest configuration object | Reading ini options inside a test |
import logging
import pytest
from aitoolkit.settings import get_settings
def test_settings_load_from_env(monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "sk-test-123")
monkeypatch.setenv("OPENAI_MODEL", "test-model")
# get_settings() is lru_cached process-wide: clear it or this returns
# the Settings built by an earlier test, not the env we just set.
get_settings.cache_clear()
settings = get_settings()
assert settings.openai_api_key.get_secret_value() == "sk-test-123"
assert settings.openai_model == "test-model"
def test_writes_report_file(tmp_path):
report = tmp_path / "report.json"
write_report(report, {"ok": True})
assert report.exists()
assert json.loads(report.read_text()) == {"ok": True}
def test_logs_warning_without_secret(caplog):
with caplog.at_level(logging.WARNING):
logger.warning("retrying request to %s", "https://api.example.com")
assert "api.example.com" in caplog.text
assert "sk-" not in caplog.text # secrets never reach the logThree habits worth building now:
monkeypatchundoes itself.setenv/setattr/delenvare reverted when the test ends — no manual cleanup, no leaked state into the next test. Prefer it overos.environ[...] = ...orunittest.mock.patch.dict, which persist until you undo them.get_settings()is cached — clear it in tests. 01B.2 backsget_settings()withlru_cache, so the second call returns the first test'sSettingseven aftermonkeypatch.setenv. The pattern ismonkeypatch.setenv(...)+get_settings.cache_clear(); 9.2 wires it as an autouse fixture so no test can forget. This is the classic settings-test trap: without the clear, your "missing key fails fast" test happily asserts against a cached instance that has the key.caplogcaptures records, not just text.caplog.recordsgives youLogRecordobjects with.levelname,.message,.args— assert on structure, not on a formatted string that might change.
3.4 Parametrised fixtures, factories, autouse — and when fixtures hide too much#
Parametrised fixtures run the whole test once per parameter value:
@pytest.fixture(params=["sqlite", "postgres"])
def db_backend(request):
return connect(request.param)
def test_query_works(db_backend): # runs twice: once per backend
assert db_backend.query("SELECT 1")The test doesn't change; pytest just calls it once per db_backend value, and request.param inside the fixture tells it which one. You can also parametrise through the test with @pytest.mark.parametrize and have the fixture read request.param — that's indirect parametrisation, used when the parameter itself is a fixture name:
@pytest.fixture
def client(request):
transport = httpx.MockTransport(request.param)
return httpx.Client(transport=transport)
@pytest.mark.parametrize("client", [handler_a, handler_b], indirect=True)
def test_client_works_with_any_handler(client):
...Fixtures using fixtures is the normal composition mechanism — a fixture can declare other fixtures as parameters and pytest resolves the whole graph:
@pytest.fixture
def settings(monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "sk-test")
get_settings.cache_clear() # the lru_cache would serve stale settings
return get_settings()
@pytest.fixture
def api_client(settings): # depends on settings fixture
# httpx.Client configured the way aitoolkit/http.py configures TicketClient's
# inner client — the transport seam is what makes it testable (7.1).
return httpx.Client(
transport=httpx.MockTransport(handler),
base_url="https://tickets.example.com/v1",
headers={"Authorization": "Bearer test-token"},
)Factory fixtures return a callable so each test controls construction:
@pytest.fixture
def make_ticket():
def _make(**overrides):
base = {"title": "Refund", "priority": "normal", "status": "open"}
return Ticket(**{**base, **overrides})
return _make
def test_ticket_defaults(make_ticket):
t = make_ticket()
assert t.status == "open"
def test_ticket_override(make_ticket):
t = make_ticket(status="closed")
assert t.status == "closed"This is the test data builder pattern: one place to evolve the defaults, tests override only what they care about.
autouse=True fixtures run for every test in scope without being requested:
@pytest.fixture(autouse=True)
def _block_network():
disable_network() # the socket guard from 5.5
yield
enable_network()Part 4: Parametrisation and test design#
4.1 @pytest.mark.parametrize: one test, many cases#
The most-used pytest feature after assert. It runs the same test body once per row of a table:
import pytest
@pytest.mark.parametrize("raw, expected", [
("REFUND", "refund"),
(" Billing Issue ", "billing issue"),
("", ""),
("UPPER", "upper"),
])
def test_normalise_label(raw, expected):
assert normalise_label(raw) == expectedpytest reports four tests — one per row, with auto-generated ids built from the values, e.g. test_normalise_label[REFUND-refund] for the first row — and if row three fails you see exactly which row. Two refinements you'll use constantly:
ids=— human-readable test IDs instead of auto-generated ones. Passid=insidepytest.paramfor per-row names, or a list of strings toids=:
@pytest.mark.parametrize(
"raw,expected",
[("REFUND", "refund"), ("", "")],
ids=["shouty-input", "empty-input"],
)
def test_normalise_label(raw, expected):
assert normalise_label(raw) == expectedor per-row:
@pytest.mark.parametrize("raw, expected", [
pytest.param("REFUND", "refund", id="shouty"),
pytest.param("", "", id="empty"),
])
def test_normalise_label(raw, expected):
assert normalise_label(raw) == expected- Stacking decorators — two
parametrizemarks produce the cartesian product:
@pytest.mark.parametrize("priority", ["low", "high"])
@pytest.mark.parametrize("status", ["open", "closed"])
def test_ticket_matrix(priority, status):
t = make_ticket(priority=priority, status=status)
assert route_ticket(t).priority == priority # 4 combinationsAnd pytest.param(..., marks=...) attaches a mark to one row only — e.g. mark one input xfail because it's a known bug:
@pytest.mark.parametrize("text, ok", [
("plain", True),
pytest.param("tricky\x00null", True, marks=pytest.mark.xfail(reason="null byte crashes parser", strict=True)),
])
def test_parser(text, ok): ...4.2 Arrange–act–assert, one behaviour per test#
Every good test has three parts, usually visually separated:
# tests/test_retry.py
import pytest
from tenacity import AsyncRetrying, retry_if_exception, stop_after_attempt, wait_none
from aitoolkit.resilience import call_with_retry, is_transient
async def test_retry_recovers_after_transient_failures():
# Arrange: a call that fails twice with a transient error, then succeeds
calls = []
async def flaky_call():
calls.append(1)
if len(calls) < 3:
raise TimeoutError("transient")
return "ok"
policy = AsyncRetrying(
retry=retry_if_exception(is_transient), # 01B.9's classifier
stop=stop_after_attempt(3),
wait=wait_none(), # instant waits: test the logic, not the clock
reraise=True,
)
# Act
result = await call_with_retry(flaky_call, policy=policy)
# Assert: two failures absorbed, one success, three calls total
assert result == "ok"
assert len(calls) == 3Rules that keep suites maintainable:
- One behaviour per test. A test named
test_ticket_lifecyclethat creates, updates, closes and deletes a ticket is four tests pretending to be one — when it fails you don't know which behaviour broke. Split it. - Name tests after behaviour, not implementation.
test_refund_rejected_for_closed_orderbeatstest_refund_works— the name is the documentation of what the suite protects. - No test interdependence. Tests must pass in any order, alone or together. Never let test B rely on state test A created; never rely on execution order (pytest runs files alphabetically, functions top-to-bottom, but random-order plugins such as
pytest-randomlyand-ksubsets break that assumption). Each test builds or borrows its own fresh state. - No shared mutable state across tests. A module-level
ORDERS = {}that tests mutate is a classic flake source — test 3 passes only because test 2 left an order behind. Use a fixture that returns a fresh dict, or a factory (3.4) that deep-copies a template. - Failure messages should explain intent.
assert result.status == "open", f"expected open, got {result.status} after {result.history}"beats a bare assert when the test fails in CI.
4.3 Property-based testing with hypothesis#
@pytest.mark.parametrize checks the cases you thought of. Property-based testing checks a rule over hundreds of generated inputs: you state "for all inputs, X holds", and hypothesis generates inputs (including weird ones you'd never write), shrinks failures to a minimal counterexample, and saves failing cases to a database so they replay forever.
# tests/test_extract_json.py
from hypothesis import given, settings, strategies as st
# extract_json and ExtractionError are your own parser and its typed error
@given(st.text())
@settings(max_examples=200)
def test_extract_json_never_crashes(model_output: str):
"""Whatever the 'model' returns, extraction either parses or raises OUR error."""
try:
result = extract_json(model_output)
except ExtractionError:
pass # a clean, typed failure is fine
else:
assert isinstance(result, dict)Key pieces:
@given(strategy)— one strategy per argument.st.integers(),st.text(),st.lists(...),st.dictionaries(...),st.sampled_from([...]),st.builds(Model, ...)for Pydantic models..filter()— restrict a strategy:st.integers().filter(lambda n: n > 0).assume(cond)— inside the test, discard inputs that don't satisfy a precondition (use sparingly;.filteris cleaner).@st.composite— build strategies that draw dependent values (e.g. two ints wheren1 <= n2).@settings(max_examples=N, deadline=None)— control how many cases run (default 100) and whether slow cases fail.- Shrinking — on failure, hypothesis automatically tries simpler inputs and reports the minimal failing case, e.g.
Falsifying example: test_x(model_output=''). - The example database — failing inputs are saved (
.hypothesis/directory) and re-run first next time, so a once-found edge case never silently regresses.
Hypothesis shines exactly where LLM code lives: parsers that must never crash on arbitrary text, validators that must reject or accept cleanly, state machines, round-trip properties (serialise → deserialise = identity). 03.10, 10.2 uses it on a triage parser — the same technique applies to any extract_json-style function you write.
4.4 Snapshot and golden-file tests#
A snapshot test records a function's output once and fails when it changes. For most code that's a smell — output changes are often legitimate. But for contracts it's gold: the JSON Schema your Pydantic model generates, the exact request body your client sends, the wire format of an SSE stream.
# tests/test_schemas.py — golden-file test for the wire contract
import json
from pathlib import Path
import pytest
from aitoolkit.models import Ticket
def test_ticket_schema_is_stable():
schema = Ticket.model_json_schema()
golden = Path("tests/golden/ticket_schema.json")
if not golden.exists():
golden.parent.mkdir(parents=True, exist_ok=True)
golden.write_text(json.dumps(schema, indent=2, sort_keys=True))
pytest.skip("created golden file; re-run to verify")
assert json.loads(golden.read_text()) == schemaBetter: use a plugin like pytest-regressions (file_regression) or syrupy for snapshots — but the hand-rolled version above shows the mechanics. Two rules:
- Snapshot the contract, not the answer. A snapshot of "what request did we build" catches accidental prompt/parameter drift; a snapshot of "what the model replied" is a flaky test (the model's answer isn't deterministic).
- Review snapshot diffs like code. A changed golden file is a deliberate act — someone must look at the diff and accept it, the same way you'd review a migration.
08A.6 uses schema snapshots for tool definitions; 03.10, 7.6 covers request snapshots for LLM calls.
4.5 Markers, flaky tests and test selection#
Markers label tests so you can select or skip groups:
import sys
import pytest
@pytest.mark.live
def test_live_provider_smoke(): ... # needs keys; excluded from default run
@pytest.mark.integration
def test_against_local_server(): ... # needs a running service
@pytest.mark.skipif(sys.platform == "win32", reason="POSIX-only test")
def test_unix_signals(): ...
@pytest.mark.xfail(reason="known bug #123", strict=True)
def test_currently_broken_feature(): ...With the markers registration from 2.4, run subsets:
uv run pytest -m "not live and not integration" # the fast suite
uv run pytest -m live # only live tests
uv run pytest --strict-markers -m slow # fail on unregistered marks tooskip— "this test can't run here" (missing dep, wrong platform).skipif(cond)— conditional skip; the condition is evaluated at collection.xfail— "this test is expected to fail".strict=Trueturns an unexpected pass into a failure, so the marker can't silently rot. Usexfailfor known bugs you're tracking,skipfor tests that can't run — neverxfailto hide a flaky test.
Flaky tests fail intermittently for reasons unrelated to the code: real sleeps, unseeded randomness, shared state, network timing, dict/set iteration where order matters, tests that depend on each other. The defence is determinism: fake clocks, seeded random.Random, tmp_path isolation, events instead of sleeps (6.3), and markers to quarantine genuinely environment-dependent tests. pytest's own docs on flaky tests are the canonical reference.
Part 5: Fakes, stubs, mocks and spies#
5.1 The four doubles and when to use each#
A test double is anything that stands in for a real dependency during a test. The vocabulary (from Gerard Meszaros's xUnit Test Patterns) is worth keeping straight because it changes what your test actually verifies:
| Double | What it is | Verifies behaviour? | Use when |
|---|---|---|---|
| Dummy | Passed but never used | No | Filling a required argument |
| Stub | Returns canned answers | No — it doesn't check how it was called | You only care about the return value |
| Fake | A working, simplified implementation | Partially — it is real code | The dependency is complex but deterministic (an in-memory DB, a scripted backend) |
| Spy | A real object that also records calls | Yes — you inspect afterwards | You need the real behaviour and the call log |
| Mock | An object pre-programmed with expectations | Yes — it asserts the calls | Verifying interactions is the point ("did it call the API exactly once?") |
The pragmatic rule for this path: prefer fakes. A ScriptedBackend that returns canned replies and records its calls is real, readable code you control — it can't drift from the interface the way a mock's return_value can, and it exercises your code's actual call pattern. Reach for unittest.mock when the thing you're replacing is a boundary you don't own (a third-party SDK, a socket, the clock) or when the interaction itself is the contract.
5.2 The ScriptedBackend fake#
Every lesson from 01B.3 onward uses the same idea: a fake "model" that returns canned text. It already exists — aitoolkit/backend.py, built in 01B.3, Part 7. This lesson does not redefine it; it uses it. What matters for testing is the surface area:
from aitoolkit.backend import ScriptedBackend
backend = ScriptedBackend(
replies={"France": "Paris", "capital": "Paris is the capital."},
# replies: prompt-substring -> canned reply; first match wins, in dict order
default_reply="I don't have a scripted answer for that.",
latency=0.0, # asyncio.sleep per call — set 0 in tests for speed
stream_delay=0.0, # per-token delay when streaming
fail_first=0, # raise RuntimeError on the first N calls
seed=0,
)await backend.complete(prompt)→ aCompletiondataclass — assert on.text,.usage, not the object itself.async for chunk in backend.stream(prompt)→ the canned reply split into tokens.backend.calls→[{"prompt": ..., "mode": "complete"|"stream"}, ...]— the spy log: assertlen(backend.calls)and[c["prompt"] for c in backend.calls].fail_first=Nis the flaky-fake knob: the first N calls raiseRuntimeError. For retry-classification tests you need a failureis_transientrecognises —RuntimeErroris permanent to 01B.9's classifier — so those tests use a tinyFlakyBackendraisingTimeoutErrorinstead (7.5, 9.2).
A test using it:
async def test_completion_records_the_prompt():
backend = ScriptedBackend(replies={"weather": "sunny"}, latency=0)
result = await backend.complete("what is the weather?")
assert result.text == "sunny"
assert backend.calls == [{"prompt": "what is the weather?", "mode": "complete"}]The design points that make it a good fake rather than a mock:
- It records calls (
self.calls) so tests can assert on inputs — the spy property — withoutunittest.mockmachinery. - It fails loudly when misused. An unscripted prompt returns
default_reply, andfail_firstraises a real exception — both visible in assertions. A fake that silently returns""would hide bugs. - It's async where it needs to be.
complete/streamareasync def, matching the real backend's interface — your service can't tell the difference.
5.3 unittest.mock: Mock, patch, autospec, side_effect#
unittest.mock is standard library — no install needed — and pytest uses it happily alongside its own fixtures. Reach for it at boundaries you don't control.
from unittest.mock import Mock, patch
class TicketService:
"""Minimal stand-in for the classify pipeline: the injected backend
callable returns raw text; the service normalises it into a label."""
def __init__(self, backend):
self.backend = backend
def classify(self, text):
raw = self.backend(text)
return {"label": raw.strip().lower()} if raw else {"label": "unknown"}
def demo_side_effect_sequence():
# side_effect list: each call returns/raises the next item; call count is recorded.
flaky = Mock(side_effect=[TimeoutError("attempt 1"), TimeoutError("attempt 2"), " REFUND "])
svc = TicketService(flaky)
labels = []
for _ in range(3): # naive retry loop: try until it works
try:
labels.append(svc.classify("where is my refund?"))
break
except TimeoutError:
continue
print("labels:", labels)
print("backend call count:", flaky.call_count)
print("last call args:", flaky.call_args)
def demo_patch():
# patch replaces an attribute for the duration of the with-block, then restores it.
import json
with patch("json.loads", return_value={"ok": True}):
print("inside patch:", json.loads("not json at all"))
print("after patch:", json.loads('{"real": 1}'))
demo_side_effect_sequence()
demo_patch()labels: [{'label': 'refund'}]
backend call count: 3
last call args: call('where is my refund?')
inside patch: {'ok': True}
after patch: {'real': 1}The pieces:
Mock(return_value=...)— returns a fixed value.Mock(side_effect=...)— richer: an exception instance or class is raised, an iterable is consumed one item per call, a callable's return value is used, andDEFAULTfalls back toreturn_value.mock.call_count,mock.call_args,mock.call_args_list,mock.assert_called_with(...),mock.assert_called_once_with(...),mock.assert_has_calls([...])— the interaction assertions.call_argsis acallobject:call('arg', kw=1); compare with==or inspect.args/.kwargs.patch("module.attr")— replacesmodule.attrfor the block.patch.object(obj, "attr")— same but on an instance.create_autospec/autospec=True— builds a mock with the same signature as the real thing, so a wrong-argument call fails at mock-creation rather than silently passing. Forasync deffunctions,patch/autospecautomatically returns anAsyncMock(awaitable) since Python 3.8 — you don't needAsyncMockexplicitly unless you're constructing one by hand.MagicMock— aMockthat also supports magic methods (__len__,__iter__,__enter__). Needed when the double must behave like a container or context manager.
5.4 Controlling time, randomness, environment and the filesystem#
Flaky tests almost always come from uncontrolled inputs. Control them:
- Time. The cleanest fix is injecting a clock: your code takes
now: Callable[[], float]or aClockobject, and tests pass a fake that returns scripted times. When you can't change the signature,freezegun(freeze_time("2026-01-01")) ortime-machine(@time_machine.travel(...), faster — 3.6.0 as of November 2026) patchdatetime/timefor the block. For retry/backoff tests specifically, 01B.9 shows injecting a sleep function so "waiting" is instant and assertable. - Randomness.
random.seed(42)for module-level use; better, injectrandom.Random(seed)so tests don't share global state;hypothesismanages its own deterministic-ish generation plus a failure database. - Environment.
monkeypatch.setenv/delenv/setattr(3.3) — always prefer these over mutatingos.environdirectly, because they undo themselves. - Filesystem.
tmp_pathgives each test a private directory; never write to the repo or home directory in tests.
5.5 Blocking the network in tests#
The strongest guarantee a fast suite can give: no test can open a socket. Two ways:
1. pytest-socket (0.8.1) — a plugin that disables socket use for the whole run:
# pyproject.toml — still one `addopts` line: edit the value from 2.4 in place
[tool.pytest.ini_options]
addopts = "-ra --strict-markers --disable-socket"uv run pytest --disable-socket --allow-hosts=127.0.0.1 # allow only localhost (e.g. a local test server)
uv run pytest --disable-socket --allow-unix-socket # allow Unix sockets too
uv run pytest -m live --force-enable-socket # exempt the live suiteAny test that reaches for the network fails immediately with SocketBlockedError — whichever HTTP library or mock tool it uses. This is the defence that catches the respx-doesn't-mock-httpx2 trap (7.2) and a thousand other "I thought it was mocked" bugs.
2. A hand-rolled guard — the ~15-line stdlib version, useful to understand what the plugin does and as a fallback:
# tests/conftest.py — autouse fixture: no test in this directory may open a socket
import socket
import pytest
class NetworkDisabledError(RuntimeError):
pass
def _blocked(*args, **kwargs):
raise NetworkDisabledError("network disabled in tests")
@pytest.fixture(autouse=True)
def _no_network(monkeypatch):
real_socket = socket.socket
class GuardedSocket(real_socket):
def connect(self, address):
raise NetworkDisabledError(f"network disabled in tests: connect to {address!r}")
def connect_ex(self, address):
raise NetworkDisabledError(f"network disabled in tests: connect_ex to {address!r}")
def sendto(self, data, *args):
raise NetworkDisabledError("network disabled in tests: sendto")
monkeypatch.setattr(socket, "socket", GuardedSocket)
monkeypatch.setattr(socket, "getaddrinfo", _blocked)
# the other name-lookup paths bypass getaddrinfo — block them too
monkeypatch.setattr(socket, "gethostbyname", _blocked)
monkeypatch.setattr(socket, "gethostbyaddr", _blocked)
monkeypatch.setattr(socket, "getnameinfo", _blocked)
yieldNote it patches getaddrinfo too — socket.create_connection resolves DNS before connect, so guarding only connect still leaks lookups (and on some systems, the lookup itself is enough to reach a DNS server). gethostbyname/gethostbyaddr/getnameinfo are the remaining lookup doors; pytest-socket covers all of them if you'd rather not hand-roll. (sendto takes *args because its real signature accepts either (data, address) or (data, flags, address) — a fixed two-arg override would TypeError instead of raising our error.) The monkeypatch fixture undoes all the patches after each test.
Running the equivalent logic directly (stdlib only):
import socket
class NetworkDisabledError(RuntimeError):
pass
def _blocked(*args, **kwargs):
raise NetworkDisabledError("network disabled in tests")
def disable_network():
real_socket = socket.socket
class GuardedSocket(real_socket):
def connect(self, address):
raise NetworkDisabledError(f"network disabled in tests: connect to {address!r}")
def connect_ex(self, address):
raise NetworkDisabledError(f"network disabled in tests: connect_ex to {address!r}")
def sendto(self, data, *args):
raise NetworkDisabledError("network disabled in tests: sendto")
socket.socket = GuardedSocket
socket.getaddrinfo = _blocked
socket.gethostbyname = _blocked
socket.gethostbyaddr = _blocked
socket.getnameinfo = _blocked
def fetch(url):
host = url.split("//", 1)[-1].split("/", 1)[0]
with socket.create_connection((host, 80), timeout=2) as s:
return s.recv(1024)
disable_network()
try:
fetch("http://api.example.com/v1/status")
except NetworkDisabledError as exc:
print("blocked:", exc)blocked: network disabled in testsPart 6: Testing async code#
6.1 pytest-asyncio#
pytest has no built-in async support — without a plugin, an async def test_* function is never awaited. Older pytest versions skipped such tests with a warning ("async def functions are not natively supported"); recent versions (8.4 onwards) fail them with the same message, so the mistake is loud rather than silent. Either way you need a plugin to run them. pytest-asyncio (1.4.1.post1 as of November 2026) is the standard plugin for asyncio code.
uv add --dev pytest-asyncioTwo ways to enable it:
# pyproject.toml — the recommended default for asyncio-only projects
# (01B.1's table already has this key; nothing to add if you followed it)
[tool.pytest.ini_options]
asyncio_mode = "auto"In auto mode, every async def test_* runs automatically — no decorator needed:
# tests/test_service_async.py
from aitoolkit.backend import ScriptedBackend
async def test_complete_returns_scripted_text():
backend = ScriptedBackend(replies={"hello": "world"}, latency=0)
result = await backend.complete("hello")
assert result.text == "world"
assert backend.calls[0]["mode"] == "complete"In strict mode (the plugin's default), you must mark each test and use pytest_asyncio.fixture for async fixtures:
import pytest
import pytest_asyncio
@pytest.mark.asyncio
async def test_complete_returns_text(scripted_backend):
...
@pytest_asyncio.fixture
async def api_client():
async with httpx.AsyncClient(transport=transport) as client:
yield clientStrict mode exists so projects using multiple async libraries (asyncio + trio, say) can coexist — each plugin only claims what it's told to. If your project is asyncio-only, auto mode is simpler, and it is the mode the pytest-asyncio docs describe as intended for projects whose only async library is asyncio.
Key behaviours worth knowing:
- One event loop per test by default (
loop_scope="function"), so async tests get the same isolation as sync ones — no state leaks between tests through the loop. @pytest.mark.asyncio(loop_scope="module")shares one loop across a module's tests — useful when you have expensive per-loop setup (an async client you want to build once). Every test that should share the loop must ask for the sameloop_scope; theasyncio_default_test_loop_scopeini option sets it for all tests at once.- Tests run sequentially, not concurrently — pytest-asyncio deliberately doesn't parallelise async tests, because concurrent tests would race on shared state. For parallelism you want
pytest-xdist(separate processes), not async concurrency within one test. - Async fixtures work in both modes:
@pytest_asyncio.fixturein strict, plain@pytest.fixturewithasync defin auto.
6.2 The anyio alternative#
If your code is written against anyio (the async compatibility layer used by httpx, starlette/FastAPI internals, and others) or you want to test against both asyncio and trio, the anyio pytest plugin (part of anyio itself, 4.16.0) is the alternative:
[tool.pytest.ini_options]
anyio_mode = "auto" # or mark tests with @pytest.mark.anyioimport pytest
pytestmark = pytest.mark.anyio # applies to every test in the module
async def test_something():
...The plugin runs each test on the backend named by the anyio_backend fixture — "asyncio" by default, "trio" if you override it. You can even parametrise it to run the same test on both backends.
6.3 Testing timeouts, cancellation and concurrency without sleeps#
The cardinal sin of async tests is await asyncio.sleep(0.2) "to let things settle" — it's slow, flaky, and proves nothing. The alternatives:
Test ordering with recorded calls, not timing. Have the fake record what it saw; assert on the record:
import asyncio
class ReplyRouter: # a minimal stand-in for this demo —
"""Not the module fake: the real one is aitoolkit.backend.ScriptedBackend."""
def __init__(self, replies):
self.replies = replies # prompt -> canned reply
self.calls = [] # every prompt seen, in the order calls finished
async def complete(self, prompt):
self.calls.append(prompt)
return self.replies[prompt]
async def worker(backend, prompt, yields):
for _ in range(yields):
await asyncio.sleep(0) # yield to the loop; no real time passes
return await backend.complete(prompt)
async def main():
backend = ReplyRouter({"slow": "S", "fast": "F", "mid": "M"})
# 'slow' yields most, so it finishes LAST; 'fast' yields least, finishes FIRST.
tasks = [
worker(backend, "slow", 5),
worker(backend, "fast", 1),
worker(backend, "mid", 3),
]
results = await asyncio.gather(*tasks)
print("results (input order):", results)
print("calls (finish order):", backend.calls)
asyncio.run(main())results (input order): ['S', 'F', 'M']
calls (finish order): ['fast', 'mid', 'slow']asyncio.gather returns results in input order even though the tasks finished out of order — a test can assert both facts deterministically: results == ["S", "F", "M"] and backend.calls == ["fast", "mid", "slow"]. The await asyncio.sleep(0) yields control without waiting real time, so the interleaving is deterministic.
Test timeouts with a fake that hangs, not a real delay. If your code wraps a call in asyncio.timeout(0.05), the test doesn't need a 50 ms sleep — give the fake a complete that awaits an asyncio.Event that never gets set, and assert the timeout fires:
import asyncio
import pytest
class HangingBackend:
"""complete() never returns — for timeout tests only."""
async def complete(self, prompt):
await asyncio.Event().wait() # the event is never set: hangs forever
@pytest.mark.asyncio
async def test_timeout_fires_on_hung_backend():
with pytest.raises(TimeoutError):
await asyncio.wait_for(HangingBackend().complete("hi"), timeout=0.01)The 10 ms timeout is real but tiny — the test proves the mechanism (the timeout propagates as TimeoutError, and wait_for cancels the hung coroutine on the way out), not the wall-clock duration.
Test cancellation explicitly. task.cancel() raises CancelledError inside the coroutine at its next await; your code should let it propagate (never swallow it — that's a bug, see 01B.3). A test can assert the cleanup ran:
async def test_cancellation_closes_client():
closed = False
async def worker():
nonlocal closed
try:
await asyncio.sleep(10)
finally:
closed = True
task = asyncio.create_task(worker())
await asyncio.sleep(0) # let it start
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert closed is True # finally ran during cancellationTest TaskGroup exception groups. asyncio.TaskGroup raises ExceptionGroup on child failure; assert with except* or pytest.raises(ExceptionGroup) — or, better, pytest.RaisesGroup/pytest.RaisesExc (added in pytest 8.4), which let you assert which sub-exceptions the group contains instead of just that a group arrived.
Part 7: Testing HTTP clients and APIs#
7.1 httpx.MockTransport: fake the network, keep the client#
httpx.MockTransport lets you give an httpx.Client/AsyncClient a handler function that returns canned httpx.Response objects — the real client code (request building, headers, JSON encoding, error handling) runs untouched, only the wire is fake.
# tests/test_http_client.py
import httpx
import pytest
from aitoolkit.http import TicketAPIError, TicketClient
@pytest.fixture
def ticket_client(monkeypatch):
"""A TicketClient whose inner httpx.Client answers from `handler` — no network."""
real_client = httpx.Client # captured once, before any patching
def make(handler) -> TicketClient:
transport = httpx.MockTransport(handler)
# TicketClient builds its httpx.Client in __init__ with no transport=
# seam — patch httpx.Client where __init__ looks it up (7.1 explains).
monkeypatch.setattr(httpx, "Client",
lambda **kw: real_client(transport=transport, **kw))
return TicketClient(token="test-token")
return make
def test_get_ticket_parses_response(ticket_client):
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/v1/tickets/42"
assert request.headers["authorization"] == "Bearer test-token"
return httpx.Response(200, json={
"id": "T-42", "title": "Refund", "status": "open", "priority": "high",
})
with ticket_client(handler) as client:
ticket = client.get_ticket(42)
assert ticket["id"] == "T-42" and ticket["status"] == "open"
def test_404_maps_to_ticket_api_error(ticket_client):
def handler(request):
return httpx.Response(404, json={
"error": {"code": "not_found", "message": "no such ticket"}})
with ticket_client(handler) as client:
with pytest.raises(TicketAPIError) as excinfo:
client.get_ticket(999)
assert excinfo.value.status == 404
assert excinfo.value.code == "not_found"
def test_timeout_is_not_an_api_error(ticket_client):
def handler(request):
raise httpx.ReadTimeout("simulated timeout", request=request)
with ticket_client(handler) as client:
# transport failures propagate as httpx errors, not TicketAPIError —
# _raise_for_api only sees responses that arrived
with pytest.raises(httpx.TimeoutException):
client.get_ticket(1)Why this beats mocking client.get_ticket itself: the test exercises the client's real request construction — base-URL joining (/v1/tickets/42), the Authorization header, params encoding — so a bug in "how we build the request" is caught, not just "how we handle the response". get_ticket returns the decoded dict; validating it into a Ticket model is 01B.6's layer (and a good candidate for a Ticket.model_validate line inside get_ticket later).
7.2 respx and the httpx2 trap#
respx (0.23.1) is the higher-level router for httpx: declare routes, return responses, assert they were called.
# tests/test_respx.py
import httpx
import pytest
def test_respx_route(respx_mock):
route = respx_mock.get("https://tickets.example/tickets/1").mock(
return_value=httpx.Response(200, json={"id": 1, "title": "A"})
)
resp = httpx.get("https://tickets.example/tickets/1")
assert resp.status_code == 200
assert route.called
assert route.call_count == 1The respx_mock fixture is function-scoped and resets between tests; @pytest.mark.respx(base_url=...) sets a base URL for the whole module.
7.3 FastAPI TestClient and dependency overrides#
To test an incoming API (your FastAPI service from 01B.7), use TestClient — it runs the ASGI app in-process, no server needed:
# tests/test_service.py
import pytest
from fastapi.testclient import TestClient
from aitoolkit.backend import ScriptedBackend
from aitoolkit.service import app, get_backend
# every /v1/* route sits behind Security(require_api_key): send the demo key
API_KEY = {"X-API-Key": "demo-key-alice"}
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture
def fake_backend():
"""Swap the lifespan-built backend for a scripted one; restore after."""
backend = ScriptedBackend(replies={"France": "Paris"}, latency=0, stream_delay=0)
app.dependency_overrides[get_backend] = lambda: backend
yield backend
app.dependency_overrides.pop(get_backend, None)
def test_health(client):
resp = client.get("/health") # unversioned, no key needed
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "ok" and body["service"] == "aitoolkit"
def test_echo_roundtrip(client):
resp = client.post("/v1/echo", json={"message": "hello"}, headers=API_KEY)
assert resp.json() == {"message": "hello", "length": 5}
def test_v1_rejects_missing_key(client):
resp = client.post("/v1/echo", json={"message": "hello"})
assert resp.status_code == 401
def test_v1_rejects_wrong_key(client):
resp = client.post("/v1/echo", json={"message": "hello"},
headers={"X-API-Key": "wrong-key"})
assert resp.status_code == 401
def test_validation_error_uses_the_error_envelope(client):
resp = client.post("/v1/echo", json={"message": ""}, headers=API_KEY)
assert resp.status_code == 422 # min_length=1 on EchoIn
assert resp.json()["error"]["code"] == "validation_error" # service's envelope
def test_complete_uses_fake_backend(client, fake_backend):
resp = client.post("/v1/complete", json={"prompt": "capital of France?"},
headers=API_KEY)
assert resp.status_code == 200
body = resp.json()
assert body["text"] == "Paris" # the Completion model's reply field
assert body["finish_reason"] == "stop"
def test_stream_yields_sse_events(client, fake_backend):
with client.stream("POST", "/v1/stream", json={"prompt": "hi"},
headers=API_KEY) as resp:
assert resp.headers["content-type"].startswith("text/event-stream")
body = "".join(resp.iter_text())
assert "event: token" in body
assert "event: done" in body and "[DONE]" in bodyKey points:
TestClient(app)is synchronous even though the app is async — it runs an anyio portal under the hood. For async tests, usehttpx.AsyncClient(transport=httpx.ASGITransport(app=app))instead.app.dependency_overridesswaps aDepends(...)/Security(...)callable for a test double — the FastAPI equivalent of constructor injection. Thefake_backendfixture clears its override on teardown so it can't leak into other tests.- Auth is part of the contract.
/v1/*runsrequire_api_keyagainst theDEMO_API_KEYSmap inservice.py; the tests send a real (demo) key and assert 401s — you are testing the auth wiring, not bypassing it. - 422 responses come back in the service's
{"error": {"code", "message", "details"}}envelope, not FastAPI's default{"detail": ...}— the customRequestValidationErrorhandler from 01B.7 shapes it. Assert the envelope, not just the status. raise_server_exceptions=FalseonTestClientturns unhandled exceptions into 500s instead of raising in the test — useful for testing your error handler, dangerous if overused (it hides real bugs).
7.4 Testing streaming and SSE#
For an SSE endpoint (01B.7's POST /v1/stream), TestClient.stream iterates the response body — the full version lives in 9.2; the shape:
def test_stream_yields_sse_events():
app.dependency_overrides[get_backend] = lambda: ScriptedBackend(
replies={"hi": "Hello world"}, latency=0, stream_delay=0)
try:
client = TestClient(app)
with client.stream("POST", "/v1/stream", json={"prompt": "hi"},
headers={"X-API-Key": "demo-key-alice"}) as resp:
assert resp.headers["content-type"].startswith("text/event-stream")
body = "".join(resp.iter_text())
assert "event: token" in body # one ServerSentEvent per chunk
assert "event: done" in body and "[DONE]" in body
finally:
app.dependency_overrides.clear()For the parser side (01B.5's SSE parser), test it as a pure function on fixture text — feed it a string containing data:, event:, id:, comments and [DONE], assert the parsed events. That keeps the wire-format test fast and deterministic.
7.5 Testing retries, error mapping and flaky fakes#
The pattern that matters most for AI code: a fake that fails N times then succeeds, proving your retry logic works without real waiting.
# tests/test_resilience.py
import pytest
from tenacity import stop_after_attempt, wait_none
from aitoolkit.resilience import is_transient, retry_async
class FlakyBackend:
"""A fake that raises `exc` for its first `failures` calls, then returns 'ok'.
Raises TimeoutError by default — is_transient() retries it. Pass
exc=ValueError for a permanent failure. (ScriptedBackend.fail_first
raises RuntimeError, which is_transient treats as permanent — wrong
exception type for retry tests.)
"""
def __init__(self, failures: int, exc: type[Exception] = TimeoutError):
self.failures = failures
self.exc = exc
self.calls = 0
async def __call__(self):
self.calls += 1
if self.calls <= self.failures:
raise self.exc("simulated failure")
return "ok"
@pytest.mark.asyncio
async def test_retry_recovers_after_transient_failures():
backend = FlakyBackend(failures=2) # TimeoutError -> transient
run = retry_async(stop=stop_after_attempt(3), wait=wait_none())
result = await run(backend)() # decorator + instant waits
assert result == "ok" and backend.calls == 3
@pytest.mark.asyncio
async def test_retry_does_not_retry_permanent_errors():
backend = FlakyBackend(failures=99, exc=ValueError) # permanent: never retried
run = retry_async(stop=stop_after_attempt(3), wait=wait_none())
with pytest.raises(ValueError):
await run(backend)()
assert backend.calls == 1
@pytest.mark.asyncio
async def test_retry_gives_up_after_attempts():
backend = FlakyBackend(failures=99)
run = retry_async(stop=stop_after_attempt(3), wait=wait_none())
with pytest.raises(TimeoutError):
await run(backend)()
assert backend.calls == 3 # stopped at the capwait_none() (or any injected wait=/sleep=) makes retries instant — you're testing the logic (which errors retry via is_transient, how many attempts stop_after_attempt allows), not the wall-clock backoff. retry_async here is 01B.9's decorator factory over tenacity; call_with_retry(fn, *args, policy=...) is its function-call twin for cases a decorator can't express. The FlakyBackend is the same shape 01B.9 uses — a callable that fails N times then succeeds.
Part 8: Coverage, speed and CI#
Deep-dive
8.1 pytest-cov: statement and branch coverage#
pytest-cov (7.1.0) wraps coverage.py and reports which lines your tests executed.
uv run pytest --cov=aitoolkit --cov-report=term-missing
uv run pytest --cov=aitoolkit --cov-branch --cov-report=term-missing # branch coverage tooName Stmts Miss Branch BrPart Cover Missing
-----------------------------------------------------------------------
aitoolkit/__init__.py 0 0 0 0 100%
aitoolkit/concurrency.py 45 3 12 2 91% 88-90, 102->105
aitoolkit/http.py 62 8 20 4 84% 45-52, 78
aitoolkit/models.py 38 0 10 0 100%
aitoolkit/resilience.py 55 5 18 3 89% 120-124
aitoolkit/service.py 71 12 22 5 80% 88-95, 140-148
-----------------------------------------------------------------------
TOTAL 271 28 82 14 86%What coverage does and doesn't tell you:
- Statement coverage (default) — did this line run? Branch coverage (
--cov-branch) — did both sides of everyif/for/whilerun? Branch coverage catches "theexceptpath was never tested" that statement coverage misses. - Coverage is a floor, not a target. 100% coverage is achievable with vacuous tests (
assert Truecovers lines). It tells you what you didn't test, not whether your tests are good. Missingcolumn — the line numbers not covered. Use it to find untested error paths, not to chase a percentage.fail_underin config makes CI fail below a threshold:
# the same single `addopts` line, extended (it keeps the flags from 2.4 and 5.5)
[tool.pytest.ini_options]
addopts = "-ra --strict-markers --disable-socket --cov=aitoolkit --cov-report=term-missing --cov-fail-under=80"Putting the coverage flags in addopts means every run measures coverage, so running one test file (uv run pytest tests/test_models.py) fails the 80% gate. If that annoys you, leave addopts as it was after 5.5 and pass the --cov options on the command line, as the CI job in 8.3 does.
Coverage's own settings live in pyproject.toml too, under [tool.coverage.*], so every run (local, CI, IDE) measures the same way:
[tool.coverage.run]
branch = true # same as --cov-branch
source = ["aitoolkit"] # measure the package, not the tests or site-packages
[tool.coverage.report]
show_missing = true
exclude_also = [ # lines that need no test
"if TYPE_CHECKING:",
"raise NotImplementedError",
"^\\s*\\.\\.\\.$", # a line that is only `...` (protocol / abstract bodies)
]A line can also opt out with a # pragma: no cover comment; use it for genuinely untestable code (a __main__ guard, a platform branch) and review each one like a code comment, because every pragma is a promise that someone looked. Two more habits: generate an HTML report (--cov-report=html, open htmlcov/index.html) when you want to see the uncovered branches highlighted line by line, and treat a falling percentage in a pull request as a question to ask ("what did this change leave untested?"), not a rule to satisfy.
8.2 Speed: pytest-xdist, warnings and mutation testing awareness#
pytest-xdist(3.8.0) —pytest -n autoruns tests across CPU cores in separate processes. Near-linear speedup for CPU-bound suites; less useful for I/O-bound async tests (they're already fast). Watch for tests that share state (files, ports, env vars) — xdist exposes them.-W error— turns warnings into errors. CatchesDeprecationWarnings from your code and deps before they become breakage. Pair withfilterwarningsexceptions for known noise.--durations=10— shows the 10 slowest tests/setup/teardown. Run it after any suite grows; one 5-second test can dominate a 30-second suite.pytest-timeout(2.4.0 is the latest non-yanked release on PyPI as of November 2026 — a 2.5.0 upload of 16 August 2026 was yanked — and its metadata asks only forpytest>=7.0.0, with no upper cap, so it installs alongside pytest 9.2) —timeout = 10under[tool.pytest.ini_options], or@pytest.mark.timeout(5)on one test, fails any test that runs longer instead of letting it hang the CI job until the 10-minutetimeout-minuteskills everything. A hungawaiton a fake that never answers is the classic cause. Treat a timeout failure as a bug in the test or in the code, never as a reason to raise the number.- Random order —
pytest-randomly(5.1.0 as of November 2026, released 8 November; it requires Python 3.11+ andpytest>=8) shuffles test order and reseedsrandomper test, so hidden order dependence shows up as a failure on your machine instead of a mystery in CI. It installs itself as a plugin (nothing to configure) and prints the seed it used at the top of the run; reproduce a failing order withpytest --randomly-seed=1234, and switch it off with-p no:randomlywhen you need a stable order for debugging. - Debugging a failure —
pytest --pdbdrops intopdbat the failing assertion (01B.10 covers the debugger),-l/--showlocalsprints local variables in the traceback,-vvshows full diffs instead of truncated ones, and--lf -xre-runs just the last failure and stops at the first. - Mutation testing (awareness) — tools like
mutmutorcosmic-rayintroduce small bugs (mutants) into your code and check whether your tests catch them. High coverage + surviving mutants = weak tests. It's slow, so run it occasionally, not per-commit.
8.3 CI: GitHub Actions and pre-commit#
The fast suite belongs in CI on every push — it's deterministic, offline, and seconds fast. A minimal workflow:
# .github/workflows/tests.yml
name: tests
on: [push, pull_request]
permissions:
contents: read
jobs:
test:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.3.3
with:
python-version: "3.13"
- run: uv sync --frozen
# one run: fast suite only, with coverage gate and a JUnit report
- run: >
uv run pytest -m "not live and not integration"
--cov=aitoolkit --cov-branch --cov-fail-under=80 --junitxml=report.xmlKey points:
uv sync --frozeninstalls exactly the lockfile — same versions locally and in CI.- One
pytestrun, not two. A second bareuv run pytest --cov=...step would also collect theliveandintegrationtests, because nothing but-mexcludes them. Put the marker expression and the coverage options on the same command. --junitxml=report.xmlwrites JUnit-format results you can upload as a CI artifact (GitHub Actions' test reporters andactions/upload-artifactconsume it) — the standard way to get per-test pass/fail detail on a PR without reading raw logs.-m "not live and not integration"keeps the fast suite key-free and network-free; live tests run on a schedule (03.10, 12, 11C.2).- Pre-commit can run
pyteston changed files before commit — the 01B.1 pre-commit config is the place to add it. - Git and GitHub workflows themselves are 00.4's territory; in real repos, pin action versions to a full commit SHA (with a
# vX.Y.Zcomment) rather than a floating major tag — a moved tag is a supply-chain hole.
Part 9: Test-driven habits and the aitoolkit suite#
Deep-dive
aitoolkit suite#9.1 Red–green–refactor, worked#
The loop: write a failing test (red), write the minimum code to pass (green), then clean up (refactor) while the test stays green.
Here's the whole thing in stdlib Python, so you can run it right now — a ~15-line test runner that shows what pytest automates:
# mini_runner.py — what pytest does, minus fixtures/assertion-rewriting/selection
import sys
def cart_total(items):
return sum(i["price"] * i["qty"] for i in items)
def test_total_sums_price_times_qty():
items = [{"price": 2.5, "qty": 4}, {"price": 1.0, "qty": 3}]
assert cart_total(items) == 13.0, "2.5*4 + 1.0*3 should be 13.0"
def test_total_empty_cart_is_zero():
assert cart_total([]) == 0, "an empty cart totals zero"
def test_total_rejects_negative_qty():
# Fails on purpose: cart_total lets a negative quantity through.
items = [{"price": 5.0, "qty": -2}]
assert cart_total(items) == 0, "negative quantities must be rejected"
def run_tests(module):
tests = [(n, f) for n, f in vars(module).items()
if n.startswith("test_") and callable(f)]
failed = 0
for name, fn in tests:
try:
fn()
except Exception as exc:
failed += 1
detail = str(exc) or type(exc).__name__
print(f"FAIL {name}: {detail}")
else:
print(f"PASS {name}")
print(f"{len(tests) - failed} passed, {failed} failed")
return 1 if failed else 0
if __name__ == "__main__":
sys.exit(run_tests(sys.modules[__name__]))Run it (python3 mini_runner.py):
PASS test_total_sums_price_times_qty
PASS test_total_empty_cart_is_zero
FAIL test_total_rejects_negative_qty: negative quantities must be rejected
2 passed, 1 failedThat's red: the test caught a real bug — cart_total silently accepts qty=-2 and returns -10.0. Now the fix (green):
def cart_total(items):
total = 0.0
for i in items:
qty = i["qty"]
if qty < 0:
raise ValueError("negative quantity")
total += i["price"] * qty
return totalAnd the test updated to expect the ValueError:
def test_total_rejects_negative_qty():
items = [{"price": 5.0, "qty": -2}]
try:
cart_total(items)
except ValueError:
pass
else:
raise AssertionError("negative quantities must be rejected")Run it again. Copy mini_runner.py to mini_runner_fixed.py, replace its cart_total and test_total_rejects_negative_qty with the two versions above, and run python3 mini_runner_fixed.py:
PASS test_total_sums_price_times_qty
PASS test_total_empty_cart_is_zero
PASS test_total_rejects_negative_qty
3 passed, 0 failedGreen. Now refactor — extract the validation, keep the tests green:
def _validate_qty(qty):
if qty < 0:
raise ValueError(f"negative quantity: {qty}")
return qty
def cart_total(items):
return sum(i["price"] * _validate_qty(i["qty"]) for i in items)The tests still pass — the behaviour contract is unchanged, only the structure improved. That's the loop: test first, minimal code, refactor with confidence.
9.2 The aitoolkit/tests/ suite#
Here is the complete test suite for the aitoolkit package — the deliverable of this lesson. It assumes the modules built in 01B.2–01B.9 (settings.py, backend.py, models.py, concurrency.py, resilience.py, http.py, service.py).
Layout mirrors the package. tests/ sits at the project root next to src/aitoolkit/ and mirrors it: test_http.py exercises aitoolkit/http.py, test_service.py exercises aitoolkit/service.py. There is no sys.path trickery — from aitoolkit.backend import ScriptedBackend resolves because uv sync installed the project itself into its own environment (uv init --package makes aitoolkit importable; a --bare project would not be). When the package grows, add tests/test_<module>.py alongside the module it covers.
tests/conftest.py — shared fixtures, the socket guard and the settings-cache reset:
# tests/conftest.py
import socket
import pytest
from aitoolkit.backend import ScriptedBackend
from aitoolkit.settings import get_settings
class NetworkDisabledError(RuntimeError):
pass
def _blocked(*args, **kwargs):
raise NetworkDisabledError("network disabled in tests")
@pytest.fixture(autouse=True)
def _no_network(monkeypatch):
"""No test in this directory may open a socket."""
real_socket = socket.socket
class GuardedSocket(real_socket):
def connect(self, address):
raise NetworkDisabledError(f"connect to {address!r}")
def connect_ex(self, address):
raise NetworkDisabledError(f"connect_ex to {address!r}")
def sendto(self, data, *args):
raise NetworkDisabledError("sendto")
monkeypatch.setattr(socket, "socket", GuardedSocket)
monkeypatch.setattr(socket, "getaddrinfo", _blocked)
monkeypatch.setattr(socket, "gethostbyname", _blocked)
monkeypatch.setattr(socket, "gethostbyaddr", _blocked)
monkeypatch.setattr(socket, "getnameinfo", _blocked)
yield
@pytest.fixture(autouse=True)
def _reset_settings_cache():
"""get_settings() is lru_cached process-wide: clear it around every test so
a monkeypatch.setenv in one test can't leak a stale Settings into the next."""
get_settings.cache_clear()
yield
get_settings.cache_clear()
@pytest.fixture
def scripted_backend():
"""A ScriptedBackend with zero fake latency; tests script their own replies."""
return ScriptedBackend(latency=0, stream_delay=0)tests/test_settings.py — env config, secrets, fail-fast:
# tests/test_settings.py
import pytest
from pydantic import ValidationError
from aitoolkit.settings import get_settings
def test_settings_reads_env(monkeypatch):
monkeypatch.setenv("OPENAI_API_KEY", "sk-test-123")
monkeypatch.setenv("OPENAI_MODEL", "test-model")
s = get_settings() # cache cleared by the autouse fixture
assert s.openai_api_key.get_secret_value() == "sk-test-123"
assert s.openai_model == "test-model"
def test_secret_never_in_repr(monkeypatch):
monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-ant-super-secret")
s = get_settings()
assert "sk-ant-super-secret" not in repr(s)
assert "sk-ant-super-secret" not in str(s)
def test_invalid_value_fails_fast(monkeypatch):
monkeypatch.setenv("REQUEST_TIMEOUT_SECONDS", "-1") # Field(gt=0) violated
with pytest.raises(ValidationError):
get_settings()
def test_service_port_out_of_range_rejected(monkeypatch):
monkeypatch.setenv("SERVICE_PORT", "99999") # Field(le=65535) violated
with pytest.raises(ValidationError):
get_settings()
def test_get_settings_is_cached():
first = get_settings()
assert get_settings() is first # lru_cache: same object, built once
get_settings.cache_clear()
assert get_settings() is not first # after clear: rebuilt from envtests/test_models.py — Pydantic validation:
# tests/test_models.py
from datetime import datetime, timezone
import pytest
from pydantic import ValidationError
from aitoolkit.models import (
Completion, CompletionRequest, Priority, Status, Ticket, TicketIn, Usage,
)
def make_ticket(**overrides):
base = {
"id": "T-1042",
"title": "Login fails on Safari", # "title" is accepted via AliasChoices; the field is .subject
"requester": "sam",
"created_at": datetime(2026, 11, 1, 10, 0, tzinfo=timezone.utc),
}
return Ticket(**{**base, **overrides})
def test_ticket_valid():
t = make_ticket()
assert t.subject == "Login fails on Safari" # attribute is `subject`, not `title`
assert t.status == Status.OPEN # enum defaults applied
assert t.priority == Priority.NORMAL
assert t.votes == 0
def test_ticket_rejects_bad_status():
with pytest.raises(ValidationError):
make_ticket(status="bogus") # not a Status member
def test_ticket_rejects_missing_required_fields():
with pytest.raises(ValidationError): # `subject` is the only required field
Ticket()
def test_ticket_id_accepts_int_or_str():
# id: int | str — the API uses ints, fixtures use "T-1042" strings; both valid
assert make_ticket(id=1).id == 1
assert make_ticket(id="T-9").id == "T-9"
def test_ticketin_rejects_unknown_priority():
with pytest.raises(ValidationError):
TicketIn(title="Refund please", requester="sam", priority="ASAP")
def test_ticketin_strips_whitespace():
t = TicketIn(title=" Refund please ", requester="sam")
assert t.subject == "Refund please" # str_strip_whitespace: ends only
def test_ticketin_rejects_too_short_subject():
with pytest.raises(ValidationError): # TicketIn.subject has min_length=3
TicketIn(subject="hi")
def test_completion_request_defaults():
req = CompletionRequest(prompt="hello")
assert req.max_tokens == 256 # defaults applied
assert req.model == "fake-tiny"
assert req.temperature == 1.0
def test_completion_request_rejects_empty_prompt():
with pytest.raises(ValidationError): # min_length=1
CompletionRequest(prompt="")
def test_ticket_model_validate_json():
data = ('{"id": "T-9", "title": "Printer jam", "requester": "lee",'
' "created_at": "2026-11-02T09:30:00Z", "priority": "urgent"}')
t = Ticket.model_validate_json(data)
assert t.priority == Priority.URGENT
assert t.subject == "Printer jam" # the "title" key landed on .subject via the alias
assert t.created_at == datetime(2026, 11, 2, 9, 30, tzinfo=timezone.utc)
def test_model_validate_json_rejects_garbage():
with pytest.raises(ValidationError):
Ticket.model_validate_json("not json at all")
def test_usage_total_tokens():
assert Usage(input_tokens=3, output_tokens=4).total_tokens == 7
def test_completion_response_shape():
c = Completion(text="Paris", model="fake-tiny",
usage=Usage(input_tokens=2, output_tokens=1))
assert c.text == "Paris"
assert c.model == "fake-tiny"
assert c.finish_reason == "stop" # Literal default
assert c.usage.total_tokens == 3tests/test_concurrency.py — bounded fan-out, rate limiter, results:
# tests/test_concurrency.py
import asyncio
import pytest
from aitoolkit.backend import ScriptedBackend
from aitoolkit.concurrency import (
Err, Ok, RateLimiter, bounded_gather, run_pipeline,
)
class FakeClock:
"""Deterministic clock for RateLimiter: fake sleep advances time, nothing waits."""
def __init__(self) -> None:
self.t = 0.0
def now(self) -> float:
return self.t
async def sleep(self, seconds: float) -> None:
self.t += seconds
@pytest.mark.asyncio
async def test_bounded_gather_respects_limit(scripted_backend):
in_flight = 0
max_seen = 0
async def tracked(prompt):
nonlocal in_flight, max_seen
in_flight += 1
max_seen = max(max_seen, in_flight)
try:
return await scripted_backend.complete(prompt)
finally:
in_flight -= 1
results = await bounded_gather([tracked(f"p{i}") for i in range(10)], limit=3)
assert len(results) == 10
assert max_seen <= 3 # never more than `limit` in flight
@pytest.mark.asyncio
async def test_gather_preserves_input_order():
backend = ScriptedBackend(
replies={"slow": "S", "fast": "F", "mid": "M"}, latency=0,
)
async def delayed(prompt, n):
for _ in range(n):
await asyncio.sleep(0) # yield control; no real time passes
return await backend.complete(prompt)
results = await bounded_gather(
[delayed("slow", 5), delayed("fast", 1), delayed("mid", 3)],
limit=3,
)
# results come back in input order even though the tasks finish out of order
assert [r.text for r in results] == ["S", "F", "M"]
assert [c["prompt"] for c in backend.calls] == ["fast", "mid", "slow"]
@pytest.mark.asyncio
async def test_bounded_gather_first_exception_propagates():
async def ok():
return "fine"
async def bad():
raise ValueError("boom")
# bounded_gather has no return_exceptions flag: the first error propagates.
# For continue-on-error collection use run_pipeline (next test).
with pytest.raises(ValueError):
await bounded_gather([ok(), bad(), ok()], limit=2)
@pytest.mark.asyncio
async def test_run_pipeline_collects_partial_failures():
async def process(item):
if item == "bad":
raise ValueError("boom")
return item.upper()
results = await run_pipeline(["good", "bad", "also-good"], process, limit=2)
assert isinstance(results[0], Ok) and results[0].value == "GOOD"
assert isinstance(results[1], Err) and isinstance(results[1].error, ValueError)
assert isinstance(results[2], Ok) and results[2].value == "ALSO-GOOD"
@pytest.mark.asyncio
async def test_rate_limiter_waits_when_bucket_empty():
clock = FakeClock()
limiter = RateLimiter(rate=10.0, sleep=clock.sleep, now=clock.now)
for _ in range(10):
await limiter.acquire() # drains the burst bucket (capacity == rate)
assert clock.t == 0.0 # no waiting while tokens last
await limiter.acquire() # bucket empty -> waits for one token
assert clock.t == pytest.approx(0.1) # 1 token at 10/sec = 0.1s of fake timetests/test_resilience.py — retry, circuit breaker:
# tests/test_resilience.py
import httpx
import pytest
from tenacity import stop_after_attempt, wait_none
from aitoolkit.resilience import (
CircuitBreaker, CircuitOpenError, Deadline, is_transient, retry_async,
)
class FlakyBackend:
"""A fake that raises `exc` for its first `failures` calls, then returns 'ok'.
TimeoutError by default — is_transient() retries it. Pass exc=ValueError
for a permanent failure. (ScriptedBackend.fail_first raises RuntimeError,
which is_transient treats as permanent — wrong exception for retry tests.)
"""
def __init__(self, failures: int, exc: type[Exception] = TimeoutError):
self.failures = failures
self.exc = exc
self.calls = 0
async def __call__(self):
self.calls += 1
if self.calls <= self.failures:
raise self.exc("simulated failure")
return "ok"
class FakeClock:
def __init__(self) -> None:
self.t = 0.0
def now(self) -> float:
return self.t
def advance(self, seconds: float) -> None:
self.t += seconds
@pytest.mark.parametrize("exc, expected", [
(TimeoutError("x"), True),
(ConnectionError("x"), True),
(httpx.ConnectError("x", request=httpx.Request("GET", "http://x")), True),
(httpx.ReadTimeout("x", request=httpx.Request("GET", "http://x")), True),
(ValueError("x"), False),
(RuntimeError("x"), False), # what ScriptedBackend.fail_first raises: permanent
])
def test_is_transient_classification(exc, expected):
assert is_transient(exc) is expected
@pytest.mark.asyncio
async def test_retry_recovers_after_transient_failures():
backend = FlakyBackend(failures=2) # TimeoutError -> transient
run = retry_async(stop=stop_after_attempt(3), wait=wait_none())
result = await run(backend)() # decorator + instant waits
assert result == "ok" and backend.calls == 3
@pytest.mark.asyncio
async def test_retry_does_not_retry_permanent_errors():
backend = FlakyBackend(failures=99, exc=ValueError) # permanent: never retried
run = retry_async(stop=stop_after_attempt(3), wait=wait_none())
with pytest.raises(ValueError):
await run(backend)()
assert backend.calls == 1
@pytest.mark.asyncio
async def test_retry_gives_up_after_attempts():
backend = FlakyBackend(failures=99)
run = retry_async(stop=stop_after_attempt(3), wait=wait_none())
with pytest.raises(TimeoutError):
await run(backend)()
assert backend.calls == 3 # stopped at the cap
@pytest.mark.asyncio
async def test_circuit_breaker_opens_and_fails_fast():
breaker = CircuitBreaker(failure_threshold=2, reset_timeout=30.0)
dead = FlakyBackend(failures=99)
for _ in range(2):
with pytest.raises(TimeoutError):
await breaker.acall(dead)
with pytest.raises(CircuitOpenError):
await breaker.acall(dead) # fails fast — dead.calls doesn't grow
assert dead.calls == 2
@pytest.mark.asyncio
async def test_circuit_breaker_half_open_probe_recovers():
clock = FakeClock()
breaker = CircuitBreaker(failure_threshold=1, reset_timeout=30.0, clock=clock.now)
flaky = FlakyBackend(failures=1)
with pytest.raises(TimeoutError):
await breaker.acall(flaky) # fails once -> open
with pytest.raises(CircuitOpenError):
await breaker.acall(flaky) # open: fails fast, flaky.calls stays 1
clock.advance(31.0)
result = await breaker.acall(flaky) # half-open probe succeeds -> closed
assert result == "ok" and flaky.calls == 2
assert breaker.state == CircuitBreaker.CLOSED
def test_deadline_expires():
assert Deadline(seconds=60).expired is False
assert Deadline(seconds=-1).expired is True # already past: no waiting neededtests/test_http.py — MockTransport for the HTTP client:
# tests/test_http.py
import httpx
import pytest
from aitoolkit.http import TicketAPIError, TicketClient
@pytest.fixture
def ticket_client(monkeypatch):
"""A TicketClient whose inner httpx.Client answers from `handler` — no network."""
real_client = httpx.Client # captured once, before any patching
def make(handler) -> TicketClient:
transport = httpx.MockTransport(handler)
# TicketClient builds its httpx.Client in __init__ with no transport=
# seam — patch httpx.Client where __init__ looks it up (7.1 explains).
monkeypatch.setattr(httpx, "Client",
lambda **kw: real_client(transport=transport, **kw))
return TicketClient(token="test-token")
return make
def test_get_ticket_parses_response(ticket_client):
def handler(request: httpx.Request) -> httpx.Response:
assert request.url.path == "/v1/tickets/42"
assert request.headers["authorization"] == "Bearer test-token"
return httpx.Response(200, json={
"id": "T-42", "title": "Refund", "status": "open", "priority": "high",
})
with ticket_client(handler) as client:
ticket = client.get_ticket(42)
assert ticket["id"] == "T-42" and ticket["status"] == "open"
def test_404_maps_to_ticket_api_error(ticket_client):
def handler(request):
return httpx.Response(404, json={
"error": {"code": "not_found", "message": "no such ticket"}})
with ticket_client(handler) as client:
with pytest.raises(TicketAPIError) as excinfo:
client.get_ticket(999)
assert excinfo.value.status == 404
assert excinfo.value.code == "not_found"
def test_timeout_is_not_an_api_error(ticket_client):
def handler(request):
raise httpx.ReadTimeout("simulated", request=request)
with ticket_client(handler) as client:
# transport failures propagate as httpx errors, not TicketAPIError —
# _raise_for_api only sees responses that arrived
with pytest.raises(httpx.TimeoutException):
client.get_ticket(1)
def test_iter_tickets_follows_cursor(ticket_client):
seen = []
def handler(request: httpx.Request) -> httpx.Response:
cursor = request.url.params.get("cursor")
seen.append(cursor)
if cursor is None:
return httpx.Response(200, json={
"items": [{"id": "T-1"}], "next_cursor": "c2"})
return httpx.Response(200, json={
"items": [{"id": "T-2"}], "next_cursor": None})
with ticket_client(handler) as client:
tickets = list(client.iter_tickets())
assert [t["id"] for t in tickets] == ["T-1", "T-2"]
assert seen == [None, "c2"]
@pytest.mark.asyncio
async def test_async_client_shares_the_pattern(monkeypatch):
from aitoolkit.http import AsyncTicketClient
def handler(request: httpx.Request) -> httpx.Response:
return httpx.Response(200, json={"id": "T-7", "title": "Async"})
transport = httpx.MockTransport(handler)
real_async_client = httpx.AsyncClient
monkeypatch.setattr(httpx, "AsyncClient",
lambda **kw: real_async_client(transport=transport, **kw))
async with AsyncTicketClient(token="test-token") as client:
ticket = await client.get_ticket(7)
assert ticket["id"] == "T-7"tests/test_service.py — FastAPI TestClient:
# tests/test_service.py
import pytest
from fastapi.testclient import TestClient
from aitoolkit.backend import ScriptedBackend
from aitoolkit.service import app, get_backend
# every /v1/* route sits behind Security(require_api_key): send the demo key
API_KEY = {"X-API-Key": "demo-key-alice"}
@pytest.fixture
def client():
return TestClient(app)
@pytest.fixture
def fake_backend():
"""Swap the lifespan-built backend for a scripted one; restore after."""
backend = ScriptedBackend(replies={"France": "Paris"}, latency=0, stream_delay=0)
app.dependency_overrides[get_backend] = lambda: backend
yield backend
app.dependency_overrides.pop(get_backend, None)
def test_health(client):
resp = client.get("/health") # unversioned, no key needed
assert resp.status_code == 200
body = resp.json()
assert body["status"] == "ok" and body["service"] == "aitoolkit"
def test_echo_roundtrip(client):
resp = client.post("/v1/echo", json={"message": "hello"}, headers=API_KEY)
assert resp.json() == {"message": "hello", "length": 5}
def test_v1_rejects_missing_key(client):
resp = client.post("/v1/echo", json={"message": "hello"})
assert resp.status_code == 401
def test_v1_rejects_wrong_key(client):
resp = client.post("/v1/echo", json={"message": "hello"},
headers={"X-API-Key": "wrong-key"})
assert resp.status_code == 401
def test_validation_error_uses_the_error_envelope(client):
resp = client.post("/v1/echo", json={"message": ""}, headers=API_KEY)
assert resp.status_code == 422 # min_length=1 on EchoIn
assert resp.json()["error"]["code"] == "validation_error" # service's envelope
def test_complete_uses_fake_backend(client, fake_backend):
resp = client.post("/v1/complete", json={"prompt": "capital of France?"},
headers=API_KEY)
assert resp.status_code == 200
body = resp.json()
assert body["text"] == "Paris" # the Completion model's reply field
assert body["finish_reason"] == "stop"
def test_stream_yields_sse_events(client, fake_backend):
with client.stream("POST", "/v1/stream", json={"prompt": "hi"},
headers=API_KEY) as resp:
assert resp.headers["content-type"].startswith("text/event-stream")
body = "".join(resp.iter_text())
assert "event: token" in body
assert "event: done" in body and "[DONE]" in bodyRun the suite:
uv run pytest -v============================= test session starts ==============================
collected 47 items
tests/test_settings.py::test_settings_reads_env PASSED [ 2%]
tests/test_settings.py::test_secret_never_in_repr PASSED [ 4%]
tests/test_settings.py::test_invalid_value_fails_fast PASSED [ 6%]
tests/test_settings.py::test_service_port_out_of_range_rejected PASSED [ 9%]
tests/test_settings.py::test_get_settings_is_cached PASSED [ 11%]
tests/test_models.py::test_ticket_valid PASSED [ 13%]
tests/test_models.py::test_ticket_rejects_bad_status PASSED [ 15%]
tests/test_models.py::test_ticket_rejects_missing_required_fields PASSED [ 17%]
tests/test_models.py::test_ticket_id_accepts_int_or_str PASSED [ 19%]
tests/test_models.py::test_ticketin_rejects_unknown_priority PASSED [ 21%]
tests/test_models.py::test_ticketin_strips_whitespace PASSED [ 23%]
tests/test_models.py::test_ticketin_rejects_too_short_subject PASSED [ 26%]
tests/test_models.py::test_completion_request_defaults PASSED [ 28%]
tests/test_models.py::test_completion_request_rejects_empty_prompt PASSED [ 30%]
tests/test_models.py::test_ticket_model_validate_json PASSED [ 32%]
tests/test_models.py::test_model_validate_json_rejects_garbage PASSED [ 34%]
tests/test_models.py::test_usage_total_tokens PASSED [ 36%]
tests/test_models.py::test_completion_response_shape PASSED [ 38%]
tests/test_concurrency.py::test_bounded_gather_respects_limit PASSED [ 40%]
tests/test_concurrency.py::test_gather_preserves_input_order PASSED [ 43%]
tests/test_concurrency.py::test_bounded_gather_first_exception_propagates PASSED [ 45%]
tests/test_concurrency.py::test_run_pipeline_collects_partial_failures PASSED [ 47%]
tests/test_concurrency.py::test_rate_limiter_waits_when_bucket_empty PASSED [ 49%]
tests/test_resilience.py::test_is_transient_classification[exc0-True] PASSED [ 51%]
tests/test_resilience.py::test_is_transient_classification[exc1-True] PASSED [ 53%]
tests/test_resilience.py::test_is_transient_classification[exc2-True] PASSED [ 55%]
tests/test_resilience.py::test_is_transient_classification[exc3-True] PASSED [ 57%]
tests/test_resilience.py::test_is_transient_classification[exc4-False] PASSED [ 60%]
tests/test_resilience.py::test_is_transient_classification[exc5-False] PASSED [ 62%]
tests/test_resilience.py::test_retry_recovers_after_transient_failures PASSED [ 64%]
tests/test_resilience.py::test_retry_does_not_retry_permanent_errors PASSED [ 66%]
tests/test_resilience.py::test_retry_gives_up_after_attempts PASSED [ 68%]
tests/test_resilience.py::test_circuit_breaker_opens_and_fails_fast PASSED [ 70%]
tests/test_resilience.py::test_circuit_breaker_half_open_probe_recovers PASSED [ 72%]
tests/test_resilience.py::test_deadline_expires PASSED [ 74%]
tests/test_http.py::test_get_ticket_parses_response PASSED [ 77%]
tests/test_http.py::test_404_maps_to_ticket_api_error PASSED [ 79%]
tests/test_http.py::test_timeout_is_not_an_api_error PASSED [ 81%]
tests/test_http.py::test_iter_tickets_follows_cursor PASSED [ 83%]
tests/test_http.py::test_async_client_shares_the_pattern PASSED [ 85%]
tests/test_service.py::test_health PASSED [ 87%]
tests/test_service.py::test_echo_roundtrip PASSED [ 89%]
tests/test_service.py::test_v1_rejects_missing_key PASSED [ 91%]
tests/test_service.py::test_v1_rejects_wrong_key PASSED [ 94%]
tests/test_service.py::test_validation_error_uses_the_error_envelope PASSED [ 96%]
tests/test_service.py::test_complete_uses_fake_backend PASSED [ 98%]
tests/test_service.py::test_stream_yields_sse_events PASSED [100%]
============================== 47 passed in 1.41s ==============================Notice what's not there: no API keys, no network, no real model, no sleeps. Every test is deterministic — the only "waiting" is asyncio.sleep(0) yields and a fake clock. (The 47 counts the six is_transient parametrised cases individually.)
9.3 unittest for real — and what pytest adds#
unittest is stdlib — it works with zero installs, and pytest can run unittest.TestCase classes natively. Two reasons to care:
- Legacy suites — if you inherit a
unittest-based project, pytest runs it unchanged. - Understanding the baseline — seeing what
unittestgives you makes pytest's additions (fixtures, parametrize, assertion rewriting, plugins) concrete.
# test_cart_unittest.py — runs with: python3 -m unittest test_cart_unittest -v
import unittest
from unittest.mock import Mock
class CartTest(unittest.TestCase):
def test_add_item(self):
cart = {}
cart["MUG-1"] = cart.get("MUG-1", 0) + 2
self.assertEqual(cart, {"MUG-1": 2})
def test_mock_side_effect(self):
flaky = Mock(side_effect=[TimeoutError, TimeoutError, "ok"])
for _ in range(3):
try:
result = flaky("prompt")
break
except TimeoutError:
continue
self.assertEqual(result, "ok")
self.assertEqual(flaky.call_count, 3)
if __name__ == "__main__":
unittest.main()Run it (python3 test_cart_unittest.py):
..
----------------------------------------------------------------------
Ran 2 tests in 0.000s
OKThe unittest.mock demo from 5.3 is also runnable stdlib — Mock, patch, side_effect all work without pytest. pytest doesn't replace unittest.mock; it complements it with fixtures (monkeypatch is often cleaner than patch), parametrisation, and assertion rewriting.
Part 10: Decision tables and the failure gallery#
Reference
10.1 Decision tables#
Which double should I use?
| Situation | Reach for | Why |
|---|---|---|
| Replacing the model/backend in tests | Fake (ScriptedBackend; a tiny FlakyBackend when you need a chosen exception) |
Real code, records calls, scripted replies and failures, async-native |
| Replacing a complex deterministic dependency (in-memory DB, file store) | Fake | A simplified working implementation beats a canned stub |
| You only need a fixed return value, don't care about calls | Stub (Mock(return_value=...)) |
Cheapest double there is |
| You must assert how a boundary was called (once, with these args) | Mock / Spy | Interaction is the contract |
| Patching a third-party SDK or socket you don't own | unittest.mock.patch / MockTransport / respx |
Boundary you can't rewrite |
| Controlling time, env, filesystem | monkeypatch, injected clock, tmp_path |
Fixtures, not mocks |
Which test level?
| You want to verify... | Level | Tool |
|---|---|---|
| A pure function's logic (parser, validator, cost maths) | Unit | plain assert |
| Your orchestration with a fake backend | Component | ScriptedBackend + pytest-asyncio |
Your httpx client's request/response handling |
Transport | MockTransport / respx |
| Your FastAPI routes and DI | API | TestClient + dependency_overrides |
| SSE stream framing | Stream | TestClient.stream or parser unit test |
| Retry/backoff decisions | Component | flaky ScriptedBackend + wait_none |
| The provider's actual behaviour | Live (scheduled) | markers + CI; 03.10 owns design |
pytest-asyncio vs anyio plugin?
| Your situation | Choose |
|---|---|
| asyncio-only project (the common case) | pytest-asyncio with asyncio_mode = "auto" |
| Testing both asyncio and trio, or anyio-native code | anyio plugin + anyio_backend fixture |
Legacy unittest.IsolatedAsyncioTestCase suite |
pytest runs it; migrate gradually |
10.2 Failure gallery#
Real-world testing failures you'll meet, with the tell-tale sign:
| Symptom | Cause | Fix |
|---|---|---|
async def test_... fails (older pytest: skipped) with "async def functions are not natively supported" |
No async plugin, or wrong mode | pytest-asyncio + asyncio_mode="auto" or @pytest.mark.asyncio |
| Test passes locally, fails in CI (or vice versa) | Env var, cwd, or file path difference | monkeypatch.setenv, tmp_path, never hard-code paths |
ScopeMismatch: You tried to access the function scoped fixture 'dep' with a session scoped request object |
Wide fixture depends on narrow one | Widen the dependency or narrow the dependent |
AttributeError: module 'x' does not have the attribute 'y' from patch |
Patching where it's defined, not where it's used | patch("using_module.attr") |
Mock registered but route.called is False |
respx doesn't patch httpx2 (SDK calls) |
MockTransport on httpx2.Client, or socket guard to catch it |
| Test suite takes 9 minutes | Real sleeps, network, or unbounded concurrency in tests | wait_none, MockTransport, -n auto, --durations |
1 failed, 0 passed but you changed nothing |
Shared mutable state leaked between tests | Fresh fixture per test, no module-level dicts |
assert shows only "AssertionError" with no values |
Helper outside test file, no rewriting | Move assert into test, or pytest.register_assert_rewrite |
| Coverage 95% but bugs ship | Tests assert True, or only happy paths |
Test error paths, use --cov-branch, mutation testing |
| Flaky test that passes alone, fails in suite | Order dependence, shared fixture, timing | Isolate state, events not sleeps, pytest-randomly (or --randomly-seed=<n>) to verify |
Common misconceptions#
| Misconception | Reality |
|---|---|
| "Tests prove the code is correct." | They prove the specified behaviours hold. Coverage and green tests are necessary, not sufficient — bugs live in the gap between spec and test. |
| "100% coverage means bug-free." | You can hit 100% with assert True or tests that never exercise the failure path. Coverage shows what's untested, not what's correct. |
| "Mock everything for isolation." | Prefer fakes — real, readable, deterministic code you control. Mocks of your own functions test the mock, not your code. |
| "Tests should hit the real API to be realistic." | The fast suite must be deterministic, fast and offline. Realism comes from contract tests and scheduled live smoke tests, not per-commit calls. |
| "Assert the model's exact output." | The model's answer isn't deterministic — that's an eval question, not a unit test. Assert shapes, invariants and error handling. |
"asyncio_mode = "auto" is always right." |
It's right for asyncio-only projects. If you also test trio or anyio-native code, the anyio plugin is the better fit — and the two auto modes conflict. |
| "A test that sleeps 0.1s is fine." | It's slow and flaky. Use asyncio.sleep(0) for yielding, asyncio.Event/Queue for coordination, and fakes that record calls instead of timing. |
"Fixtures are just setUp/tearDown with extra steps." |
They're scoped, composable, cached dependencies — closer to DI than to lifecycle methods. They can depend on other fixtures and be parametrised. |
| "Test order matters." | It must not. Tests that depend on each other or on module-level mutable state are flaky by construction. |
"xfail means the test is broken." |
It means "expected to fail" — for known bugs you're tracking. strict=True keeps it honest; skip is for tests that can't run. |
"unittest is dead, pytest replaced it." |
pytest runs unittest.TestCase suites unchanged, and unittest.mock is still the mocking tool. pytest adds fixtures, parametrize and assertion rewriting on top. |
| "Coverage % is a target to game." | It's a floor, not a goal. Chase uncovered error paths, not a number. |
Key takeaways#
- Tests are deterministic, fast and offline; evals are statistical, slow and model-dependent. Test everything except the model's answer — parsing, validation, retries, error mapping, concurrency, streaming, config.
- pytest discovers
test_*.py/test_*functions, rewritesassertfor readable failures, and provides fixtures, parametrisation, markers and plugins. Exit codes0–6are part of the API;5(no tests collected) is a failure to keep visible, never to swallow. - Fixtures are scoped, composable, cached dependencies with
yieldteardown — not justsetUp.tmp_path,monkeypatch,capsys,caplogcover the common needs;autouseis for things that must always happen (the socket guard). - Parametrise tables of cases; use
hypothesisfor properties over generated inputs; snapshot contracts (schemas, requests), never model answers. - Prefer fakes (
ScriptedBackend) over mocks; useunittest.mockat boundaries you don't own.patchwhere it's used, not where it's defined;autospeccatches signature drift;side_effectscripts flaky sequences. - Control the world in tests: injected clocks, seeded randomness,
monkeypatch.setenv,tmp_path— and block the network (pytest-socketor the socket-guard fixture) so "I thought it was mocked" becomes a failing test, not a surprise bill. - Async tests need
pytest-asyncio(auto mode) or the anyio plugin; never both auto modes. Test ordering with recorded calls andasyncio.sleep(0), not real sleeps; test cancellation and timeouts explicitly. - HTTP testing:
MockTransportfor yourhttpxcode,respxfor route-level mocking (but it doesn't patchhttpx2— the SDK trap),TestClient+dependency_overridesfor FastAPI,ASGITransportfor async. - Coverage guides, doesn't judge:
--cov+--cov-branch+fail_underin CI;pytest-xdistfor speed; mutation testing for test quality. - Red–green–refactor: write the failing test first, minimal code to pass, refactor with the suite as safety net. The
aitoolkit/tests/suite is the template.
Where you'll use this in the AI path#
| Skill from this lesson | Where it's used next |
|---|---|
| pytest mechanics, fixtures, fakes | 03.10 — Debugging and Testing LLM Code — the seven levels of LLM testing built on these tools |
ScriptedBackend, async tests |
03.9 — Async and Batch — testing concurrent LLM calls |
MockTransport, respx, socket guard |
03.10, 7.3–7.4 — mock transports under real SDKs, and the httpx2 trap |
| Schema snapshot tests | 08A.6 — Designing Tools — tool-definition schema snapshots |
| pytest + markers + CI | 10A.8 — Regression Testing and CI — eval suites as pytest tests |
| CI workflow, markers | 11C.2 — CI/CD for Prompts and Evals — the pipeline this lesson's CI feeds into |
| Contract tests, live smoke | 03.10, Part 12 — CI without keys, live tests on schedule |
dependency_overrides, TestClient |
07.11 — Production RAG and 11C.1 — Deployment — testing deployed services |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| pytest | The Python test runner: discovers test_* functions, rewrites asserts, provides fixtures and plugins |
| Test discovery | pytest's rules for finding tests: test_*.py files, test_* functions, Test* classes |
| Assertion rewriting | pytest's compile-time transform that makes assert failures show every sub-expression's value |
| Node ID | A test's unique address: file.py::test_func[param] — used for selection and --lf |
| Fixture | A named, scoped, cached dependency pytest injects into tests by parameter name |
| Fixture scope | How long a fixture lives: function/class/module/package/session |
| Yield fixture | A fixture using yield to split setup (before) from teardown (after) |
conftest.py |
Per-directory pytest plugin file for shared fixtures and hooks |
| Marker | A label on tests (@pytest.mark.live) for selection with -m or skipping |
| Parametrise | @pytest.mark.parametrize runs one test body once per row of a table |
pytest.raises |
Context manager asserting an exception is raised, with optional match regex |
pytest.RaisesGroup / RaisesExc |
pytest 8.4+ matchers asserting which sub-exceptions an ExceptionGroup contains |
excinfo |
The exception info object from pytest.raises, with .type/.value/.tb |
pytest.approx |
Floating-point comparison helper for assert |
| Arrange–act–assert (AAA) | The three-part test structure: set up, exercise, verify |
| Test double | Anything standing in for a real dependency: dummy, stub, fake, spy or mock |
| Fake | A working, simplified implementation used as a test double (e.g. ScriptedBackend) |
| Stub | A double returning canned answers without checking how it was called |
| Mock | A double pre-programmed with expectations that assert the calls made |
| Spy | A real object that also records how it was called |
unittest.mock |
Stdlib mocking library: Mock, MagicMock, patch, autospec, side_effect |
side_effect |
Mock attribute: iterable/callable/exception controlling per-call behaviour |
autospec |
Mock mode enforcing the real signature, catching wrong-argument calls |
monkeypatch |
pytest fixture for scoped, auto-undone patching of env vars and attributes |
tmp_path |
pytest fixture giving each test a private temporary directory |
capsys / capfd |
Fixtures capturing Python-level / file-descriptor-level stdout/stderr |
caplog |
Fixture capturing logging records for assertions |
| Property-based testing | Testing a rule over hundreds of generated inputs (hypothesis) |
| Strategy | A hypothesis generator description (st.integers(), st.text()) |
| Shrinking | hypothesis's minimisation of a failing input to the simplest counterexample |
| Snapshot / golden test | Recording output once and failing when it changes; for contracts, not answers |
| Flaky test | A test failing intermittently for reasons unrelated to the code |
| Coverage (statement/branch) | Which lines / which branch directions your tests executed |
pytest-cov |
Coverage plugin reporting per-file coverage with --cov |
pytest-xdist |
Plugin running tests across CPU cores in parallel processes |
pytest-socket |
Plugin disabling socket use in tests (--disable-socket) |
| Network guard | A fixture/plugin making any socket attempt fail loudly |
MockTransport |
httpx transport returning canned responses for tests |
respx |
Route-level mocking library for httpx (patches httpx only, not httpx2) |
TestClient |
FastAPI's synchronous in-process ASGI test client |
dependency_overrides |
FastAPI's mechanism for swapping Depends in tests |
ASGITransport |
httpx transport calling an ASGI app directly, for async tests |
pytest-asyncio |
Plugin enabling async def tests for asyncio |
asyncio_mode |
pytest-asyncio config: "strict" (default) or "auto" |
anyio_backend |
anyio plugin fixture naming which async backend runs the test |
| Contract test | A test against a real server speaking the real wire format (link 03.10) |
All terms are also collected in the glossary.
Exercises#
- Write a failing test first. Take any function from
aitoolkit/models.py(or write a smallslugify(text)helper). Write the pytest test before the implementation, runuv run pytest -v, watch it fail, then implement. Paste the failing output. - Parametrise a classifier. Write
@pytest.mark.parametrizetests for aclassify_ticket(text) -> strfunction covering at least 6 inputs: refund, billing, bug, how-to, angry, and empty string. Give each row anid=. - Fixture scopes. Create a
counterfixture withscope="module"that returns a shared{"n": 0}dict. Write two tests that each add 1 tocounter["n"]and then assert its value (1in the first test,2in the second). Explain in a comment why the second test sees2and what would change withscope="function". monkeypatchenv. Write a test that setsOPENAI_API_KEYviamonkeypatch.setenv, callsget_settings(), asserts the key, then assertsos.environno longer contains it after the test (check in a second test).unittest.mockside_effect. UsingAsyncMock(side_effect=[TimeoutError, TimeoutError, "ok"])(orMockfor a sync helper), write a test that a retry helper calls the backend exactly 3 times and returns"ok". Assertcall_countandcall_args.- Patch the right name. Suppose a hypothetical helper module
aitoolkit/banner.pydoesfrom aitoolkit.settings import get_settingsand callsget_settings()insidedef build_banner() -> str. Show whypatch("aitoolkit.settings.get_settings")does not change whatbuild_banner()sees, and whypatch("aitoolkit.banner.get_settings")does. Write both and explain. Then say why neither works for the/healthroute inservice.py. - Async test. Write
@pytest.mark.asyncio(or rely onasyncio_mode="auto") test thatbounded_gatherruns 5ScriptedBackend.completecalls and preserves input order. Assertlen(backend.calls) == 5and result order. MockTransporthandler. Write a handler that returnshttpx.Response(500)for/v1/tickets/42/failandhttpx.Response(200, json={"ok": True})for/v1/tickets/42/ok. Test thatTicketClientraises on 500 and parses on 200 (use theticket_clientfixture pattern from 9.2).respxroute. Write arespx_mocktest asserting a route was called exactly once and with the right path. Then explain why it would not work for anopenai.OpenAIclient call.- FastAPI
TestClient. Write a test that overridesget_backendwith a scriptedScriptedBackend, POSTs to/v1/completewith anX-API-Keyheader, asserts 200 andbody["text"] == "Paris"(theCompletionmodel's reply field — there is nochoiceslist). Then a second test asserting 422 on a missingprompt. - Socket guard. Add the
_no_networkautouse fixture toconftest.py, then write a test that callssocket.create_connection(("example.com", 80))and asserts the guard's error (aRuntimeErrorwhose message says the network is disabled) is raised. - Coverage. Run
uv run pytest --cov=aitoolkit --cov-branch --cov-report=term-missing. Identify one uncovered line and write a test for it. - Flaky test hunt. Given a test file containing
await asyncio.sleep(0.5)before an assertion, rewrite it usingasyncio.Eventor recorded calls so it's deterministic. - Hypothesis property. Write a
@given(st.text())test asserting thatextract_json(text)either returns a dict or raisesExtractionError— never any other exception.
Solutions
-
See the red-green-refactor example in 9.1 — the
cart_total/mini_runnerpattern is the template. The failing run looks likeFAILED test_cart.py::test_total - AssertionError: assert 9 == 10with pytest's rewritten diff showing both sides. -
The shape from 4.1:
python @pytest.mark.parametrize("text, expected", [ pytest.param("I want a refund", "billing", id="refund"), pytest.param("charged twice this month", "billing", id="double-charge"), pytest.param("the app crashes on save", "bug", id="crash"), pytest.param("how do I export data?", "how_to", id="export"), pytest.param("this is the third time!", "angry", id="angry"), pytest.param("", "empty", id="empty"), ]) def test_classify_ticket(text, expected): assert classify_ticket(text) == expectedSix rows → six collected items, one test body.
id=makes failures readable (test_classify_ticket[refund]). -
Module scope creates the fixture once per test module, before the first test that asks for it, and hands every test in the file the same object. Because the object is a mutable dict, the tests can see each other's changes:
python @pytest.fixture(scope="module") def counter(): return {"n": 0} # one dict, shared by every test in the module def test_first(counter): counter["n"] += 1 assert counter["n"] == 1 def test_second(counter): counter["n"] += 1 # sees test_first's mutation: n is already 1, so this makes 2 assert counter["n"] == 2Test order matters here (pytest runs tests in file order by default). With
scope="function"each test would get a fresh{"n": 0}, so the second test would see1, not2. That shared-state leakage between tests is exactly whyfunctionscope is the default, and why a module-scoped fixture should hold only read-only or expensive-to-build things. -
Two tests, because the undo happens after the first test ends:
python import os from aitoolkit.settings import get_settings def test_settings_reads_env(monkeypatch): monkeypatch.setenv("OPENAI_API_KEY", "sk-test-123") get_settings.cache_clear() # lru_cache would serve stale Settings s = get_settings() assert s.openai_api_key.get_secret_value() == "sk-test-123" def test_env_is_undone(): assert "OPENAI_API_KEY" not in os.environ # monkeypatch reverted it # (or: it holds the value it had before — check os.environ.get, not membership, # if your shell already exports one)Without
cache_clear(),get_settings()returns theSettingsbuilt by an earlier test — the env assertion fails for the wrong reason. The autouse_reset_settings_cachefixture inconftest.pymakes the clear automatic; calling it explicitly is still the habit to learn. -
side_effectas a list pops one item per call; when it hits"ok"(a non-exception) that value is returned. The helper under test is 01B.9'scall_with_retry, which awaits its callable — so the double must be awaitable too:AsyncMock, the async counterpart ofMock:python import pytest from tenacity import AsyncRetrying, retry_if_exception, stop_after_attempt, wait_none from unittest.mock import AsyncMock, call from aitoolkit.resilience import call_with_retry, is_transient @pytest.mark.asyncio async def test_retry_helper_recovers(): backend = AsyncMock(side_effect=[TimeoutError("t1"), TimeoutError("t2"), "ok"]) policy = AsyncRetrying( retry=retry_if_exception(is_transient), # TimeoutError -> transient stop=stop_after_attempt(3), wait=wait_none(), # instant waits: logic, not the clock reraise=True, ) result = await call_with_retry(backend, "prompt", policy=policy) assert result == "ok" assert backend.call_count == 3 assert backend.call_args == call("prompt")call_argsrecords the last call's arguments — with three identical calls it equalscall("prompt"). If the helper passed kwargs, assertbackend.call_args.kwargs["model"] == ...instead. (The realScriptedBackendcan't script exceptions —fail_firstraisesRuntimeError, whichis_transienttreats as permanent — which is why retry tests useFlakyBackend;AsyncMockis fine here because the retry helper is the unit under test, not the backend.) -
banner.pyexecutesfrom aitoolkit.settings import get_settings, which copies the reference intobanner's namespace at import time. After that,aitoolkit.banner.get_settingsandaitoolkit.settings.get_settingsare two names pointing at the same function — butbuild_banner()looks the name up in its own module globals:python from unittest.mock import patch from aitoolkit import banner # FAILS to change anything: patches the original, but banner.py never looks there again with patch("aitoolkit.settings.get_settings") as m: m.return_value = fake_settings banner.build_banner() # still uses its own binding -> real Settings # WORKS: replaces the name banner.py actually resolves with patch("aitoolkit.banner.get_settings") as m: m.return_value = fake_settings banner.build_banner() # sees fake_settingsRule: patch where the name is looked up, not where it's defined. (
fake_settingsis anySettings(...)you build for the test.)Neither patch helps the
/healthroute inservice.py. The route declaresDepends(get_settings), and FastAPI stores the function object when the route is defined, so replacing the module-level name afterwards changes nothing for that route. For FastAPI dependencies the right tool isapp.dependency_overrides[get_settings] = lambda: fake_settings— no patching, and it composes with the other overrides. -
Same pattern as 9.2's
test_gather_preserves_input_order:python @pytest.mark.asyncio async def test_bounded_gather_five_calls(): backend = ScriptedBackend( replies={"a": "A", "b": "B", "c": "C", "d": "D", "e": "E"}, latency=0) results = await bounded_gather( [backend.complete(p) for p in "abcde"], limit=5) assert [r.text for r in results] == ["A", "B", "C", "D", "E"] # input order assert len(backend.calls) == 5asyncio.gather(insidebounded_gather) returns results in submission order no matter which task finishes first — that's the contract to assert. For finish order, record it:[c["prompt"] for c in backend.calls]shows completion order. -
One handler, dispatch on path:
python def handler(request: httpx.Request) -> httpx.Response: if request.url.path.endswith("/fail"): return httpx.Response(500, json={"error": {"code": "internal", "message": "boom"}}) return httpx.Response(200, json={"ok": True}) # with the ticket_client fixture from 9.2. get_ticket() only builds # /v1/tickets/<int>, so the /fail and /ok paths go through the client's # _get() helper (the method get_ticket() itself calls): def test_500_raises_and_200_parses(ticket_client): with ticket_client(handler) as client: with pytest.raises(TicketAPIError) as excinfo: client._get("/tickets/42/fail") assert excinfo.value.status == 500 and excinfo.value.code == "internal" assert client._get("/tickets/42/ok").json() == {"ok": True}Note: 01B.5's
_raise_for_apimaps any non-2xx response toTicketAPIError, readingerror.codeanderror.messagefrom a{"error": {"code": ..., "message": ...}}body and falling back tohttp_<status>when the body has another shape. Calling a private_getfrom a test is acceptable here because the point is the transport and error mapping; in your own code prefer testing through the public method. -
python def test_route_called_once(respx_mock): route = respx_mock.get("https://tickets.example.com/v1/tickets/42").mock( return_value=httpx.Response(200, json={"id": "T-42"})) with TicketClient(token="t") as client: # real client: respx intercepts httpx itself client.get_ticket(42) assert route.called assert route.call_count == 1It fails for
openai.OpenAI(...)because that SDK talks tohttpx2, nothttpx—respxpatcheshttpx's transport machinery only, so the SDK's requests bypass the mock entirely (that's the 7.2 trap;MockTransportinjected intohttpx2.Clientis the fix). -
python API_KEY = {"X-API-Key": "demo-key-alice"} def test_complete_returns_scripted_reply(client, fake_backend): resp = client.post("/v1/complete", json={"prompt": "capital of France?"}, headers=API_KEY) assert resp.status_code == 200 body = resp.json() assert body["text"] == "Paris" # Completion model's reply field assert body["finish_reason"] == "stop" def test_complete_validates_input(client): resp = client.post("/v1/complete", json={}, headers=API_KEY) assert resp.status_code == 422 assert resp.json()["error"]["code"] == "validation_error"The first test needs
fake_backendfrom 9.2 (ScriptedBackend(replies={"France": "Paris"}, latency=0)+dependency_overrides). The 422 asserts the service's error envelope, not FastAPI's default{"detail": ...}. -
The fixture from 5.5 patches
socket.socket,getaddrinfo,gethostbyname,gethostbyaddrandgetnameinfo. The test:python import socket import pytest def test_no_real_network(): # NetworkDisabledError subclasses RuntimeError; matching on the class and # message avoids importing from conftest.py (test modules shouldn't). with pytest.raises(RuntimeError, match="network disabled"): socket.create_connection(("example.com", 80), timeout=1)create_connectioncallsgetaddrinfofirst — which is patched to raise — so the guard fires before any DNS or TCP happens. If it doesn't raise, your guard has a hole (a lookup path you didn't patch) or the test isn't in theconftest.pydirectory's scope. -
term-missingprints aMissingcolumn of line numbers per file. Pick an uncovered branch — typically an error path like_raise_for_api's 404 branch or afinallycleanup — and write the smallest test that reaches it. Re-run; the percentage should rise. Don't chase 100%: defensiveexceptbranches and__main__guards legitimately stay uncovered. -
Replace the sleep with a rendezvous the code under test controls:
python # before (flaky): await asyncio.sleep(0.5); assert worker.finished # after: the fake records completion; the test waits on an Event the fake sets done = asyncio.Event() class FakeBackend: async def complete(self, prompt): ... done.set() # signal, don't sleep return "ok" async def test_worker_finishes(): task = asyncio.create_task(worker(FakeBackend(), "hi")) await asyncio.wait_for(done.wait(), timeout=1) # bounded, deterministic await task # let the worker finish; surfaces its errorsIf the code offers no hook, assert on recorded state (
backend.calls, a results list) afterawait asyncio.gather(...)— gather's completion is the synchronisation point, no sleep needed. -
python from hypothesis import given, settings import hypothesis.strategies as st @given(st.text()) @settings(max_examples=200) def test_extract_json_never_raises_unexpected(text): try: result = extract_json(text) except ExtractionError: return # contract allows it assert isinstance(result, dict) # or whatever the success shape isAny other exception fails the test — hypothesis will shrink the input to the minimal string that triggers it and replay it first next run (the
.hypothesis/example database).
Check yourself#
- What's the difference between a test and an eval in AI code?Tests are deterministic, fast, offline checks of specified behaviour; evals are statistical, slow, model-dependent measures of answer quality. Test everything except the model's answer.
- Why does pytest rewrite
assertstatements, and what does it buy you?Assertion rewriting shows every sub-expression's value on failure, making CI failures readable at 2 a.m. without a debugger. - What are the five fixture scopes, and which should you use 95% of the time?
function(default),class,module,package,session. Usefunctionunless setup is genuinely expensive and shareable. - What's the difference between
yieldteardown and a regularreturnfixture?yieldsplits the fixture into setup (before) and teardown (after);returnhas no teardown. - When should you prefer a fake over a mock?When the dependency is complex but deterministic — a fake is real code you control, records calls, and can't drift from the interface like a mock's
return_value. - What's the
patch-target trap, and what's the rule for avoiding it?patchmust target where the name is looked up, not where it's defined. Rule: patch where it's used. - Why is
await asyncio.sleep(0.2)in a test a bad idea, and what do you use instead?It's slow and flaky — timing-dependent. Useasyncio.sleep(0)for yielding,asyncio.Event/Queuefor coordination, and fakes that record calls. - What does
asyncio_mode = "auto"do, and when would you not use it?It makespytest-asynciohandle everyasync def test_*without decorators. Don't use it if you also need anyio/trio — the two auto modes conflict. - Why does
respxfail to mockopenai/anthropicSDK calls?respxpatcheshttpxonly; the SDKs usehttpx2, a different library with its own classes. - What's the difference between
MockTransportandrespx?MockTransportis anhttpxtransport you inject into a client;respxis a higher-level router that patcheshttpxglobally. - How does
app.dependency_overrideswork in FastAPI tests?It swaps aDepends(...)callable for a test double, so routes use your fake instead of the real dependency. - What does
--disable-socketdo, and why is it the strongest test guard?pytest-socket's--disable-socketmakes any socket attempt fail immediately — catching unmocked calls regardless of HTTP library. - What's the difference between statement coverage and branch coverage?Statement coverage = which lines ran; branch coverage = which sides of every
if/for/whileran. Branch catches untested error paths. - Why is "no tests collected" (exit code 5) dangerous in CI?Exit code 5 means pytest found nothing — a suite that "passes" vacuously protects nothing. CI should fail on zero collected tests.
- What does
xfail(strict=True)do that plainxfaildoesn't?strict=Trueturns an unexpected pass into a failure, so the marker can't silently rot when the bug is fixed.
Further resources#
- pytest documentation — docs.pytest.org: getting started, fixtures, parametrize, monkeypatch, exit codes, flaky tests.
- pytest-asyncio — pytest-asyncio.readthedocs.io: modes,
loop_scope, async fixtures. - anyio testing — anyio.readthedocs.io/en/stable/testing.html: the alternative plugin and
anyio_backend. - hypothesis — hypothesis.readthedocs.io: strategies,
@given, shrinking, settings. - httpx transports — python-httpx.org/advanced/transports:
MockTransport,ASGITransport, custom transports. - respx — lundberg.github.io/respx: route mocking for
httpx. - pytest-cov — pytest-cov.readthedocs.io: coverage options.
- pytest-xdist — pytest-xdist.readthedocs.io: parallel test runs.
- pytest-socket — github.com/miketheman/pytest-socket:
--disable-socket,--allow-hosts. - time-machine — time-machine.readthedocs.io: faster
freezegunalternative for tests. - unittest.mock — docs.python.org/3/library/unittest.mock.html:
Mock,patch,autospec,side_effect. - xUnit Test Patterns (Meszaros) — the book that defined dummy/stub/fake/spy/mock.
← 01B.7 — FastAPI Basics: Building a Small API | Module 01B overview | 01B.9 — Retries, Timeouts, Backoff and Resilience →