Pytest for Claude Apps: Mocking Claude API Responses

📚 Exam guide v1.1 (exams from 7 Dec 2026)🔄 Checked against official sources: 24 Nov 2026⏱️ 9 min read🎯 D4 Evaluation Design · D2 Integration Resilience

👋 In plain words: Your own code around Claude (parsing, retries, tool loops, error handling) should be tested like any other code: fast, offline and repeatable. That means replacing the real API with a fake that returns exactly what each test needs. This lesson shows how, step by step, with pytest and the SDK’s own types.

Advertisement

Evals (Lesson 45) measure the model; unit tests check your code. Mixing them up gives slow, flaky, expensive test suites. In this lesson you will design code that accepts an injected client, build real Message objects for mocked responses, test parsing, a full tool loop with scripted replies, retry and error handling with simulated 429 and 529 errors, and keep live API tests in a separate, opt-in marker.

📖 What You’ll Learn: You will be able to structure Claude code for testability, mock Messages API responses with real SDK types, test tool loops and error paths, and separate fast unit tests from live evaluation tests.

🔑 Key terms

  • Mock: a stand-in object that returns scripted results and records how it was called.
  • Dependency injection: passing the client into your code instead of creating it inside, so tests can pass a fake.
  • side_effect: in unittest.mock, a list of results (or exceptions) returned on successive calls.
  • Live test: a test that calls the real API; slow and costly, run deliberately.

🪜 Step 1: Make the code testable

Accept the client as a parameter. Production passes a real anthropic.Anthropic(); tests pass a mock:

📄 triage.py

import json

import anthropic

SYSTEM = 'Classify bug severity. Reply only with JSON: {"severity": "critical|major|minor"}'


class TriageError(Exception):
    pass


def triage(client, report: str) -> str:
    try:
        r = client.messages.create(model="claude-opus-5-5", max_tokens=50, system=SYSTEM,
                                   messages=[{"role": "user", "content": report}])
    except anthropic.RateLimitError as e:
        raise TriageError("rate limited, retry later") from e
    if r.stop_reason == "refusal":
        raise TriageError("model declined")
    text = next((b.text for b in r.content if b.type == "text"), "")
    try:
        severity = json.loads(text)["severity"]
    except (json.JSONDecodeError, KeyError) as e:
        raise TriageError(f"unparseable reply: {text[:40]!r}") from e
    if severity not in {"critical", "major", "minor"}:
        raise TriageError(f"unknown severity: {severity}")
    return severity

🪜 Step 2: Build realistic fake responses

Use the SDK’s own Message type so your code sees exactly the objects it gets in production, including .type on content blocks:

📄 fakes.py

import anthropic
import httpx2
from anthropic.types import Message


def message(*blocks: dict, stop_reason: str = "end_turn") -> Message:
    return Message.model_validate({
        "id": "msg_test", "type": "message", "role": "assistant", "model": "claude-opus-5-5",
        "content": list(blocks), "stop_reason": stop_reason, "stop_sequence": None,
        "usage": {"input_tokens": 10, "output_tokens": 5},
    })


def text(t: str) -> dict:
    return {"type": "text", "text": t}


def tool_use(name: str, inp: dict, id_: str = "toolu_1") -> dict:
    return {"type": "tool_use", "id": id_, "name": name, "input": inp}


def api_error(cls, status: int):
    request = httpx2.Request("POST", "https://api.anthropic.com/v1/messages")
    response = httpx2.Response(status, request=request)
    return cls(f"HTTP {status}", response=response, body={"type": "error", "error": {"type": "test", "message": "x"}})

The Python SDK 2.x is built on httpx2, which is why the fake error uses httpx2 objects.

Advertisement

🪜 Step 3: Test parsing and validation

📄 test_triage.py

from unittest.mock import MagicMock

import anthropic
import pytest

from fakes import api_error, message, text
from triage import TriageError, triage


def client_returning(*responses):
    client = MagicMock()
    client.messages.create.side_effect = list(responses)
    return client


def test_valid_json_is_parsed():
    client = client_returning(message(text('{"severity": "critical"}')))
    assert triage(client, "Card charged twice") == "critical"


def test_request_uses_pinned_model_and_system_prompt():
    client = client_returning(message(text('{"severity": "minor"}')))
    triage(client, "Typo")
    kwargs = client.messages.create.call_args.kwargs
    assert kwargs["model"] == "claude-opus-5-5" and "JSON" in kwargs["system"]


@pytest.mark.parametrize("reply", ["Severity: major", '{"level": "major"}', '{"severity": "urgent"}'])
def test_bad_replies_raise_clear_errors(reply):
    with pytest.raises(TriageError):
        triage(client_returning(message(text(reply))), "x")


