Sub topic 12
Testing the Chat Logic with a Fake Model
This chapter assumes you have the run_turn, trim_history, save_history and load_history functions from the earlier chapters. It also assumes basic familiarity with pytest: test functions named test_*, plain assert statements, and the tmp_path fixture. Install it with pip install pytest.
Why test against a fake
A real model call is slow, costs money, needs a network and an API key, and returns different text each time. None of that helps when you want to check whether your program builds the right list of messages.
The chat logic has its own behavior, separate from the model:
- It appends messages in the right order.
- It keeps the system message at the front.
- It trims old turns.
- It saves and loads history.
- It recovers when a call fails.
You can test all of this with a stand-in function that has the same shape as the real one: it takes a list of messages and returns a string. That stand-in is a fake model.
This only works because of the design choice from the "Isolating the model call" chapter. run_turn receives complete as a parameter instead of importing a provider SDK. That parameter is the seam where a test substitutes the fake.
The simplest fake: a lambda
The spine's first test uses a one-line fake:
fake = lambda messages: f"saw {len(messages)} messages"Its reply encodes how many messages it received, so the assertion checks that the whole history was sent. If run_turn sent only the newest message, the second reply would say saw 1 messages and the test would fail.
A lambda is enough for counting. It cannot check what the messages contained, or what happens on the third call versus the first. For that you need a fake that remembers.
A recording, scripted fake
This class does two jobs. It returns replies from a script, and it records every list it was called with.
import copy
class FakeModel:
"""Callable stand-in for complete(messages)."""
def __init__(self, replies=None, error=None):
self.replies = list(replies or [])
self.error = error
self.calls = []
def __call__(self, messages):
# Snapshot the list. run_turn keeps appending to the same list
# object, so storing a reference would show later messages too.
self.calls.append(copy.deepcopy(messages))
if self.error is not None:
raise self.error
if not self.replies:
raise AssertionError("fake model called more times than scripted")
return self.replies.pop(0)The deepcopy is the part people forget. run_turn passes its live history list to the model function. If the fake stores that same list, then after the second turn fake.calls[0] also contains the second turn's messages. Your assertions about the first call would then pass or fail for the wrong reasons. Copy at call time.
The AssertionError for an exhausted script makes extra calls loud. A fake that returns an empty string by default would hide a bug where your code calls the model twice per turn.
Testing that earlier turns are resent
This test checks the core claim of the whole tutorial: the client resends the conversation each turn.
from chat import run_turn
def test_second_call_receives_earlier_turns():
history = [{"role": "system", "content": "s"}]
model = FakeModel(["Hello Ada", "Your name is Ada"])
run_turn(history, "I am Ada", model)
run_turn(history, "Who am I?", model)
second_call = model.calls[1]
assert [m["role"] for m in second_call] == [
"system", "user", "assistant", "user",
]
assert second_call[2]["content"] == "Hello Ada"
assert second_call[3]["content"] == "Who am I?"The test never asks whether the model would really answer "Ada". That is the model's job, and it is not repeatable enough to assert on. The test checks what your code controls: the roles, their order, and the content.
Testing trimming
trim_history is a pure function. It takes a list and returns a list, so it needs no fake model, only well-chosen input.
from chat import trim_history
def make_history():
return [
{"role": "system", "content": "s"},
{"role": "user", "content": "u1"},
{"role": "assistant", "content": "a1"},
{"role": "user", "content": "u2"},
{"role": "assistant", "content": "a2"},
{"role": "user", "content": "u3"},
]
def test_trim_keeps_system_message_first():
trimmed = trim_history(make_history(), 3)
assert trimmed[0] == {"role": "system", "content": "s"}
def test_trim_never_starts_conversation_with_assistant():
# The last 4 non-system messages are a1, u2, a2, u3.
# a1 is an assistant message, so it must be dropped as well.
trimmed = trim_history(make_history(), 4)
assert [m["content"] for m in trimmed] == ["s", "u2", "a2", "u3"]
def test_trim_does_not_modify_the_original():
history = make_history()
trim_history(history, 2)
assert len(history) == 6The second test checks an edge case. A naive "keep the last N" can cut between a user message and its reply, and some providers reject a conversation that begins with an assistant message. The while loop in trim_history handles that, and this test pins the behavior down.
The third test catches a subtle bug. If someone "optimizes" the function to use del history[...], the caller's list would silently shrink.
Testing persistence with `tmp_path`
Tests that write files should never touch your real save file. The tmp_path fixture gives each test its own empty directory, which pytest cleans up later.
from chat import load_history, save_history
def test_save_then_load_round_trips(tmp_path):
path = tmp_path / "chat.json"
history = [
{"role": "system", "content": "s"},
{"role": "user", "content": "héllo, wörld"},
]
save_history(history, path)
assert load_history(path, default=[]) == history
def test_load_missing_file_returns_default(tmp_path):
default = [{"role": "system", "content": "s"}]
assert load_history(tmp_path / "nope.json", default) == default
def test_save_leaves_no_temporary_file(tmp_path):
path = tmp_path / "chat.json"
save_history([], path)
assert sorted(p.name for p in tmp_path.iterdir()) == ["chat.json"]The non-ASCII text in the first test checks that the UTF-8 encoding is applied on both sides. A test with only ASCII passes even if you forget encoding="utf-8" on a machine whose default is UTF-8, and then fails on another one.
Testing failures
A fake can raise on demand, which is hard to arrange with a real provider. This test covers the failure path from the error-handling chapter:
import copy
import pytest
def test_failed_call_leaves_history_unchanged():
history = [{"role": "system", "content": "s"}]
before = copy.deepcopy(history)
model = FakeModel(error=RuntimeError("network down"))
with pytest.raises(RuntimeError, match="network down"):
run_turn(history, "hi", model)
assert history == before
assert len(model.calls) == 1Comparing against a deep copy is stricter than checking the length. It also catches a bug where the wrong message is removed.
An edge case: Ctrl+C during a call
Now try a fake that simulates the user pressing Ctrl+C while waiting for the reply:
def test_interrupt_during_call_leaves_history_unchanged():
history = [{"role": "system", "content": "s"}]
model = FakeModel(error=KeyboardInterrupt())
with pytest.raises(KeyboardInterrupt):
run_turn(history, "hi", model)
assert len(history) == 1With the run_turn shown in the spine, this test fails with assert 2 == 1. KeyboardInterrupt inherits from BaseException, not Exception, so except Exception does not catch it. The unanswered user message stays in the history, and the next turn would send two user messages in a row. The fix is to clean up on any exit:
def run_turn(history, user_text, complete):
history.append({"role": "user", "content": user_text})
try:
reply = complete(history)
except BaseException:
history.pop()
raise
history.append({"role": "assistant", "content": reply})
return replyThe raise re-raises the same exception, so the interrupt still reaches your loop and ends the program as before. Only the cleanup changed.
Which fake for which question
| What you want to check | Tool | Why |
|---|---|---|
| The model got the full history | `FakeModel` with `calls` | Records exactly what was sent |
| The reply is stored correctly | `FakeModel` with `replies` | Returns known text |
| Failure recovery | `FakeModel` with `error` | Raises on demand |
| Trimming rules | No fake, plain input lists | `trim_history` is a pure function |
| Saving and loading | `tmp_path`, no fake | Needs a real file, not a model |
Common errors
- Recording a reference instead of a copy. Earlier calls appear to contain later messages. Use
copy.deepcopyin the fake. - Asserting on model wording. A fake's text is whatever you scripted, so checking it proves nothing. Assert on structure: roles, order, counts, and which content was passed.
- Letting tests write to the real save file. Always pass a
tmp_pathlocation, never the default path. - A fake that never fails. If every test uses the success path, the error handling is untested. Keep at least one failing fake per function that calls the model.
- Testing through
input(). Keep the loop thin and put the logic in functions likerun_turn. You can then test the logic without patchingbuiltins.input.
A fake proves that your code builds and stores messages correctly. It cannot prove that the real provider accepts them. Keep one manual run, or a small opt-in integration test, against the real API for that.
Exercise
Your FakeModel stores self.calls.append(messages) without copying. You run two turns and then assert that model.calls[0] has 2 messages. The assertion fails with 4. Why, and how do you fix it?
Show answer
run_turn passes the same live history list on every call, and the fake stored a reference to it. After the second turn appends its messages, the stored first "call" shows the longer list. Fix it by storing a snapshot: self.calls.append(copy.deepcopy(messages)).
Exercise
Write a test that checks trim_history(history, 2) on a history containing one system message and the messages u1, a1, u2, a2 returns exactly the system message followed by u2 and a2, in that order.
Show answer
def testtrimtotwokeepslastexchange(): history = [ {"role": "system", "content": "s"}, {"role": "user", "content": "u1"}, {"role": "assistant", "content": "a1"}, {"role": "user", "content": "u2"}, {"role": "assistant", "content": "a2"}, ] trimmed = trim_history(history, 2) assert [m["content"] for m in trimmed] == ["s", "u2", "a2"]