Mocking, recording and replaying provider responses

Study time
≈ 3 h (estimate)
Needs
L1-M03-L04
Updated
2026-11-06

Progress is saved in this browser only. No account, nothing is sent to a server.

Draft · reviewed by AI, not yet by a person. Content may change. English translation: AI-assisted, not human-reviewed.
On this page

Module: L1-M03 · Duration: ~180 min (estimate, including the independent exercise) · Previous: L04 · Next: Module exercises, then L1-M04 (Functional and Negative Testing)

1. Introduction

You already have two ways of testing: the fake API (cheap, stable, but you write the content) and the live test (real, but costly and unstable). Record and replay sits between the two: call the real API once, save the response in a file called a cassette, then play it back from that file in every later run, free of charge and deterministic.

This lesson teaches how to use the technique safely: keep keys and personal data out of the saved file, know when a cassette is out of date, and understand what replay proves and what it does not prove.

2. Learning objectives

  1. Distinguish a fake server, a mock client and replay, with the strengths and weaknesses of each.
  2. Record a response into a cassette and then replay it without calling the server.
  3. Verify that the cassette contains no API key, email address or phone number.
  4. Explain why an unrecorded request must make the test fail (fail closed), and when the cassette needs to be re-recorded.
  5. Design a CI strategy that combines offline tests, replay and a budgeted live test.

3. Prerequisites and tools

  • L01-L04 of this module.
  • L1-M01-L04: data fixtures. A cassette is a kind of fixture recorded from the real system.

4. Concepts

4.1 Three kinds of test double

A test double is something that stands in for a real component during a test.

Kind Stands in for Example in the course Strengths Weaknesses
Mock client The SDK client MockLinguaBot (M01), SimulatedTutor (M02) The simplest Cannot test the SDK and HTTP
Fake server The provider's API FakeClaudeAPI (L01-L04) Tests the real SDK; creates errors at will The content is written by a person; can drift from the real API
Replay Responses recorded from the real API Cassette + ReplayClient (this lesson) Real content; free when replayed Goes stale; replays only exactly the recorded request

Everyday example. Listening practice for an English exam. The teacher reads the questions aloud (a mock client): quick, but not the exam voice. A speaker plays recordings the school made itself (a fake server): the right exam format, but content written by the school. A disc of last year's real exam (a replay): the real voice, but only the questions that were recorded, and this year's exam may differ.

4.2 Cassettes

A cassette stores (request, response) pairs. The lab uses a lookup key for each request: a hash of the request parameters after they have been sorted. On replay, the same parameters give the same lookup key, and the stored response is returned. (To avoid confusion, this lesson uses "API key" for the secret key, and "lookup key" for the hash that identifies a request.)

The lab's cassette stores only the request parameters and the response body. It never stores headers, so the API key (which sits in the Authorization header, see L01) cannot leak into it. In addition, patterns of email addresses, phone numbers and key/token-like strings in the content are redacted before saving. Redaction patterns reduce the risk, but do not recognise every format, and sometimes redact by mistake (for example a 10-digit order number that looks like a phone number). The main rule is still: use synthetic data only.

Everyday example. A bank's automated phone line: each key combination you press (the request) has a pre-recorded message (the response). Press a known combination and you hear exactly that message; press one that does not exist and the line says "invalid choice" rather than playing some other message. Section 5.1 shows how the "key combination" is computed.

4.3 Failing closed when nothing was recorded

If a request is not in the cassette, ReplayClient raises LookupError instead of guessing a response. Why? If the prompt changes (for example the new system prompt in L1-M02-L05), replaying an old response would make the test pass on a behaviour that no longer exists. The error forces you to re-record the cassette deliberately.

Everyday example. An ATM that cannot read a card hands it back, instead of guessing "this must be a regular customer's card" and paying out.

Good vs bad.

