VCR.py and pytest-recording can replay recorded responses offline, but you must scrub tokens and customer data before committing.
Key takeaways
- Record real requests into a cassette once; from then on, tests replay the responses with no network and no tokens.
- Filter headers, query strings, and response bodies before committing, because cassettes are plain-text files anyone can read.
- Keep pytest-recording's default none mode in CI and add --block-network, so any unexpected request fails the tests.
Picture this scenario: it's your second week on-site with a customer, and their sandbox API starts returning 503 errors every afternoon. Every time it happens, CI goes red, even though you haven't changed a single line of code.
The cleanest solution is to call the real API once, record every request and response, and use that recording for every subsequent run. That's exactly what VCR.py does. According to the library's documentation, on the first test run it records HTTP requests into a YAML-format cassette file, and from then on the tests read from that file.
This guide builds a complete example: write a client for a hypothetical customer orders API, record pytest tests only once, scrub sensitive data before committing, and run CI fully offline. You'll use this approach in the first week of any integration project.
What do you need before starting?
You need Python, pytest, the
requests
library, and two packages:
vcrpy
and
pytest-recording
. The latter is a pytest plugin built on VCR.py that lets you mark tests with
pytest.mark.vcr
instead of wrapping code manually.
pip install pytest requests vcrpy pytest-recording
The
api.example-customer.com
endpoint below is just a placeholder. In a real project, replace it with the customer's sandbox URL and the token they gave you.
Step 1: Write a lightweight client, separate from the tests
Put all HTTP calls in a standalone module. Tests call this function exactly the way production code does.
# orders_client.py
import requests
BASE_URL = "https://api.example-customer.com"
def list_orders(token, status="open"):
resp = requests.get(
f"{BASE_URL}/v1/orders",
params={"status": status},
headers={"Authorization": f"Bearer {token}"},
timeout=10,
)
resp.raise_for_status()
return resp.json()["orders"]Check: run this function once in a terminal with a real token and confirm the API returns the list of orders. If this step fails, don't record anything, because the cassette will faithfully store the errors too.
Step 2: Record your first cassette with vanilla VCR.py
Before using the plugin, see how VCR.py works at the lowest level.
# test_raw.py
import os
import vcr
from orders_client import list_orders
def test_list_orders_raw():
with vcr.use_cassette("fixtures/vcr_cassettes/orders.yaml"):
orders = list_orders(token=os.environ["CUSTOMER_TOKEN"])
assert isinstance(orders, list)VCR.py's default record mode is
once
: it records new interactions when the cassette file doesn't exist, and only replays when it does. Run the test twice; the second run will be noticeably faster because it no longer touches the network.
Now open
orders.yaml
. You'll see the token-bearing
Authorization
header sitting in the file untouched, along with the full contents of customer orders. Note the real email addresses and email domains that appear here; you'll need them for the checks later. Don't commit this file. Delete it and move on to step 3.
Step 3: Switch to pytest-recording and filter secrets
With pytest-recording, the recording configuration lives in a
vcr_config
fixture. This is also where you declare what must never enter the cassette.
# conftest.py
import pytest
from scrub import scrub_response
@pytest.fixture(scope="module")
def vcr_config():
return {
"filter_headers": ["authorization"],
"filter_query_parameters": ["api_key"],
"before_record_response": scrub_response,
}filter_headers
accepts a list of headers to strip during recording;
filter_query_parameters
does the same for query strings. The latter matters when customers put secrets in the URL, such as
?api_key=...
, a pattern still common in legacy systems.
# test_orders.py
import os
import pytest
from orders_client import list_orders
@pytest.mark.vcr
def test_list_open_orders():
token = os.environ.get("CUSTOMER_TOKEN", "dummy")
orders = list_orders(token=token)
assert all(o["status"] == "open" for o in orders)Note the
"dummy"
value: during replay, tests don't need a real token. CI stores no secrets at all, which is exactly what you want.
Step 4: Scrub customer data from responses
Filtering headers only solves half the problem. The response body still contains end users' emails, names, and addresses.
before_record_response
A hook can modify the response before recording, or return
None
to drop the entire request-response pair from the cassette.
# scrub.py
import json
def scrub_response(response):
body = response["body"]["string"]
try:
data = json.loads(body)
except ValueError:
return response
for order in data.get("orders", []):
order["customer_email"] = "[email protected]"
response["body"]["string"] = json.dumps(data).encode()
return responseThis is a simplified version: it assumes the response body is uncompressed JSON and that the field to scrub is called
customer_email
. When integrating with a real API, ask the customer which fields contain personal data; don't guess.
Now re-record. pytest-recording runs in
none
mode by default and won't touch the network accidentally, so you must explicitly enable recording. Since the plugin's recording configuration lives in
vcr_config
, the easiest approach to manage is: temporarily set that fixture to
once
mode on your machine, run the tests once with a real token, then delete that line before committing.
CUSTOMER_TOKEN=xxx pytest test_orders.py
Check: open the newly generated cassette and search for
Bearer
and the token, then search for the customer's real email domain and the email addresses you noted in step 2. Don't search for the
@
string, because the replacement value
contains it too. Commit only when nothing turns up.
[email protected]Step 5: Lock CI into offline mode
No extra recording-mode configuration is needed in CI, because
none
is already the default. This mode errors on any new request, so if someone adds an API call but forgets to record a cassette, the test fails immediately instead of quietly sending requests outward.
pytest --block-network
--block-network
The
vcr
parameter blocks all network access for the duration of the test run, including tests without the
marker. It's a second line of defense, specifically catching network calls that bypass VCR entirely.
What happens when the customer's API changes? How do you re-record?
| 模式 | 行为 | 适用场景 |
|---|---|---|
| Mode | Behavior | When to use |
| once | Records only when the cassette doesn't exist | First recording on your machine |
| new_episodes | Replays existing interactions, records new ones | Adding endpoints to existing tests |
| none | Errors on any new request | CI and all everyday runs |
| all | Never replays, always records | Rarely used; almost never in CI |
rewrite | Re-records the cassette from scratch (pytest-recording) | The customer changed the data schema and you need a clean recording
rewrite
When the customer announces a schema change, run
on your machine, open the file and check for secrets as in step 4, then commit in a separate pull request (PR). This way the cassette's diff shows exactly what changed in the API.
Common mistakes
POST /v1/orders
The first involves request matching. By default, VCR.py matches on method, protocol, host, port, path, and query parameters, which means it ignores the request body. Two
calls with different bodies may be treated as the same request, and the test will get the wrong response.
vcr.use_cassette
When you need to test multiple POSTs to the same URL, the safe approach is, as in step 2, to use
to give each call its own cassette file.
The second is adding filters after the cassette has already been committed. Filters only take effect on the next recording; they can't remove tokens already in git history. When this happens, notify the customer to revoke the token rather than just editing the file.
vcr_config
The third is forgetting to remove the record mode from
all
after debugging is done, worst of all leaving it in
How is this skill used on-site with customers?
In real projects, the cassette can also double as documentation. When a customer asks what your system sent to their API, you open the YAML file and show them the request with sensitive data masked. That answer is more convincing than any architecture diagram.
It also helps with handover. The customer's engineers clone the repository and run
pytest --block-network
, and see all tests pass green without needing to request sandbox access. You leave the site, and the test suite stays behind, still running.
Career-wise: when reading Forward Deployed Engineer (FDE) job descriptions, watch for phrases like "integrate with customer systems" or "own integrations end to end". On your resume, don't just write "wrote tests" — write outcomes, for example: "built an offline integration test suite for a customer API using VCR.py recordings, filtered credentials and personal data, and ran CI without network access".
In interviews, if you can clearly explain why CI should run in
none
mode, the interviewer will see that you understand the risks involved, not just that you know how to use a library.
The next time the customer's sandbox returns a 503, your CI is unaffected. You only need to call the real API again on the day the customer announces a change to their data structures.
Was this article helpful to you?
Thanks for your feedback!