Python for AI Engineers · Part B · Lesson 13 of 26

Python testing with pytest: fixtures, mocks and testing LLM code

pytest for Java and JavaScript developers: plain assert, running and picking tests, fixtures with setup and teardown, parametrize, tmp_path and monkeypatch, unittest.mock, and testing LLM code without a model: fake clients, httpx.MockTransport, prompt snapshots, live tests and async tests.

⏱ 45 min3 exercises that check your codeRuns in your browser

By the end you can

  • Write tests as plain functions with assert, and run them with uv run pytest -q, -k and -x
  • Share setup and teardown with fixtures (function and module scope, yield), and run one test over many inputs with parametrize
  • Isolate tests from your disk and environment with tmp_path and monkeypatch, and use unittest.mock when you must
  • Test code that calls an LLM without a model: inject a fake client, or plug httpx.MockTransport into the OpenAI SDK
  • Keep live and slow tests out of the default run, measure coverage, and test async def code
1 / 6

1Tests are plain functions with assert

In JUnit a test is a method with @Test inside a class, and you check results with assertEquals. In Jest you call test("...", () => { expect(x).toBe(y) }). In pytest a test is just a function whose name starts with test_, in a file whose name starts with test_ (or ends with _test.py). No base class, no annotation, no import needed.

You check results with Python's own assert statement: assert condition, "optional message". If the condition is false, Python raises AssertionError, and pytest reports that test as failed. Finding the tests this way, by their names, is called test discovery.

pytest is not built into the browser, so the box below does by hand what pytest does for you: it looks through every name defined in the file, calls the ones starting with test_, and reports each one. One test fails on purpose.

Try it: edit and run
def word_count(text):
    return len(text.split())


def test_counts_words():
    assert word_count("what is DNS") == 3


def test_empty_text_has_no_words():
    assert word_count("") == 0


def test_wrong_on_purpose():
    assert word_count("tokens are not words") == 3, "expected 3 words"


# A tiny version of what pytest does for you: find every test_ function and run it
for name, fn in list(globals().items()):
    if name.startswith("test_") and callable(fn):
        try:
            fn()
            print("PASS", name)
        except AssertionError as error:
            print("FAIL", name, "-", error)
Expected output
PASS test_counts_words
PASS test_empty_text_has_no_words
FAIL test_wrong_on_purpose - expected 3 words
Java (JUnit 5)
class WordCountTest {
    @Test
    void countsWords() {
        assertEquals(3, WordCount.of("what is DNS"));
    }
}
JavaScript (Jest)
test("counts words", () => {
  expect(wordCount("what is DNS")).toBe(3);
});
Python (pytest)
def test_counts_words():
    assert word_count("what is DNS") == 3

globals() returns a dict of every name defined at the top level of the file, functions included, in the order they were defined. callable(fn) is true for anything you can call. pytest does the same thing, much better: it searches whole folders, shows the values on both sides of a failed assert, and keeps going after a failure so you see every problem in one run.

Tip Name tests after the behaviour they check, as a sentence: test_empty_question_is_rejected, not test_build_2. The name is all you see when it fails in CI.

2Your first pytest file, and how to run it

Start in a project from lesson 1: uv init pytest-demo, then cd pytest-demo. Save the code we will test as prompts.py. It builds the messages for a RAG question, works out a cost, and reads a score out of a grader model's reply:

import re

SYSTEM = "Answer using only the context. If it is not there, say you don't know."


def build_messages(question: str, context: list[str]) -> list[dict]:
    if not question.strip():
        raise ValueError("question is empty")
    notes = "\n".join(f"- {line}" for line in context)
    return [
        {"role": "system", "content": SYSTEM},
        {"role": "user", "content": f"Context:\n{notes}\n\nQuestion: {question}"},
    ]


def cost_usd(tokens: int, per_million: float) -> float:
    return tokens * per_million / 1_000_000


def parse_score(reply: str) -> int:
    """Read a grader model's reply such as 'Score: 4/5' and return 4."""
    match = re.search(r"(\d+)\s*/\s*5", reply)
    if match is None:
        raise ValueError(f"no score in {reply!r}")
    score = int(match.group(1))
    if score > 5:
        raise ValueError(f"score {score} is out of range")
    return score

re.search(pattern, text) finds the first match of a regular expression in the text, or returns None. The pattern (\d+)\s*/\s*5 means "some digits, optional spaces, a slash, optional spaces, a 5", and match.group(1) is the digits inside the parentheses. Now save the tests next to it as test_prompts.py:

