Sub topic 12
Testing the Chat Logic with a Fake Model
This chapter assumes you have the history list of role-tagged messages from earlier chapters, and that you know basic pytest usage (functions named test_* with plain assert).
Why test without a real model
A real model call is slow, costs money, needs a network, and returns different text each time. None of that helps you check whether your own code is correct. The chat logic you wrote is ordinary list handling: append the user message, call the model, append the reply, and undo on failure. You can test that part with no model at all.
The model call is already isolated behind one function, complete(messages). That function is the seam. In production you pass the real one. In tests you pass a small fake.
Make the model a parameter
run_turn receives complete as an argument instead of importing it. That makes the dependency explicit.
def run_turn(history, user_text, complete):
history.append({"role": "user", "content": user_text})
try:
reply = complete(history)
except Exception:
history.pop()
raise
history.append({"role": "assistant", "content": reply})
return replyIf the call fails, the except block removes the user message and re-raises the error. The history stays valid, so the next attempt does not send two user messages in a row.
Write the tests
Save these in test_chat.py next to the code above, or import run_turn from your module.
def test_history_grows_by_two_per_successful_turn():
history = [{"role": "system", "content": "s"}]
fake = lambda messages: f"saw {len(messages)} messages"
assert run_turn(history, "hi", fake) == "saw 2 messages"
assert run_turn(history, "again", fake) == "saw 4 messages"
assert len(history) == 5
def test_failed_call_leaves_history_unchanged():
history = [{"role": "system", "content": "s"}]
def broken(messages):
raise RuntimeError("network down")
try:
run_turn(history, "hi", broken)
except RuntimeError:
pass
assert len(history) == 1The first test uses a fake that reports how many messages it received. That checks the behavior this whole tutorial depends on: the model gets the full history on every turn. The second test uses a fake that always raises, and confirms the history is unchanged afterward.
Run them with python -m pytest test_chat.py.
Test the other pure functions
trim_history and the JSON helpers need no fake at all, because they take data in and return data. Here is a test for the sliding window.
def test_trim_keeps_system_and_starts_with_user():
history = [
{"role": "system", "content": "s"},
{"role": "user", "content": "1"},
{"role": "assistant", "content": "a"},
{"role": "user", "content": "2"},
{"role": "assistant", "content": "b"},
]
trimmed = trim_history(history, 3)
assert trimmed[0]["role"] == "system"
assert trimmed[1]["role"] == "user"
assert [m["content"] for m in trimmed] == ["s", "2", "b"]Asking for the last three non-system messages gives a, 2, b. The window starts on an assistant message, so the function drops it, leaving 2 and b. This is the edge case that is easy to get wrong, so it is worth a test.
For persistence, pytest provides a tmp_path fixture. It gives each test a fresh temporary directory, so you can call save_history(history, tmp_path / "chat.json"), then load_history on the same path, and assert the lists are equal.
Common mistakes
- Importing the real client inside the logic. If
run_turncalls the SDK directly, you cannot test it offline. Keep the SDK call incompleteonly. - Asserting on model wording. Check structure (message count, roles, order), not the text of a real reply.
- Forgetting the failure path. The success path is easy to test. Bugs usually live in what happens after an exception.
Exercise
Write a test showing that run_turn passes the user's new message to the model as the last item in the list. What should the fake do?
Show answer
The fake returns the content of the last message it receives, for example lambda messages: messages[-1]["content"]. Call run_turn(history, "hello", fake) and assert the return value equals "hello". Because the user message is appended before complete is called, the last message the fake sees is the new user message.