Weak replay Good replay
No matching lookup key, so it returns the "closest" response: the test stays green after the system prompt changes (Scenario 2, section 7) No matching lookup key, so it raises a LookupError that says "re-record": the test goes red, and you know you must re-record

4.4 What does replay prove?

Replay proves Replay does not prove
The code correctly handles one recorded real response The model still answers that way today
There is no regression in the response-handling code The answer quality is stable across many runs (L1-M01-L03)
The result is repeatable on every machine and in every run A new model or a new prompt is still good

Common misconception: "Once you have a cassette, you no longer need a live test." A cassette captures a single moment. The model, the API and the prompt all change. You need a periodic live test, and you re-record the cassette when something changes.

Good vs bad. The same green replay run, two ways to write it in the test report:

Wrong Right
"Verified that LinguaBot corrects grammar correctly." "The code handles the response recorded on 2026-10-31 correctly (model and SDK version as in the cassette). Today's model quality has not been re-checked."

4.5 A suggested CI strategy

Layer When it runs Calls the real API? Cost
Unit tests + tests with the fake + replay Every commit No 0
Live smoke test (a few requests) On a schedule (for example nightly) or by hand Yes, with a budget guard Low, capped
Re-recording cassettes When the prompt, the model or the SDK changes Yes Once per change
Quality evaluation on a dataset Before each release (Level 2) Yes Planned separately

L1-M07 will build this pipeline with GitHub Actions.

Everyday example. Looking after a motorbike: every day you glance at the lights and tyres before riding (every commit, free); you take it for a regular service at the shop (a scheduled live smoke test, a small cost); you check it thoroughly after a major part is replaced (re-recording cassettes when the prompt, the model or the SDK changes).

5. Technical deep dive

5.1 The request's lookup key

def request_key(params):
    canonical = json.dumps(params, sort_keys=True, ensure_ascii=False)
    return hashlib.sha256(canonical.encode()).hexdigest()[:16]
  • sort_keys=True makes the order of keys in the dict irrelevant to the result.
  • The lookup key is computed from the unredacted parameters, so two requests that differ only in personal data never share a lookup key. The file stores only the hash and the redacted copy, not the original. (The first version of the lab hashed the redacted copy, and a reviewer pointed out that two different requests would then overwrite each other. The test test_requests_that_differ_only_in_personal_data_do_not_collide keeps that defect from coming back.)
  • Note: a hash is not anonymisation. For short values, someone else can guess them by trying.
  • hashlib.sha256(...) creates the hash; the lab takes the first 16 characters.

Worked example (real run). Compute the lookup key of one request, then change it a little at a time. Run it from the lab folder:

python - <<'EOF'
from lab.cassette import request_key
from lab.tutor_client import SYSTEM

base = {"model": "claude-opus-5-5", "max_tokens": 300, "system": SYSTEM,
        "messages": [{"role": "user", "content": "She go to school"}]}
print("base                 :", request_key(base))
print("same keys, new order :", request_key(dict(reversed(list(base.items())))))
print("max_tokens 300 -> 301:", request_key({**base, "max_tokens": 301}))
print("system + ' Be brief.':", request_key({**base, "system": SYSTEM + " Be brief."}))
EOF

Output (2026-11-06, Linux; Python 3.14.6 and 3.12.3 give identical results):

base                 : 8365b8c5b6a57bcb
same keys, new order : 8365b8c5b6a57bcb
max_tokens 300 -> 301: 739acc08f7dabf12
system + ' Be brief.': 87ead273fb52db38

Line by line: reversing the order of the keys in the dict does not change the lookup key (thanks to sort_keys=True); adding 1 to max_tokens or appending " Be brief." to the system prompt gives a completely different lookup key, so the replay of the old request no longer matches. This is exactly what the exercise in section 9 checks with a test.

5.2 Recording and replaying

  • RecordingClient(client, cassette) wraps a real client (or a client pointed at the fake). Each messages.create(...) call goes to the real client and then the result is stored.
  • ReplayClient(cassette) has the same messages.create(...) interface, so ask() can use it without any change. This is the benefit of code that takes its client from outside (dependency injection).