def test_refusal_is_reported():
    with pytest.raises(TriageError, match="declined"):
        triage(client_returning(message(stop_reason="refusal")), "x")


def test_rate_limit_becomes_triage_error():
    client = client_returning(api_error(anthropic.RateLimitError, 429))
    with pytest.raises(TriageError, match="rate limited"):
        triage(client, "x")

⌨️ Terminal

pytest -q -p no:cacheprovider test_triage.py

🖥️ Output

.......                                                                  [100%]
7 passed in 0.42s

These tests cover the success path, the request contract (pinned model and system prompt), malformed replies, refusals and rate limits, without any network call.

Advertisement

🪜 Step 4: Test a tool loop with scripted turns

Script the model’s turns with side_effect: first a tool request, then the final answer. Then assert on what your loop did:

📄 loop.py

import json


def run(client, tools_impl: dict, question: str, max_steps: int = 5) -> str:
    messages = [{"role": "user", "content": question}]
    for _ in range(max_steps):
        r = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=[], messages=messages)
        messages.append({"role": "assistant", "content": r.content})
        if r.stop_reason != "tool_use":
            return "".join(b.text for b in r.content if b.type == "text")
        results = []
        for b in r.content:
            if b.type == "tool_use":
                try:
                    out, err = json.dumps(tools_impl[b.name](**b.input)), False
                except Exception as e:
                    out, err = str(e), True
                results.append({"type": "tool_result", "tool_use_id": b.id, "content": out, "is_error": err})
        messages.append({"role": "user", "content": results})
    return "stopped: too many steps"

📄 test_loop.py

from unittest.mock import MagicMock

from fakes import message, text, tool_use
from loop import run


def test_tool_result_is_sent_back_and_answer_returned():
    client = MagicMock()
    client.messages.create.side_effect = [
        message(tool_use("get_build", {"id": "812"}), stop_reason="tool_use"),
        message(text("Build 812 failed in checkout.")),
    ]
    calls = []
    answer = run(client, {"get_build": lambda id: calls.append(id) or {"status": "failed"}}, "Status of 812?")
    assert answer == "Build 812 failed in checkout."
    assert calls == ["812"]
    sent = client.messages.create.call_args_list[1].kwargs["messages"][2]  # user turn with the results
    assert sent["content"][0]["type"] == "tool_result"
    assert sent["content"][0]["tool_use_id"] == "toolu_1"


def test_tool_exception_becomes_is_error_result():
    client = MagicMock()
    client.messages.create.side_effect = [
        message(tool_use("get_build", {"id": "999"}), stop_reason="tool_use"),
        message(text("I could not find build 999.")),
    ]

    def missing(id):
        raise KeyError(id)

    assert "could not" in run(client, {"get_build": missing}, "Status of 999?")
    sent = client.messages.create.call_args_list[1].kwargs["messages"][2]["content"][0]
    assert sent["is_error"] is True


def test_loop_stops_after_max_steps():
    client = MagicMock()
    client.messages.create.return_value = message(tool_use("get_build", {"id": "1"}), stop_reason="tool_use")
    assert run(client, {"get_build": lambda id: {}}, "loop", max_steps=3) == "stopped: too many steps"
    assert client.messages.create.call_count == 3

⌨️ Terminal

pytest -q -p no:cacheprovider test_loop.py

🖥️ Output

...                                                                      [100%]
3 passed in 0.42s
⚠️ Watch out: MagicMock stores a reference to the messages list your code passed, not a copy. The loop keeps appending to that list after the call, so messages[-1] in the recorded call is the final assistant turn, not what was sent at that moment. Look up turns by position (as above), or record a deep copy in a side_effect function. Our first version of this test made exactly that mistake.
🎯 Exam focus: Expect questions about isolating problems: if a test with a mocked client fails, the defect is in your integration code (parsing, loop, error handling), not in the model. If unit tests pass but evals fail, look at prompts, tools or model behaviour. Mocks test your code; evals test the model’s behaviour.

🪜 Step 5: Keep live tests separate

Live tests call the real API: useful before releases, but slow and billed. Mark them and skip them unless explicitly requested:

📄 test_live.py

import os

import anthropic
import pytest

from triage import triage

pytestmark = pytest.mark.skipif(not os.environ.get("RUN_LIVE_TESTS"), reason="set RUN_LIVE_TESTS=1 to call the real API")


def test_live_triage_returns_known_label():
    assert triage(anthropic.Anthropic(), "Card charged twice when Pay is double-clicked") in {"critical", "major", "minor"}

⌨️ Terminal

