Sub topic 7
Testing with a Fake Provider
This chapter assumes you have the neutral types (Message, ChatRequest, ChatResponse) and the ChatProvider Protocol from the earlier chapters. You should also be comfortable with assert statements or a test runner such as pytest.
Why a fake beats mocking an SDK
Tests that call a real provider are slow, cost money, and return different text on each run. You can patch the vendor SDK instead, but then every test depends on that SDK's internal shape, and an SDK upgrade breaks tests that have nothing to do with the upgrade.
Your application already depends on one small interface. A fake is a class that satisfies that interface in memory. Calling code can't tell it from a real adapter, so you test your own logic and leave the vendor out of it.
A fake that records and replies
A useful fake does two things. It returns a reply you choose, and it stores every request it receives so a test can inspect them.
from dataclasses import dataclass
from typing import Protocol
@dataclass
class Message:
role: str
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 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)
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"
assert "long text" in fake.calls[0].messages[0].content
print("summarize works against the fake")The first assert checks the return value. The other two check what the code sent, which is where most real bugs hide: a wrong role, a missing system message, or a dropped max_tokens.
summarize takes the provider as a parameter. This is dependency injection, and it is what makes the fake possible. If summarize called get_provider() internally, you would have to set LLM_PROVIDER in every test.
Scripting failures
Success paths are the easy part. The behavior you most need to test is what happens when a provider fails. A scripted fake returns or raises a sequence of outcomes, one per call.
class ProviderError(Exception):
def __init__(self, message: str, retryable: bool):
super().__init__(message)
self.retryable = retryable
class ScriptedProvider:
def __init__(self, outcomes: list):
self.outcomes = list(outcomes)
self.calls: list[ChatRequest] = []
def complete(self, request: ChatRequest) -> ChatResponse:
self.calls.append(request)
outcome = self.outcomes.pop(0)
if isinstance(outcome, Exception):
raise outcome
return ChatResponse(text=outcome, model=request.model)
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("any", [Message("user", "hi")])
# A retryable failure moves on to the second provider.
down = ScriptedProvider([ProviderError("overloaded", retryable=True)])
backup = ScriptedProvider(["from backup"])
assert complete_with_fallback([down, backup], request).text == "from backup"
# A non-retryable failure is raised, and the backup is never called.
bad = ScriptedProvider([ProviderError("invalid request", retryable=False)])
untouched = ScriptedProvider(["never used"])
try:
complete_with_fallback([bad, untouched], request)
raise AssertionError("expected ProviderError")
except ProviderError as err:
assert not err.retryable
assert untouched.calls == []
print("fallback rules hold")Each test states one rule from the fallback design. The final assert, untouched.calls == [], checks that the second provider was never called. Without a recorded call list you could not verify that.
Keeping the fake honest
A fake can drift from reality. Two habits help:
- Make the fake return the same neutral types as real adapters. If an adapter fills
input_tokensand the fake leaves itNone, code that does arithmetic on it passes tests and fails in production. - Raise
ProviderErrorwith realisticretryablevalues, matching your error normalization rules.
Common mistakes
- Returning one fixed reply for every call, so tests can't tell a retry from a first attempt. Use
ScriptedProviderwhen order matters. - Asserting only on the response and never on
calls. - Letting tests read
LLM_PROVIDERfrom the environment, which makes results depend on the machine.
Exercise
You add a ScriptedProvider to a test of complete_with_fallback. The test passes, but a teammate points out that it would also pass if the code tried the backup provider after a non-retryable error. What assertion is missing, and why does it catch the bug?
Show answer
Assert that the backup provider's calls list is empty (assert untouched.calls == []). A raised error alone doesn't show the backup was skipped. Code that called the backup and then re-raised the first error would still pass. Checking the recorded calls verifies that no request reached the backup.