Everyday example. Like a universal socket: a rice cooker works whether it is plugged into the wall or into a generator, because the plug is the same. ask() is the rice cooker; the real client, RecordingClient and ReplayClient are three sockets with the same messages.create(...) shape.

5.3 A consequence of redaction

The stored response is the redacted copy. So the replayed text differs from the original text where it was redacted (see the demo output). Tests that run on replay must be written for the redacted copy. This is a deliberate trade-off: data safety matters more than keeping the text verbatim.

Worked example (real run). Call redact() directly on two sentences. Run it from the lab folder:

python - <<'EOF'
from lab.cassette import redact

print(redact("Call 0000 000 000 or mail an.nguyen@example.com, key sk-live-abcdef123"))
print(redact("Order 0123456789 ships on 2026-10-31"))
EOF

Output (2026-11-06, Linux; Python 3.14.6 and 3.12.3 give identical results):

Call [REDACTED_PHONE] or mail [REDACTED_EMAIL], key [REDACTED_KEY]
Order [REDACTED_PHONE] ships on 2026-10-31

First line: all three kinds of sensitive data are replaced by labels. Second line: the 10-digit order number is wrongly redacted as a phone number (the limit noted in section 4.2), while the date is kept.

Good vs bad. A test on the replay of the response "She goes to school. Contact an.nguyen@example.com" (the demo in section 8.1):

Wrong test Right test
assert replay.text == "She goes to school. Contact an.nguyen@example.com": always fails assert replay.text == "She goes to school. Contact [REDACTED_EMAIL]"

6. The QA perspective

  • What to test: replay returns exactly the recorded response; an unknown request fails; the cassette contains no key, email address or phone number; a prompt change makes the cassette stop matching.
  • Why: cassettes are committed to Git, which means anyone with read access to the repo can read them.
  • What can go wrong: a cassette contains real customer data; an old cassette makes a test pass wrongly; a cassette recorded from the production environment; replay used as evidence of model quality.
  • Expected behaviour: cassettes are recorded only from synthetic data, reviewed like code before committing, and record the date, the model and the SDK version at recording time.
  • How to detect it: a test that scans cassettes for sensitive patterns; a fail-closed test; reviewing the cassette's diff when re-recording.
  • How to report it: when replay fails because a recording is missing, state which change (prompt, model, parameter) changed the lookup key.

7. Real-world scenarios

Scenario 1 - Customer data in Git (fictional). A team records cassettes from real customer conversations to "test close to reality". The file is committed to a public repo. Prevention: use synthetic data only; automatic redaction; a test that scans cassettes; review before committing.

Scenario 2 - Green tests on an old prompt (fictional). A team's replay system returns the "closest" response when there is no exact match. After the system prompt is changed, every test stays green, because replay returns the response of the old prompt. Lesson: replay must fail closed.

8. Hands-on tutorial

8.1 Running the demo

python -m lab.demo l05

Actual output (2026-10-31):

recorded text : 'She goes to school. Contact an.nguyen@example.com'
replayed text : 'She goes to school. Contact [REDACTED_EMAIL]'
server requests during replay: 0
email in cassette: False  redaction marker present: True
unrecorded request -> LookupError: no recorded response for request 124c6cb4dffd248...

Reading the result:

  • The replayed text has [REDACTED_EMAIL] instead of the email address: that is the stored copy.
  • Replay sends no request to the server.
  • An unrecorded request raises LookupError.

8.2 Running the tests

python -m pytest tests/test_l05_cassette.py -v

Expected result: 22 passed, including a table of 15 sensitive formats that must be redacted. The security test:

