Sub topic 13
Testing the Endpoint with a Fake LLM Client
This chapter assumes you can read the /chat endpoint built earlier in this tutorial. That means the get_client dependency, the token_events generator, and the sse helper. You should also know basic pytest. By the end you will have tests for the streaming endpoint that run offline, cost nothing, and give the same result every time.
Why not call the real model
A test that calls a real LLM API has four problems:
- It needs a network connection and an API key in the test environment.
- It costs money on every run.
- The output changes between runs, so you cannot assert on exact text.
- It fails when the provider has an outage, even though your code is fine.
The endpoint you wrote does not need the real model to be tested. Its job is to take a validated request, read chunks from a client object, and turn them into SSE frames. You can check all of that with a stand-in object that produces chunks you chose.
This works because the client reaches the endpoint through Depends(get_client). FastAPI keeps a dictionary called app.dependency_overrides. When a key in it matches a dependency function, FastAPI calls the replacement instead. The endpoint code does not change.
The minimal test
Here is the test from the plan, with the fake client written as nested classes.
from types import SimpleNamespace as NS
from fastapi.testclient import TestClient
from main import app, get_client
class FakeClient:
class chat:
class completions:
@staticmethod
async def create(**kwargs):
async def gen():
for text in ["Hel", "lo"]:
yield NS(choices=[NS(delta=NS(content=text))])
return gen()
def test_chat_streams_tokens():
app.dependency_overrides[get_client] = lambda: FakeClient()
try:
with TestClient(app) as client:
with client.stream("POST", "/chat", json={"prompt": "hi"}) as resp:
body = "".join(resp.iter_text())
finally:
app.dependency_overrides.clear()
assert "event: token" in body
assert '"text": "Hel"' in body
assert "event: done" in bodyThree details matter here.
- The fake must match the call shape. The endpoint runs
await client.chat.completions.create(..., stream=True)and thenasync for chunk in stream. Socreateis anasync defthat returns an async generator. If you madecreatereturn the generator directly, theawaitin the endpoint would fail. - Chunks only need the attributes the endpoint reads. The endpoint reads
chunk.choices[0].delta.content.SimpleNamespacebuilds objects with exactly those attributes and nothing else. - Always clear the overrides.
dependency_overrideslives on the globalappobject. If one test leaves an override behind, later tests silently use the fake. Thetry/finallyprevents that.
The substring checks work because json.dumps writes {"text": "Hel"} with a space after the colon. If you change the serialization, for example by passing separators=(",", ":"), these assertions break. Parsing the body, as the next section does, avoids that.
A sturdier setup
Substring checks cannot tell you whether events came in the right order, or whether an event is missing. A better approach is to parse the body into (event, data) pairs and compare the whole list. The following file builds a reusable fake and covers the success path, empty chunks, mid-stream failure, and validation.
import json
from types import SimpleNamespace as NS
import pytest
from fastapi.testclient import TestClient
from main import app, get_client
def delta(text):
return NS(choices=[NS(delta=NS(content=text))])
def make_fake(chunks, fail_after=None):
calls = []
async def create(**kwargs):
calls.append(kwargs)
async def gen():
for i, chunk in enumerate(chunks):
if fail_after is not None and i == fail_after:
raise RuntimeError("provider failed")
yield chunk
return gen()
return NS(chat=NS(completions=NS(create=create)), calls=calls)
def parse_events(body):
events = []
for block in body.strip().split("\n\n"):
lines = block.splitlines()
name = lines[0].removeprefix("event: ")
data = json.loads(lines[1].removeprefix("data: "))
events.append((name, data))
return events
@pytest.fixture
def client():
with TestClient(app) as c:
yield c
app.dependency_overrides.clear()
def use(fake):
app.dependency_overrides[get_client] = lambda: fake
def test_tokens_arrive_in_order_and_end_with_done(client):
fake = make_fake([
delta("Hel"),
NS(choices=[]),
delta(None),
delta(""),
delta("lo"),
])
use(fake)
resp = client.post("/chat", json={"prompt": "hi"})
assert resp.status_code == 200
assert resp.headers["content-type"].startswith("text/event-stream")
assert parse_events(resp.text) == [
("token", {"text": "Hel"}),
("token", {"text": "lo"}),
("done", {}),
]
def test_prompt_and_stream_flag_reach_the_client(client):
fake = make_fake([delta("ok")])
use(fake)
client.post("/chat", json={"prompt": "hi"})
assert fake.calls[0]["stream"] is True
assert fake.calls[0]["messages"] == [{"role": "user", "content": "hi"}]
def test_failure_after_first_token_becomes_error_event(client):
fake = make_fake([delta("Hel"), delta("lo")], fail_after=1)
use(fake)
resp = client.post("/chat", json={"prompt": "hi"})
assert resp.status_code == 200
assert parse_events(resp.text) == [
("token", {"text": "Hel"}),
("error", {"message": "generation failed"}),
]
def test_empty_prompt_is_rejected_before_calling_the_model(client):
fake = make_fake([delta("never sent")])
use(fake)
resp = client.post("/chat", json={"prompt": ""})
assert resp.status_code == 422
assert fake.calls == []Run it with pytest. The file assumes your application lives in main.py, as in the plan's example.
What each test proves
The first test covers the filtering logic. The endpoint skips chunks with no choices and chunks whose content is None or an empty string. Real providers send such chunks, for example a final chunk that only carries a finish reason. The fake sends them on purpose, and the expected list has no events for them.
The second test records the keyword arguments passed to create. This catches a regression where someone drops stream=True or changes how the prompt is placed in messages. Without stream=True the real client would return one complete response object, and async for would fail.
The third test covers the error contract. The status code is still 200, because the status line was already sent before the failure. The only signal is the error event. The test also confirms that no done event follows an error.
The fourth test shows that validation happens before streaming starts. A bad request gets a normal 422 response, and the fake's calls list stays empty, so no model call was made.
What these tests cannot tell you
Starlette's TestClient runs the ASGI app to completion and then gives you the body. Even when you use client.stream(...), the chunks are not delivered to your test over time. In current Starlette versions, the whole response is collected first. The consequences:
- You cannot assert that the first token arrives before the last token is produced.
- You cannot see whether a proxy buffers the output. That depends on
X-Accel-Buffering, nginx settings, and whatever sits between the app and the browser. Check it against a running deployment, for example withcurl -N. - You cannot easily test a client disconnect. The test transport does not hold a connection open that you can drop halfway.
To check real incremental delivery, start the app with uvicorn and run the httpx consumer from the previous chapter against it, with a fake client that sleeps between chunks. That is an integration test, and it belongs in a separate, slower test group.
Fake, stub, or mock
Three terms come up in testing discussions, and they are easy to mix up.
| Term | What it does | Used here |
|---|---|---|
| Stub | Returns canned values and nothing else | The `FakeClient` in the minimal test |
| Fake | A small working replacement with simple logic | `make_fake`, which can fail partway through |
| Mock | Records calls so you can assert on them | The `calls` list in `make_fake` |
Our make_fake is a fake with a small mock feature. You can also use unittest.mock.AsyncMock, but an async generator inside a mock takes more setup than the hand-written version, and the hand-written version is easier to read.
Common errors
TypeError: object async_generator can't be used in 'await' expression. Your fake'screateis a plain function or an async generator itself. It needs to be anasync defthat returns the generator, as the real client does.AttributeError: 'types.SimpleNamespace' object has no attribute 'delta'. A chunk is missing one level of nesting.choicesis a list, and each item has adelta.- The real client is called anyway. The override key must be the exact function object used in
Depends. If you importget_clientfrom a different module path than the one the endpoint uses, the keys do not match. - Tests pass alone and fail together. An override leaked from an earlier test. Add the fixture teardown.
- A body assertion fails after a small refactor. You asserted on raw text such as spacing in JSON. Parse the events instead.
Exercise
Add a test that checks the response sends Cache-Control: no-cache and X-Accel-Buffering: no. Which tool gives you the headers, and does the fake client need to produce any chunks for this test?
Show answer
Use the response object from client.post("/chat", json={"prompt": "hi"}) and assert on resp.headers["cache-control"] == "no-cache" and resp.headers["x-accel-buffering"] == "no". Header names are case-insensitive in the test client. The fake still has to be installed through use(...), because otherwise the endpoint would build the real client. It can yield zero chunks, since the headers are set before any chunk is read and the stream would just end with a done event.
Exercise
A teammate writes a fake whose create is def create(**kwargs): return gen(), with no async. The test fails inside the endpoint. Explain why, and say what the fix is.
Show answer
The endpoint runs await client.chat.completions.create(...). A plain def returns the async generator object directly, and an async generator cannot be awaited, so Python raises a TypeError. The endpoint's except Exception catches it and sends an error event, so the test shows an error event instead of tokens. The fix is to declare create with async def, so that awaiting it returns the generator, matching the real client.