Sub topic 7
Testing with a fake provider
This chapter assumes you can write Python with dataclasses and typing.Protocol, and that you have read the earlier chapters on neutral request and response types and the provider interface. You should also have a basic idea of what assert and a test runner such as pytest do.
By the end you will be able to write a fake provider, use it to test code that depends on a provider, make it simulate failures, and know what a fake can and cannot tell you.
Why tests should not call real providers
Code that calls a hosted model API is hard to test directly, for four reasons:
- Cost. Every test run spends tokens and money.
- Speed. A network call takes hundreds of milliseconds to several seconds. A suite with hundreds of calls becomes slow.
- Non-determinism. The same prompt can produce different text on each call. An assertion such as
text == "short summary"will fail at random. - Availability. Tests fail when the network is down, a key is missing, or the provider rate-limits you.
Because your application code depends only on the ChatProvider protocol, you can pass it any object that has a matching complete method. A fake provider is such an object. It returns a canned reply and records what it was asked.
This tests your code, not the model. You are checking that your code builds the right request, handles the response correctly, and reacts properly to errors. You are not checking whether a model gives good answers.
The types used in this chapter
The examples below use the neutral types and protocol from earlier chapters. Here they are again so that every snippet in this chapter runs on its own.
from dataclasses import dataclass, field
from typing import Protocol
@dataclass
class Message:
role: str # "system", "user" or "assistant"
content: str
@dataclass
class ChatRequest:
model: str
messages: list[Message]
max_tokens: int = 512
temperature: float | None = None
@dataclass
class ChatResponse:
text: str
model: str
input_tokens: int | None = None
output_tokens: int | None = None
class ChatProvider(Protocol):
def complete(self, request: ChatRequest) -> ChatResponse: ...
class ProviderError(Exception):
def __init__(self, message: str, retryable: bool):
super().__init__(message)
self.retryable = retryableA minimal fake
The simplest fake returns a fixed string and keeps a list of every request it received.
class FakeProvider:
def __init__(self, reply: str = "ok"):
self.reply = reply
self.calls: list[ChatRequest] = []
def complete(self, request: ChatRequest) -> ChatResponse:
self.calls.append(request)
return ChatResponse(text=self.reply, model=request.model)FakeProvider does not inherit from anything. It satisfies ChatProvider structurally, because it has a complete method with the right signature. A type checker such as mypy accepts it wherever a ChatProvider is expected.
The calls list is what makes the fake useful. It turns the fake into a spy: after the code under test runs, you can look at the exact request it built.
A first test
Suppose your application has a function that summarizes text.
def summarize(provider: ChatProvider, text: str) -> str:
request = ChatRequest(
model="any",
messages=[Message("user", f"Summarize: {text}")],
)
return provider.complete(request).text
fake = FakeProvider(reply="short summary")
assert summarize(fake, "long text") == "short summary"
assert fake.calls[0].messages[0].role == "user"The first assertion checks the return value. The second checks something about the input: the first message was sent with the user role. Both checks run without a network call and give the same result every time.
Notice that summarize takes the provider as a parameter. This is called dependency injection. The function does not create its own provider, so a test can hand it a fake. If summarize called get_provider() internally, you would have to change an environment variable or patch the module to test it. Passing the provider in is simpler.
What to assert on
A fake lets you check two sides of the contract.
- Outgoing request. Did the code send the right model, the right messages in the right order, and sensible limits such as
max_tokens? - Incoming response handling. Given a response, does the code do the right thing with
text, and cope withinput_tokensbeingNone?
Here is a test of the outgoing side that checks a system message comes first and the user input is included.
def answer(provider: ChatProvider, question: str) -> str:
request = ChatRequest(
model="any",
messages=[
Message("system", "Answer in one sentence."),
Message("user", question),
],
max_tokens=100,
)
return provider.complete(request).text
fake = FakeProvider(reply="Paris.")
result = answer(fake, "Capital of France?")
sent = fake.calls[0]
assert result == "Paris."
assert [m.role for m in sent.messages] == ["system", "user"]
assert sent.messages[1].content == "Capital of France?"
assert sent.max_tokens == 100Assert on the parts of the request that your code is responsible for. Avoid asserting on the full text of a long prompt. Such a test breaks every time someone edits the wording, even when behavior has not changed. Check for the key facts instead, for example that the user's input appears in the last message.
Scripting replies and failures
One fixed reply is enough for simple cases. Real code often makes several calls, and you need to test what happens when a call fails. A scripted fake takes a list of outcomes and plays them back in order. Each outcome is either a ChatResponse to return or an exception to raise.
class ScriptedProvider:
def __init__(self, outcomes: list[ChatResponse | Exception]):
self.outcomes = list(outcomes)
self.calls: list[ChatRequest] = []
def complete(self, request: ChatRequest) -> ChatResponse:
self.calls.append(request)
if not self.outcomes:
raise AssertionError("ScriptedProvider ran out of outcomes")
outcome = self.outcomes.pop(0)
if isinstance(outcome, Exception):
raise outcome
return outcomeThe AssertionError when the script runs out is deliberate. If your code makes more calls than the test expected, you want the test to fail loudly instead of silently reusing the last reply.
Testing fallback with scripted failures
The fallback function from the retry chapter moves to the next provider only when the error is retryable. Scripted providers let you test both branches.
def complete_with_fallback(
providers: list[ChatProvider], request: ChatRequest
) -> ChatResponse:
last_error: ProviderError | None = None
for provider in providers:
try:
return provider.complete(request)
except ProviderError as err:
if not err.retryable:
raise
last_error = err
raise last_error or ValueError("no providers configured")
request = ChatRequest(model="any", messages=[Message("user", "hi")])
good = ChatResponse(text="from backup", model="backup")
# A retryable failure on the first provider falls through to the second.
primary = ScriptedProvider([ProviderError("overloaded", retryable=True)])
backup = ScriptedProvider([good])
result = complete_with_fallback([primary, backup], request)
assert result.text == "from backup"
assert len(primary.calls) == 1 and len(backup.calls) == 1
# A non-retryable failure is raised and the backup is never called.
primary = ScriptedProvider([ProviderError("bad request", retryable=False)])
backup = ScriptedProvider([good])
try:
complete_with_fallback([primary, backup], request)
raise AssertionError("expected ProviderError")
except ProviderError as err:
assert err.retryable is False
assert backup.calls == []The final line is the important one. It proves the backup provider was not contacted after an invalid request. A test that only checked the exception type would miss a bug where the code called the backup anyway.
You can test the all-providers-fail case the same way: script a retryable error on every provider and assert that the last error is raised.
Using the fake through configuration
The registry from the configuration chapter includes a "fake" entry. That lets you run the whole application with no network by setting one environment variable.
import os
REGISTRY = {
"fake": lambda: FakeProvider(),
# "openai": lambda: OpenAIAdapter(),
# "anthropic": lambda: AnthropicAdapter(),
}
def get_provider() -> ChatProvider:
name = os.environ.get("LLM_PROVIDER", "fake")
try:
return REGISTRY[name]()
except KeyError:
raise ValueError(f"Unknown provider: {name}")
os.environ["LLM_PROVIDER"] = "fake"
provider = get_provider()
assert isinstance(provider, FakeProvider)This is useful for local development and for smoke tests in continuous integration, where you want to check that the program starts and wires its parts together. For unit tests, prefer constructing the fake directly and passing it in. That keeps each test independent of global state such as environment variables.
Keeping the fake honest
A fake is a second implementation of your interface. It can drift away from what real adapters do, and then your tests pass while production breaks. Four habits reduce that risk.
- Return the same shapes. If real adapters sometimes return
Nonefor token counts, make the fake do so in at least some tests. Code that does arithmetic oninput_tokenswill then fail in a test instead of in production. - Raise the same errors. The fake should raise
ProviderError, never a vendor exception, because that is what the normalized interface promises. - Test adapters separately. The adapter that translates neutral types into one vendor's API needs its own tests. Feed it recorded vendor responses (saved JSON from a real call) and check the neutral output. Fakes test everything above the adapter, and recorded payloads test the adapter itself.
- Run a few live tests. Keep a small set of tests that call real providers, mark them so they are skipped by default, and run them on a schedule or before a release. They catch changes in vendor behavior that no fake can predict.
Using the fake with pytest
With pytest, a fixture gives each test a fresh fake, so recorded calls never leak between tests.
import pytest
@pytest.fixture
def fake() -> FakeProvider:
return FakeProvider(reply="short summary")
def test_summarize_returns_reply(fake):
assert summarize(fake, "long text") == "short summary"
def test_summarize_sends_user_message(fake):
summarize(fake, "long text")
assert len(fake.calls) == 1
assert fake.calls[0].messages[0].role == "user"
assert "long text" in fake.calls[0].messages[0].contentThe last assertion checks that the input text appears in the prompt without pinning down the exact wording around it.
Limits of a fake
A fake gives you fast, repeatable tests of your own logic. It cannot tell you:
- whether a real model follows your prompt or returns output in the format you expect,
- whether a given model supports the parameters you send, such as a temperature range or a maximum token count,
- how long real calls take or how rate limits behave under load,
- whether an adapter translates a vendor's fields correctly.
The first three need live tests or monitoring. The fourth needs adapter tests with recorded payloads. Treat the fake as one layer of a test suite and not as the whole of it.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Asserting on full prompt text | Tests break on harmless wording edits | Assert on key facts such as role order and presence of user input |
| Sharing one fake across tests | Recorded `calls` from one test appear in another | Create a fresh fake per test, for example with a fixture |
| Scripted fake reuses the last reply when exhausted | Extra calls go unnoticed | Raise an error when the script runs out |
| Fake raises vendor exceptions | Tests pass but real error handling is untested | Raise `ProviderError` with a realistic `retryable` value |
| Creating the provider inside the function under test | Test must patch globals | Pass the provider in as an argument |
Exercise
You write a function classify(provider, text) that sends text to the provider and returns the reply in lower case. Using ScriptedProvider, describe one test that checks it lowercases the reply and one test that checks it does not swallow a non-retryable ProviderError. What does each test assert?
Show answer
Test 1: script one outcome, ChatResponse(text="POSITIVE", model="any"). Call classify(provider, "great") and assert the result equals "positive". You can also assert provider.calls[0].messages[-1].content contains "great". Test 2: script one outcome, ProviderError("bad request", retryable=False). Call classify inside a try block (or pytest.raises(ProviderError)) and assert that the exception propagates and that its retryable attribute is False. Also assert len(provider.calls) == 1, which shows the function did not retry an error that cannot succeed.
Exercise
Your team's fake provider always returns a ChatResponse with input_tokens=10 and output_tokens=20. A cost-tracking function multiplies input_tokens by a price and passes every test. In production it crashes with a TypeError for one provider. What is the likely cause, and how do you fix the test setup?
Show answer
One real adapter returns None for token counts, which the neutral type allows. The fake never produced None, so the cost function was never tested with it. Fix the function to handle None (skip the cost or treat it as unknown). Then add a test using a scripted or fake response with input_tokens=None and output_tokens=None, and assert the function returns a sensible result without raising.
Exercise
Why is it better for a unit test to build FakeProvider() and pass it in than to set LLM_PROVIDER=fake and call get_provider()?
Show answer
Passing the fake in keeps the test independent of global state. Environment variables are shared across tests in a process, so one test that changes them can affect another. Constructing the fake directly also gives each test its own calls list and lets the test choose the reply or script. Using LLM_PROVIDER=fake is still useful for smoke tests that check the application wires up and starts correctly.