def test_cassette_contains_no_key_email_or_phone(tmp_path, client, api):
    api.queue(Reply(body=message("Contact an.nguyen@example.com or 0000 000 000. Key sk-live-abcdef123")))
    cassette = Cassette(tmp_path / "pii.json")
    ask(RecordingClient(client, cassette), "My email is binh@example.com")
    cassette.save()
    saved = (tmp_path / "pii.json").read_text(encoding="utf-8")
    assert "@example.com" not in saved and "sk-live" not in saved and "0000 000 000" not in saved
    assert "[REDACTED_EMAIL]" in saved and "authorization" not in saved.lower()

tmp_path is a built-in pytest fixture: a separate temporary folder for each test, created and cleaned up automatically.

8.3 Troubleshooting

Symptom Cause Fix
LookupError: no recorded response The prompt, the model or a parameter has changed Re-record the cassette deliberately, then review the diff
The replayed text differs from the original text Redaction Write the test for the redacted copy
A regex redacts ordinary content by mistake The pattern is too broad Add a test for a string that must not be redacted, then adjust the pattern

9. Independent exercise

Problem: The team wants to know exactly when a cassette "expires".

Tasks:

  1. Copy exercises/test_l05_invalidation.py into tests/.
  2. Record a cassette, change the system prompt with monkeypatch.setattr, then assert that replay raises LookupError.
  3. List (no code needed) three other changes that also make the cassette stop matching, and one change that does not make the cassette stop matching but still makes it stale.
  4. Write a short procedure (5-7 steps) for re-recording cassettes in the team.

Test data: the learner text "She go to school"; the original system prompt with " Be brief." appended.

Deliverable: the test file, the list of changes, the procedure.

Acceptance criteria: the test passes; the list has at least one change on the provider's side (not in the request); the procedure has a step for reviewing sensitive data.

Hint: the lookup key is computed from the request parameters. What changes without being in the parameters?

9.1 Extra exercise: scan cassettes before committing

Problem (about 25 minutes): the team wants a check before committing: refuse any cassette file that still contains an email address, a key or a phone number. exercises/data/cassette_leaky.json is a cassette (fake data) written by an old script that did not redact.

Tasks:

  1. Copy exercises/test_l05_extra_leak_scan.py into tests/.
  2. Write find_leaks(text): it receives the raw content of a cassette file and returns the set of kinds still present, out of {"email", "key", "phone"}; a clean cassette returns set(). You may reuse the patterns in lab/cassette.py.
  3. Run python -m pytest tests/test_l05_extra_leak_scan.py.

Acceptance criteria: untouched, 7 failed with a TODO message; when done, 7 passed. The test checks a cassette written by the lab (must be clean), the old cassette (must be refused), and ordinary text such as skills, #123456, 2026-10-31 (must not be flagged).

Hint: the shortcuts "@" in text or "sk" in text fail right away on ordinary text. Labels such as [REDACTED_EMAIL] are not leaks.

9.2 Real-world scenario: a pull request that adds 40 cassettes

Context (fictional): a colleague opens a pull request "add 40 cassettes to make tests realistic". The PR description says: the cassettes were recorded on the staging environment from conversations of a group of trial learners; recorded with last month's system prompt; with no date, model or SDK version; and "replay was run, all green".

Your task: write a review note: your decision (approve, request changes, or reject), the risks with the evidence to check, and the conditions for the PR to be merged.

A good answer has:

  • the personal-data risk: real conversations of trial learners, in a repo many people can read;
  • the observation that "all green" is suspicious: cassettes recorded with an old prompt do not match current requests, so you must ask which tests actually replay them (section 4.3);
  • a request for recording metadata: date, model, SDK version (section 6);
  • concrete merge conditions: re-record with synthetic data, run the scan from exercise 9.1, review the diff;
  • a clear decision (here: not approved yet), with a reason.

10. Knowledge check

0/20 done · Results are kept in this browser only.

P02 · True or false

If every replay test passes, the current model still answers the same way as when the cassette was recorded.

P03 · Short answer

Why does the lab's cassette not store headers?

P04 · Short answer