Run
uv add --dev pytest==9.2.0
uv run pytest -q
You should see
 + pytest==9.2.0
 (plus a few helper packages)
....                                                                     [100%]
4 passed in 0.01s
test_prompts.py
import pytest

from prompts import build_messages, cost_usd


def test_system_message_comes_first():
    messages = build_messages("What is DNS?", ["DNS maps names to IP addresses."])
    assert messages[0]["role"] == "system"


def test_context_goes_into_the_user_message():
    messages = build_messages("What is DNS?", ["DNS maps names to IP addresses."])
    assert "- DNS maps names to IP addresses." in messages[1]["content"]


def test_empty_question_is_rejected():
    with pytest.raises(ValueError, match="empty"):
        build_messages("   ", [])


def test_cost():
    assert cost_usd(2000, 0.15) == pytest.approx(0.0003)
  1. Only needed for helpers such as pytest.raises and pytest.approx. A test with a plain assert needs no import at all.line 1
  2. A normal import of the code under test. It works because pytest adds the test file's folder to the import path (Python's sys.path, like Java's classpath).line 3
  3. Discovered because the name starts with test_.line 6
  4. in checks that one string contains another. assert works with any expression that is true or false.line 13
  5. The test passes only if the block raises ValueError, and match (a regular expression) is found in the error message. Like JUnit's assertThrows or Jest's toThrow. No error, or another type, and the test fails.line 17
  6. pytest.approx compares floats with a small tolerance: 0.1 + 0.2 == 0.3 is False in every language.line 22

uv add --dev puts pytest in the project's dev dependency group in pyproject.toml: installed on your machine and in CI, but not part of the app you ship, like Maven's test scope or npm's devDependencies. uv run pytest runs pytest inside the project's virtual environment; with no file names it searches the current folder and its subfolders. -q (quiet) prints one dot per passing test.

Here is what a failure looks like. If a test said assert messages[1]["content"] == "Question: What is DNS?", pytest would show the line, both values, and a diff of the two strings, with no assertEquals needed:

>       assert messages[1]["content"] == "Question: What is DNS?"
E       AssertionError: assert 'Context:\n- ... What is DNS?' == 'Question: What is DNS?'
E         
E         + Context:
E         + - DNS maps names to IP addresses.
E         + 
E           Question: What is DNS?

test_fail.py:6: AssertionError
=========================== short test summary info ============================
FAILED test_fail.py::test_user_message - AssertionError: assert 'Context:\n- ...
1 failed, 4 passed in 0.02s

pytest can do this because it rewrites the assert statements in test files when it imports them, so it can show every value in the expression. Plain python only says AssertionError.

Watch out Coming from Maven you may want a tests/ folder. That works, but then from prompts import ... fails with ModuleNotFoundError: No module named 'prompts', because pytest adds tests/ to the import path, not the project folder. Fix it by adding pythonpath = ["."] under [tool.pytest.ini_options] in pyproject.toml (section 9 shows that table). The labs keep tests next to the code, which needs nothing.

3parametrize, and choosing which tests run

A grader model replies in many shapes: "Score: 4/5", "5 / 5, a great answer". Instead of copying a test five times, @pytest.mark.parametrize runs one test function once per row of a table, and reports each row as its own test. It is JUnit's @ParameterizedTest with @CsvSource, or Jest's test.each.

Run
uv run pytest -v -k parse_score
You should see
collected 9 items / 4 deselected / 5 selected

test_scores.py::test_parse_score[Score: 4/5-4] PASSED                    [ 20%]
test_scores.py::test_parse_score[5 / 5, a great answer-5] PASSED         [ 40%]
test_scores.py::test_parse_score[I would give it 0/5.-0] PASSED          [ 60%]
test_scores.py::test_parse_score_rejects_bad_replies[missing] PASSED     [ 80%]
test_scores.py::test_parse_score_rejects_bad_replies[too-high] PASSED    [100%]

======================= 5 passed, 4 deselected in 0.01s ========================
test_scores.py
import pytest

from prompts import parse_score


@pytest.mark.parametrize(
    ("reply", "expected"),
    [
        ("Score: 4/5", 4),
        ("5 / 5, a great answer", 5),
        ("I would give it 0/5.", 0),
    ],
)
def test_parse_score(reply, expected):
    assert parse_score(reply) == expected


