Sub topic 13
Testing the Endpoint with a Fake LLM Client
This chapter assumes you have the streaming /chat endpoint from the earlier chapters. It also assumes you know basic pytest, and that get_client is provided through Depends. You will test the endpoint without calling a real model.
Why use a fake client
A test that calls a real LLM is slow, costs money, and returns different text each run. It also needs a network and an API key. What you want to check is your own code: the SSE framing, the event order, and the error path. A fake client gives you fixed output and runs in milliseconds.
This works because the endpoint receives its client through Depends(get_client). FastAPI lets you replace that dependency during a test with app.dependency_overrides.
Building the fake
The endpoint calls client.chat.completions.create(...) with await. It then iterates the result with async for. Each chunk has choices[0].delta.content. The fake only needs to copy that shape.
SimpleNamespace creates objects with attributes, so you do not need the real OpenAI types. The nested classes mirror the attribute path chat.completions.create.
The test
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 bodyStep by step:
createis anasync defthat returns an async generator. That matches the real client, whereawait client.chat.completions.create(..., stream=True)returns a stream you iterate.app.dependency_overrides[get_client]maps the original dependency function to a replacement. The key must be the same function object the route uses.client.stream(...)reads the body as it arrives, as a real client would.iter_text()yields the text pieces, andjoinbuilds the full body.- The
finallyblock clears the overrides. Without it, the fake leaks into other tests.
Common errors
| Symptom | Likely cause |
|---|---|
| The real client is called anyway | The override key is not the same function the route uses, for example a re-imported or renamed `get_client`. |
| `TypeError: object async_generator can't be used in 'await' expression` | `create` returns a generator but is not declared `async def`. |
| `AttributeError` on `choices` | The fake chunk does not match the real shape. |
| Overrides affect later tests | The `finally` block, or a fixture that clears overrides, is missing. |
Testing the error path
The endpoint catches exceptions and emits an error event. You can test that by making the fake raise partway through. Add this class to the same test module and reuse its imports.
class FailingClient:
class chat:
class completions:
@staticmethod
async def create(**kwargs):
async def gen():
yield NS(choices=[NS(delta=NS(content="Hel"))])
raise RuntimeError("boom")
return gen()
def test_chat_reports_midstream_error():
app.dependency_overrides[get_client] = lambda: FailingClient()
try:
with TestClient(app) as client:
with client.stream("POST", "/chat", json={"prompt": "hi"}) as resp:
status = resp.status_code
body = "".join(resp.iter_text())
finally:
app.dependency_overrides.clear()
assert status == 200
assert "event: token" in body
assert "event: error" in body
assert "event: done" not in bodyThe status is still 200. The response had already started when the failure happened, so the error travels inside the stream.
Exercise
Why does the test clear app.dependency_overrides in a finally block, and what would go wrong without it?
Show answer
dependency_overrides is a dictionary stored on the shared app object. If the test fails or ends without clearing it, the fake client stays in place and later tests that expect the real dependency, or a different fake, would silently use this one. A finally block clears it even when an assertion fails.
Exercise
Write a test that sends an empty prompt and checks the status code. Do you need a fake client for it?
Show answer
Send {"prompt": ""} and assert resp.status_code == 422. Pydantic rejects it because of min_length=1, before the generator runs. The client is never used, so no fake is needed. Example: TestClient(app).post("/chat", json={"prompt": ""}).status_code == 422.