pytest -q -p no:cacheprovider -rs test_live.py

🖥️ Output

s                                                                        [100%]
=========================== short test summary info ===========================
SKIPPED [1] test_live.py:11: set RUN_LIVE_TESTS=1 to call the real API
1 skipped in 0.42s

Run unit tests on every commit; run live tests and evals on a schedule or before releases.

Advertisement

🪜 Step 6: Know the other faking options

Option Good for
MagicMock with SDK Message objects (this lesson) Fast unit tests of your logic
A local fake HTTP server, with base_url pointing at it Testing the real SDK path (retries, streaming parsing) end to end
Recorded real responses replayed in tests Regression tests that keep real model wording
Live tests with thresholds Pre-release checks of the real model

This course’s own sample runs use the second option: a local server that speaks the Messages API, so the SDK’s retry and streaming code runs for real.

🌍 Real-world example: Ravi’s 2-minute test suite

Ravi’s suite used to call Claude in every test: 14 minutes per run, flaky, and about $3 per pipeline. He split it: 120 mocked unit tests (parsing, tool loop, retries, refusals) that run in 2 seconds on every commit, and a 60-case live eval that runs nightly. Bugs in his own code are now caught in seconds, and the model’s behaviour is still checked every day.

🧪 Practice Questions

Question 1. A unit test for a triage function calls the real Claude API and fails about once a week because the wording changes. What is the better design?

  • A. Retry the test three times
  • B. Mock the client in unit tests and test model behaviour separately in an eval suite
  • C. Use temperature 0
  • D. Delete the test
Show answer

Answer: B. Unit tests should be deterministic and test your code. Model variability belongs in evals with thresholds.

Question 2. How do you make a mocked client return a tool request first and a final answer second?

  • A. Set return_value twice
  • B. Use side_effect with a list of two Message objects
  • C. Patch the network
  • D. Use two different clients
Show answer

Answer: B. side_effect returns the next item on each call, which scripts multi-turn behaviour.

Question 3. Which two things can you verify with a mocked client? (Choose 2.)

  • A. That your code sends the pinned model ID and the expected system prompt
  • B. That Claude’s answer quality is high
  • C. That a tool exception is returned to the model as an is_error tool_result
  • D. That the API’s rate limits are generous
Show answer

Answer: A and C. Mocks verify your requests and control flow; quality and rate limits are properties of the real service.

Question 4. Live API tests should be…

  • A. Run on every keystroke
  • B. Marked and run deliberately (scheduled or before release), skipped otherwise
  • C. Mixed with unit tests without markers
  • D. Never run
Show answer

Answer: B. Live tests are slow and billed; they belong in a separate, opt-in suite.

📝 Assignment

  1. Task 1: Refactor one of your Claude functions to accept the client as a parameter.
    ✅ Done when: it can be called with a MagicMock.
  2. Task 2: Write tests for the success path, a malformed reply, a refusal and a rate-limit error using fakes.py.
    ✅ Done when: all pass offline in under a second.
  3. Stretch: Point the real SDK at a local fake server (base_url) that returns 529 twice, then 200, and assert that your code succeeds and that three HTTP requests were made.
    ✅ Done when: the test proves the SDK’s retries ran.
Advertisement

❓ Frequently Asked Questions

🤔 How do I mock the Anthropic client in pytest?

Inject the client into your code, pass a MagicMock, and set client.messages.create.return_value or side_effect to SDK Message objects built with Message.model_validate(...).

🤔 How do I simulate a rate limit error?

Create anthropic.RateLimitError with an httpx2.Response(429, …) and use it as the mock’s side_effect.

🤔 Should I mock Claude in all tests?

Mock it in unit tests of your code. Keep a separate live eval suite for model behaviour, run on a schedule or before releases.

🤔 How do I test streaming code?

Feed your handler a list of fake events in order, or run it against a local fake server that sends server-sent events, as in Lesson 9.

🏁 Summary

  • Inject the client so tests can pass a fake.
  • Build mocked responses with the SDK’s Message type for realistic objects.
  • Test parsing, request contracts, tool loops, refusals and API errors offline.
  • Use side_effect to script multi-turn tool loops.
  • Keep live tests opt-in; unit tests check your code, evals check the model.
📝 Test yourself: D4 Eval, Testing, and Debugging practice test (20 random questions, 20 minutes), or browse all CCDV-F mock tests (3 full 70-question exams and 8 domain practice tests, with explanations).

Next, continue with Claude Failure Modes: Hallucination, Refusal, Format Drift, Context Loss.

🎬 Prefer video? Watch QA, automation and AI testing tutorials on the SQA Tools YouTube channel.

Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.