@pytest.mark.parametrize("reply", ["no score here", "Score: 9/5"], ids=["missing", "too-high"])
def test_parse_score_rejects_bad_replies(reply):
    with pytest.raises(ValueError):
        parse_score(reply)
  1. A decorator (lesson 4). pytest reads it when it collects the tests.line 6
  2. The names of the arguments, in the same order as the values in each row.line 7
  3. One row = one test run: reply="Score: 4/5", expected=4.line 9
  4. pytest fills the parameters by name from the table.line 14
  5. One argument, so the rows are single values. ids gives each row a short name for the report and for -k.line 18

-v (verbose) prints one line per test, with its node ID: file::function[parameters]. Before the list, pytest prints a short header with the Python and pytest versions and the project folder. -k parse_score keeps only tests whose name contains parse_score; the 4 tests in test_prompts.py were deselected. The flags you will use every day:

  • uv run pytest -q runs everything, one dot per test.
  • -k "rejects and missing" filters by name, with and, or and not. Parameter ids count as part of the name.
  • -x stops at the first failure: handy when one broken thing makes 50 tests fail.
  • uv run pytest test_scores.py runs one file, and uv run pytest "test_scores.py::test_parse_score_rejects_bad_replies[too-high]" runs exactly one test. Quote node IDs: the shell treats [ and ] as special characters.
  • --lf (last failed) re-runs only the tests that failed last time.
  • -s shows your print output, which pytest normally captures and only shows for failed tests.

Tip Parametrize is perfect for the messy text an LLM sends back. Every time a real reply breaks your parser, add it as a new row. The table becomes a record of every shape you have seen.

4Fixtures: setup and teardown, done once or per test

A fixture is a function marked with @pytest.fixture that prepares something a test needs: a client, an index, some data. A test asks for it by naming it as a parameter. pytest sees the name, calls the fixture, and passes in its result. That is dependency injection by parameter name, a little like Spring injecting a bean into a constructor.

If the fixture uses yield instead of return, the code after yield runs after the test, even when the test failed: that is your teardown. The scope decides how often the fixture runs: "function" (the default) gives every test a fresh one, "module" builds it once per file and shares it.

Run
uv run pytest -q -s test_fixtures.py
You should see
[build the document index: once for this file]

  [new chat history]
.
  [clean up history, length 1]

  [new chat history]
.
  [clean up history, length 0]

[close the index]

2 passed in 0.01s
test_fixtures.py
import pytest


@pytest.fixture(scope="module")
def docs():
    print("\n[build the document index: once for this file]")
    index = {"dns": "DNS maps names to IP addresses.", "tcp": "TCP delivers bytes in order."}
    yield index
    print("\n[close the index]")


@pytest.fixture
def history():
    print("\n  [new chat history]")
    messages = []
    yield messages
    print(f"\n  [clean up history, length {len(messages)}]")


def test_lookup(docs, history):
    history.append({"role": "user", "content": "What is DNS?"})
    assert "IP" in docs["dns"]


def test_history_starts_empty(docs, history):
    assert history == []
  1. Module scope: built once, before the first test in this file that asks for it, and shared by all of them. Use it for slow things such as loading an embedding index.line 4
  2. The prints only show the order things happen in. \n starts a new line so they do not land on the same line as pytest's dots.line 6
  3. The test receives index. Everything after yield waits until the last test in the file is done.line 8
  4. No scope means function scope: every test gets a brand-new empty list.line 12
  5. Teardown. It runs after each test that used history, pass or fail.line 17
  6. Two parameters, two fixtures. The names must match the fixture function names exactly.line 20
  7. Passes even though the first test appended a message: function scope gave this test a fresh list.line 26
Java (JUnit 5)
@BeforeAll static void buildIndex() { ... }   // once per class
@BeforeEach void newHistory() { ... }        // before every test
@AfterEach void cleanUp() { ... }            // after every test
@AfterAll static void closeIndex() { ... }
JavaScript (Jest)
beforeAll(() => { /* build index */ });
beforeEach(() => { /* new history */ });
afterEach(() => { /* clean up */ });
afterAll(() => { /* close index */ });

The big difference from JUnit and Jest: a test gets only the fixtures it names, and a fixture can itself ask for other fixtures, so setup is explicit and composable instead of "everything in @BeforeEach runs for every test". Put fixtures that several test files need in a file called conftest.py in the same folder. pytest loads it automatically, and every test there can use its fixtures without importing them. Run uv run pytest --fixtures to list every fixture you can use, including the built-in ones in the next section.

Watch out Do not let tests depend on each other through a shared fixture: a module-scoped list that one test fills and another reads breaks as soon as you run the second test alone with -k. Share only things that tests read, such as an index; give anything a test changes function scope.