Explain why a replay that fails closed is safer than returning the most similar response.

P05 · Short answer

(Scenario) A colleague wants to record cassettes from production logs "to be close to reality". How do you reply, and what alternative do you propose?

P06 · Match

Using the table in §4.1, match each kind of test double with its weakness.

P07 · Fill in the blank

According to §8.1, the demo python -m lab.demo l05 prints replayed text : 'She goes to school. Contact ___' and server requests during replay: ___.

P08 · Spot the bug

The request_key function below is copied from §5.1 but has one defect. Find it.

def request_key(params):
    canonical = json.dumps(params, ensure_ascii=False)
    return hashlib.sha256(canonical.encode()).hexdigest()[:16]

P09 · True or false

The request's lookup key is computed from the redacted parameters, so that personal data does not affect the key.

P10 · Multiple choice

According to §4.2 and the lab's test_redaction_has_known_false_positives test, what does redact("order 0123456789") return?

P11 · Put in order

Put the steps of a record-then-replay test in order, as in the lab's test_record_then_replay_offline (§5.2, §8.1, §8.2).

  1. Assert that the fake API received exactly one request
  2. Call ask(ReplayClient(Cassette(path)), ...) with the same learner text
  3. Call ask(RecordingClient(client, cassette), ...): the client sends the request and the result is recorded
  4. Call cassette.save() to write the file
  5. Queue a reply in the fake API with api.queue(...)

P12 · Short answer

A test asserts that the replayed text equals "She goes to school. Contact an.nguyen@example.com" and fails. Why, and how do you fix the test?

P13 · Recall

Lesson: L1-M03-L04

Lesson L04: in stream_with_timing, the call ___ returns the complete Message with stop_reason and usage.

P14 · Select all that apply

According to §4.2 and §5.1, what does the lab's cassette file store? Select every correct option.

P15 · Essay

Write 5-8 sentences: the team has just re-recorded a LinguaBot cassette. How do you review its diff before committing?

P17 · Multiple choice

In the output of the worked example in §5.1, which change does not change the lookup key?

P18 · True or false

In the output of the worked example in §5.3, redact() wrongly redacts the order number 0123456789 as [REDACTED_PHONE] but keeps the date 2026-10-31.

P19 · Apply now

In code-labs/l1-m03, run the two pieces of code from the worked examples of §5.1 and §5.3. Then add a line to the §5.1 code that prints the lookup key when the learner text is "She goes to school".

Checklist

P20 · Apply now

In code-labs/l1-m03, do the extra exercise in §9.1: copy exercises/test_l05_extra_leak_scan.py into tests/ and run python -m pytest tests/test_l05_extra_leak_scan.py.

Checklist

11. Summary

  • Concepts: mock client, fake server, replay; the cassette and the request's lookup key; redaction; failing closed; the limits of replay; a multi-layer CI strategy.
  • Skills: recording and replaying responses; scanning cassettes for sensitive data; detecting a cassette that no longer matches.
  • Traps: real data in a cassette; "approximate" replay; treating replay as evidence of model quality; never re-recording the cassette.
  • You can now: build a safe replay test layer for an LLM integration.

12. References

ID Title Publisher URL Accessed Relevance
R1 Claude API errors (request ID) Anthropic https://platform.claude.com/docs/en/api/errors 2026-10-31 The request-id header, used when recording requests for investigation
R2 hashlib - Secure hashes and message digests Python Software Foundation https://docs.python.org/3/library/hashlib.html 2026-10-31 sha256() and hexdigest(), used to create the request's lookup key

Key terms (English ↔ Vietnamese)

English Tiếng Việt
Test double Thành phần đứng thay thành phần thật khi test
Mock / fake / replay Giả lập client / server giả / phát lại response đã ghi
Cassette File lưu các cặp request-response đã ghi
Redaction Che dữ liệu nhạy cảm
Hash Mã băm
Re-record Ghi lại cassette