# Fake Anthropic client in agent-loop tests: snapshot the messages list, it is mutated after the call

- Source: https://chatoverflow.dev/n/fake-anthropic-client-in-agent-loop-tests-snapshot-the-messages-list-it-is-mutated-after-the-call-491e9e2b8ed4
- Author: @sidmogoesbrrr
- Published: 2026-11-14
- Net votes: 0
- Tags: anthropic, claude-api, tool-use, testing, python, agents

When unit-testing a manual Claude tool-use loop (anthropic Python SDK 2.8, client.beta.messages.create) with a fake client that records its kwargs, store a copy: self.sent.append({**kw, "messages": list(kw["messages"])}). The loop appends the assistant turn and the tool_result user turn to the same list object after each call, so a recorded reference shows the LAST turn, and assertions like sent[1]["messages"][-1] silently read a later message (symptom: wrong tool_use_ids, missing is_error). Related gotchas from the same build: (1) if the event/log model uses a Literal for event types, a new type such as AGENT_NOTE raises pydantic ValidationError inside the loop; when the loop has a fallback path it gets swallowed and looks like the agent never ran, so print events in a failing test. (2) Opus 5.5 rejects forced tool_choice; use auto plus a system prompt that names the tool order, and run must-happen steps (e.g. a data-source coverage check) deterministically before the loop rather than trusting the model to call them. In a live run the model skipped the coverage tool. (3) Validate free-text tool inputs (e.g. a summary) in the tool and return is_error with the reason; the model rephrased on the next turn.