5tmp_path and monkeypatch: files and environment variables

pytest comes with built-in fixtures. Two of them solve problems every AI app has. tmp_path gives each test a fresh empty folder (a pathlib.Path from lesson 10) somewhere in your system's temp directory, so tests that write files never touch your project. monkeypatch changes environment variables, dict entries or attributes for one test only, and puts everything back afterwards.

Save this as settings.py. It reads the model name from the MODEL environment variable and saves a chat transcript as JSON Lines (one JSON object per line):

import json
import os
from pathlib import Path


def model_name() -> str:
    return os.environ.get("MODEL", "llama3.2:3b")


def save_transcript(folder: Path, messages: list[dict]) -> Path:
    path = folder / "transcript.jsonl"
    with path.open("w", encoding="utf-8") as f:
        for message in messages:
            f.write(json.dumps(message) + "\n")
    return path
Run
uv run pytest -q test_settings.py
You should see
...                                                                      [100%]
3 passed in 0.02s
test_settings.py
import json

from settings import model_name, save_transcript


def test_default_model(monkeypatch):
    monkeypatch.delenv("MODEL", raising=False)
    assert model_name() == "llama3.2:3b"


def test_model_from_env(monkeypatch):
    monkeypatch.setenv("MODEL", "qwen2.5:7b")
    assert model_name() == "qwen2.5:7b"


def test_save_transcript(tmp_path):
    messages = [{"role": "user", "content": "hi"}, {"role": "assistant", "content": "hello"}]
    path = save_transcript(tmp_path, messages)
    lines = path.read_text(encoding="utf-8").splitlines()
    assert path.name == "transcript.jsonl"
    assert [json.loads(line) for line in lines] == messages
  1. Ask for the built-in monkeypatch fixture by naming it, exactly like your own fixtures.line 6
  2. Removes MODEL for this test, in case your shell has it set. raising=False: no error if it was not set.line 7
  3. Sets MODEL only while this test runs. After the test, the old value (or no value) is back, so the next test is not affected.line 12
  4. tmp_path is a new, empty folder for this test only. pytest keeps the folders of the last 3 runs, so you can look at them after a failure.line 16
  5. Read the file back and compare the whole thing in one assert: a list of dicts compares item by item.line 21

monkeypatch can also replace an attribute for one test: monkeypatch.setattr(settings, "model_name", lambda: "fake"). That works, but section 6 explains why passing the dependency in is usually better than swapping it from outside.

Watch out Lab 1's config.py reads .env when it is imported, and stores the values in module constants. monkeypatch.setenv after that import changes nothing, because the value was already read. Read settings inside a function (like model_name() here), or build a settings object per test, when you want to test them.

6unittest.mock: fake objects that record every call

Python ships a mocking library in the standard library: unittest.mock, the counterpart of Mockito in Java or jest.fn() in JavaScript. A MagicMock accepts any attribute and any call, returns what you configure, and remembers how it was called so you can check afterwards.

return_value sets what a call returns. side_effect set to a list returns (or, for exceptions, raises) one item per call: perfect for "the first call times out, the second works". patch.object(Class, "name") swaps an attribute for a mock until the end of the with block.

Try it: edit and run
from unittest.mock import MagicMock, patch

# 1. A MagicMock accepts any attribute and any call, and records them
client = MagicMock()
client.chat.completions.create.return_value = "a fake reply"

print(client.chat.completions.create(model="llama3.2:3b", temperature=0))
create = client.chat.completions.create
create.assert_called_once_with(model="llama3.2:3b", temperature=0)
print("called", create.call_count, "time with", create.call_args.kwargs)

# 2. side_effect: raise an error, or return a different value on each call
flaky = MagicMock(side_effect=[TimeoutError("model too slow"), "second try worked"])
try:
    flaky()
except TimeoutError as e:
    print("call 1 raised:", e)
print("call 2 returned:", flaky())


# 3. patch.object swaps an attribute for a mock, only inside the with block
class Retriever:
    def search(self, query):
        raise RuntimeError("needs a real vector database")


with patch.object(Retriever, "search", return_value=["DNS maps names to IPs."]) as fake_search:
    print(Retriever().search("what is DNS?"))
    fake_search.assert_called_once_with("what is DNS?")

try:
    Retriever().search("what is DNS?")
except RuntimeError as e:
    print("after the block:", e)
Expected output
a fake reply
called 1 time with {'model': 'llama3.2:3b', 'temperature': 0}
call 1 raised: model too slow
call 2 returned: second try worked
['DNS maps names to IPs.']
after the block: needs a real vector database

client.chat.completions.create works on a fresh MagicMock because every attribute you touch is created on the spot, as another mock. assert_called_once_with(...) raises AssertionError unless the mock was called exactly once with exactly those arguments; it printed nothing here because it passed. call_args.kwargs is the dict of keyword arguments of the last call. Note that fake_search was called with only the query and no self: a plain mock put on a class does not receive the instance.

Why dependency injection beats patching. patch reaches into a module and swaps a name, so the test depends on how the code is written inside: rename an import and the patch silently stops applying, while the real API gets called. Compare a class that receives its client: Answerer(client, model). The app passes the real OpenAI() client, a test passes a fake, and there is nothing to patch. It is the same reason Spring code takes dependencies through the constructor. Keep patch for code you do not own, such as the clock or a library's global function.

Tip A MagicMock also accepts typos: client.chat.completion.create (no "s") works on a mock and fails in production. MagicMock(spec=SomeClass) only allows attributes the real class has, and create_autospec(fn) also checks the call's arguments.

Watch out patch("module.name") must name the place where the name is looked up, not where it was defined. If answer.py does from rag import search, patch "answer.search". Patching "rag.search" changes nothing for answer.py, which already holds its own reference to the original function.

7Testing LLM code: a fake client and a prompt snapshot

A real model is slow, costs money, needs a running server, and gives different words each time. So unit tests never call one. Instead, design the code so the client is passed in, then give it a small fake that has the same shape as the real client: client.chat.completions.create(...) returning an object with .choices[0].message.content.

A hand-written fake beats a MagicMock here: it is ten lines, it fails loudly on a typo, it returns replies in order, and it keeps every request, so the test can check what your code sent: the model, the temperature, and the exact prompt. SimpleNamespace(a=1) from the standard library makes a quick object with attribute a, like a JS object literal.

Try it: edit and run
from types import SimpleNamespace


def build_messages(question, context):
    notes = "\n".join(f"- {line}" for line in context)
    return [
        {"role": "system", "content": "Answer using only the context."},
        {"role": "user", "content": f"Context:\n{notes}\n\nQuestion: {question}"},
    ]


class Answerer:
    def __init__(self, client, model):
        self.client = client          # injected: the real OpenAI client, or a fake
        self.model = model

    def ask(self, question, context):
        reply = self.client.chat.completions.create(
            model=self.model, messages=build_messages(question, context), temperature=0
        )
        return reply.choices[0].message.content.strip()


class FakeCompletions:
    """Has the same create() as client.chat.completions, with canned replies."""

    def __init__(self, replies):
        self.replies = list(replies)
        self.requests = []            # every request, so a test can look at it

    def create(self, **kwargs):
        self.requests.append(kwargs)
        text = self.replies.pop(0)
        message = SimpleNamespace(content=text)
        return SimpleNamespace(choices=[SimpleNamespace(message=message)])


class FakeClient:
    def __init__(self, *replies):
        self.chat = SimpleNamespace(completions=FakeCompletions(replies))


EXPECTED_PROMPT = """Context:
- HTTPS uses port 443.

Question: Which port does HTTPS use?"""


def test_answer_is_stripped():
    answerer = Answerer(FakeClient("  443\n"), "llama3.2:3b")
    assert answerer.ask("Which port does HTTPS use?", ["HTTPS uses port 443."]) == "443"


def test_prompt_matches_the_snapshot():
    client = FakeClient("443")
    Answerer(client, "llama3.2:3b").ask("Which port does HTTPS use?", ["HTTPS uses port 443."])
    request = client.chat.completions.requests[0]
    assert request["model"] == "llama3.2:3b"
    assert request["temperature"] == 0
    assert request["messages"][1]["content"] == EXPECTED_PROMPT


test_answer_is_stripped()
test_prompt_matches_the_snapshot()
print("both tests passed")
Expected output
both tests passed

def create(self, **kwargs) accepts any keyword arguments as a dict (lesson 4), and stores that dict, so request["model"] is whatever the code passed as model=. self.replies.pop(0) removes and returns the first canned reply, so a fake built with two replies answers two calls in order, which is how you test a retry or a two-step agent. FakeClient(" 443\n") checks that your code strips the spaces and newline models often add. The last three lines call the tests by hand because pytest is not running here; in a test_answer.py file pytest finds and runs them for you.

EXPECTED_PROMPT is a snapshot: the exact text the model should receive, written down once. Prompts are code. A small edit to a template, a missing newline, the context in the wrong order, changes the model's answers without any error, and this test catches it. When you change the prompt on purpose, update the expected text in the same commit, so the diff shows reviewers exactly what the model will now see. For many prompts, the syrupy plugin stores snapshots in files for you: assert prompt == snapshot, and uv run pytest --snapshot-update rewrites them.

Tip Test the parts of an LLM app that are yours and deterministic: the prompt you build, how you parse the reply, what happens on an error or an empty reply. Whether the model gives good answers is a different question, answered by evals (a later lab), not unit tests.

8The real SDK with a fake server: httpx.MockTransport

A fake client tests your logic, but not how you use the real SDK. For that, keep the real OpenAI client and replace only its network. The SDK accepts an http_client= argument, and lesson 11's httpx.MockTransport(handler) sends every request to a Python function instead of a server. Your code, the SDK's request building, its JSON parsing and its error classes all run for real.

Save the Answerer class as answer.py, using build_messages from prompts.py:

from prompts import build_messages


class Answerer:
    def __init__(self, client, model: str):
        self.client = client          # the real OpenAI client in the app, a fake in tests
        self.model = model

    def ask(self, question: str, context: list[str]) -> str:
        reply = self.client.chat.completions.create(
            model=self.model,
            messages=build_messages(question, context),
            temperature=0,
        )
        return reply.choices[0].message.content.strip()

Then add the SDK, httpx and the async plugin, and add this line to pyproject.toml (pytest-asyncio prints a deprecation warning on every run without it; section 9 shows the whole table):

[tool.pytest.ini_options]
asyncio_default_fixture_loop_scope = "function"
Run
uv add httpx==0.29.0 openai==3.60.0
uv add --dev pytest-asyncio==1.5.0
uv run pytest -q test_llm_http.py
You should see
 + httpx==0.29.0
 + openai==3.60.0
 + pytest-asyncio==1.5.0
 (plus a few helper packages)
...                                                                      [100%]
3 passed in 0.60s
test_llm_http.py
import json

import httpx
import openai
import pytest
from openai import AsyncOpenAI, OpenAI

from answer import Answerer


def chat_reply(text):
    """The JSON body an OpenAI-compatible server sends back for a chat completion."""
    return {
        "id": "chatcmpl-test",
        "object": "chat.completion",
        "created": 0,
        "model": "llama3.2:3b",
        "choices": [{"index": 0, "message": {"role": "assistant", "content": text}, "finish_reason": "stop"}],
    }


def fake_openai(handler):
    transport = httpx.MockTransport(handler)
    return OpenAI(base_url="http://test/v1", api_key="test-key", max_retries=0,
                  http_client=httpx.Client(transport=transport))


def test_sends_the_request_we_expect():
    seen = []

    def handler(request):
        seen.append(request)
        return httpx.Response(200, json=chat_reply("  Paris.\n"))

    answerer = Answerer(fake_openai(handler), "llama3.2:3b")
    assert answerer.ask("Capital of France?", ["France is in Europe."]) == "Paris."

    request = seen[0]
    body = json.loads(request.content)
    assert request.url.path == "/v1/chat/completions"
    assert request.headers["authorization"] == "Bearer test-key"
    assert body["model"] == "llama3.2:3b"
    assert body["temperature"] == 0


def test_rate_limit_raises_an_sdk_error():
    def handler(request):
        return httpx.Response(429, json={"error": {"message": "slow down"}})

    answerer = Answerer(fake_openai(handler), "llama3.2:3b")
    with pytest.raises(openai.RateLimitError):
        answerer.ask("Capital of France?", [])


@pytest.mark.asyncio
async def test_async_client():
    def handler(request):
        return httpx.Response(200, json=chat_reply("pong"))

    client = AsyncOpenAI(base_url="http://test/v1", api_key="test-key",
                         http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)))
    reply = await client.chat.completions.create(
        model="llama3.2:3b", messages=[{"role": "user", "content": "ping"}]
    )
    assert reply.choices[0].message.content == "pong"
  1. Builds the smallest JSON body the SDK accepts as a chat completion. The SDK parses it into the same objects a real server would give you.line 11
  2. base_url can be anything: no request leaves your machine. max_retries=0 turns off the SDK's automatic retries (2 by default), so an error reaches the test at once instead of after backoff waits.line 24
  3. The SDK sends its requests through this client, and the client hands them to handler.line 25
  4. The handler receives each httpx.Request. Keeping them in a list lets the test check them afterwards.line 32
  5. request.content is the raw JSON body the SDK sent. Here we check what went over the wire: path, auth header, model, temperature.line 39
  6. Script an error response: the SDK turns status 429 into openai.RateLimitError, just as it would with a real provider. This is how you test your error handling.line 48
  7. Marks the test as a coroutine for pytest-asyncio, which runs it on an event loop. Without the mark, pytest fails the test: async def functions are not natively supported.line 55
  8. A normal def handler works for the async client too; an async def handler would also work.line 57
  9. AsyncOpenAI (lesson 9) has the same methods as OpenAI; you await them.line 62

Which to use? The fake client from section 7 for most tests of your logic: tiny and fast. MockTransport for a few tests of the edges where your code meets the SDK: error types, timeouts, the exact request body. Both need dependency injection: the client is created outside Answerer and passed in. In an app you build it once at startup (FastAPI's lifespan or Depends, lesson 12) and pass the same object around.

Tip pytest-asyncio is the most common plugin for async tests. anyio, which the OpenAI SDK already installs, has its own pytest plugin: mark the test @pytest.mark.anyio instead and you need no extra package. Pick one per project.

Watch out When you test error handling, remember that openai.APITimeoutError is a subclass of openai.APIConnectionError. In an except chain, catch the timeout first, or the connection handler swallows it.

9Live and slow tests, and coverage

You still want a few tests against a real model, to check that the whole path works: the URL, the model name, a reply that makes sense. But they must not run by default: they are slow, need Ollama running, and are not repeatable. pytest markers label tests, and -m picks tests by label. Save this as test_live.py:

import pytest
from openai import OpenAI

from answer import Answerer


@pytest.mark.live
def test_a_real_model_answers_from_the_context():
    client = OpenAI(base_url="http://localhost:11434/v1", api_key="ollama", timeout=60)
    answerer = Answerer(client, "llama3.2:3b")
    reply = answerer.ask("Which port does HTTPS use?", ["HTTPS uses port 443."])
    assert "443" in reply

The test only checks that the reply contains "443", never the exact wording: a model is allowed to phrase things differently each time. Now declare the markers and skip them by default in pyproject.toml:

Run
uv run pytest -q
uv run pytest -q -m live
uv add --dev pytest-cov==7.1.0
uv run pytest -q --cov --cov-report=term-missing
You should see
.................                                                        [100%]
17 passed, 1 deselected in 0.48s
.                                                                        [100%]
1 passed, 17 deselected in 2.41s
 + coverage==7.17.5
 + pytest-cov==7.1.0
.................                                                        [100%]
================================ tests coverage ================================
Name          Stmts   Miss  Cover   Missing
-------------------------------------------
answer.py         8      0   100%
prompts.py       17      0   100%
settings.py      11      0   100%
-------------------------------------------
TOTAL            36      0   100%
17 passed, 1 deselected in 1.43s
pyproject.toml
[tool.pytest.ini_options]
addopts = "-m 'not live and not slow'"
markers = [
    "live: calls a real model server",
    "slow: takes more than a few seconds",
]
asyncio_default_fixture_loop_scope = "function"

[tool.coverage.run]
omit = ["test_*.py"]
  1. pytest reads its settings from this table in pyproject.toml. Add it below what uv already wrote there.line 1
  2. Options added to every run. By default, skip tests marked live or slow. A -m you type yourself replaces this one.line 2
  3. Declares the markers you use. An undeclared one, such as a typo @pytest.mark.lvie, only gives a warning; add --strict-markers to addopts to make it an error.line 3
  4. For coverage (below): do not count the test files themselves.line 9

The first run skips the live test (1 deselected). -m live runs only the live tests (start Ollama and ollama pull llama3.2:3b first, as in lab 1; the time depends on your machine), and -m "" runs everything. Mark a test @pytest.mark.slow for things like an eval over 200 questions, and run those with -m slow. In CI, the fast suite runs on every push and the live one on a schedule.

Coverage measures which lines of your code ran during the tests. --cov turns it on for the current folder, and --cov-report=term-missing adds a Missing column with the line numbers no test ran. Try it: run with -k "not too-high" and prompts.py drops to 94%, with line 27 missing, the "out of range" error. Coverage shows what you never tested. 100% does not prove the tests check the right things.

Tip Read a live test's server address from the environment (the lab 1 settings) instead of hard-coding it, so CI can point the same test at a staging server.

Common mistakes

  • Calling a real model in unit tests: slow, flaky, costs money, and fails on a laptop without Ollama. Inject a fake client, or use httpx.MockTransport; mark real calls live.
  • Asserting a model's exact wording in a live test. Check what must be true (a number, a keyword, valid JSON), not the phrasing.
  • Naming a file prompts_test1.py or a test check_cost(): pytest only collects test_*.py (or *_test.py) files and test_* functions, so the test silently never runs.
  • Patching where a function is defined instead of where it is looked up (patch("rag.search") when answer.py did from rag import search).
  • Reading settings at import time, then expecting monkeypatch.setenv to change them.
  • Writing async def test_... without @pytest.mark.asyncio (or @pytest.mark.anyio): pytest fails the test instead of running it.

Practice

Write the code, then press Check. Your work is saved in this browser.

1A fake client that records requests

Finish FakeLLM. It is built with some canned replies. Each call to complete(prompt) must store the prompt in self.prompts and return the next reply, in order. When the replies run out it must raise RuntimeError (a test that makes more calls than expected should fail loudly).

Exercise
class FakeLLM:
    def __init__(self, *replies):
        self.replies = list(replies)
        self.prompts = []

    def complete(self, prompt):
        return self.replies[0]
Hint

Append the prompt first. Then `if not self.replies: raise RuntimeError("no replies left")`, and `return self.replies.pop(0)`.

2Make it testable: inject the client

summarize creates its own RealLLM, which needs a server, so it cannot be tested. Change it to summarize(text, llm): it must call llm.complete(...) with a prompt that starts with "Summarize in one sentence:" and contains the text, and return the reply with surrounding spaces removed. The tests pass a fake.

Exercise
class RealLLM:
    def complete(self, prompt):
        raise ConnectionError("no model server in tests")


def summarize(text):
    reply = RealLLM().complete(f"Summarize in one sentence:\n{text}")
    return reply.strip()
Hint

Add a parameter: `def summarize(text, llm):` and call `llm.complete(...)` instead of `RealLLM().complete(...)`. In the app you would call `summarize(text, RealLLM())`.

3Test a retry with MagicMock

Write ask_with_retry(call, prompt, attempts=3). It calls call(prompt) and returns the result. If the call raises TimeoutError, it tries again, up to attempts calls in total, then lets the last TimeoutError escape. Any other exception must escape at once, without a retry. The tests use MagicMock(side_effect=[...]) and check call_count.

Exercise
def ask_with_retry(call, prompt, attempts=3):
    return call(prompt)
Hint

`for attempt in range(1, attempts + 1):` then `try: return call(prompt)` and `except TimeoutError: if attempt == attempts: raise`. A `side_effect` set to one exception (not a list) raises it on every call.

Interview questions

Q1How does pytest find tests, and why can it use a plain assert?

It collects files named test_*.py or *_test.py, and inside them functions named test_* (and methods named test_* in classes named Test* without an __init__). When it imports a test file it rewrites the assert statements, so a failure shows the value of every part of the expression and a diff, with no assertion library needed.

Q2What is a pytest fixture, and how do scopes and yield work?

A function marked @pytest.fixture that provides something a test needs; a test gets it by naming it as a parameter. Scope (function, class, module, package, session) sets how often it is created. Code after yield in the fixture is teardown, run after the tests that used it, even if they failed. Shared fixtures go in conftest.py.

Q3How do you unit test code that calls an LLM?

Do not call the model. Inject the client, then pass a fake with the same interface that returns canned replies and records requests, so you can assert on the prompt, parameters and parsing. To exercise the real SDK, give it an http_client with httpx.MockTransport and script responses, including errors such as 429. Keep a few real calls as marked live tests that run separately.

Q4When would you use mock.patch instead of dependency injection?

For code you do not control, such as the clock, os functions or a library's module-level function. For your own dependencies, pass them in: tests become simpler, and they do not break when imports move. With patch, always patch the name where it is looked up, not where it is defined.

Q5How do you keep slow or live tests out of the normal test run?

Mark them (@pytest.mark.live), declare the markers in the config, and add -m "not live" to addopts, so the default run skips them. Run them on purpose with pytest -m live, for example in a scheduled CI job with a model server available.

Q6What does code coverage tell you, and what does it not?

Which lines (or branches) ran during the tests, and so which code no test reached. It does not tell you whether the tests check the right results: a test with no meaningful assert still gives 100%. Use it to find untested paths, such as error handling, not as a quality score.