Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

tests(llm_translation): switch to pytest-recording for marker-based bulk capture

Cursor Agent05333e42ba8a
diff --git a/Makefile b/Makefile
index 0e5af3e17c6..8b9e10fa63c 100644
--- a/Makefile
+++ b/Makefile
@@ -187,16 +187,15 @@ test-llm-translation-single: install-test-deps
-v --tb=short --maxfail=100 --timeout=300
# VCR cassette helpers --------------------------------------------------------
-# Re-record a single VCR-backed translation test file against the live API.
-# Provider credentials must be exported (e.g. ANTHROPIC_API_KEY).
+# Sweep-record every @pytest.mark.vcr test under tests/llm_translation in one
+# shot. Provider credentials must be exported for the providers exercised
+# (e.g. ANTHROPIC_API_KEY, OPENAI_API_KEY, AWS_*).
#
-# Example:
+# Examples:
+# ANTHROPIC_API_KEY=sk-ant-... make test-llm-translation-record
# ANTHROPIC_API_KEY=sk-ant-... make test-llm-translation-record \
-# FILE=test_anthropic_completion_vcr.py
+# TARGET=test_anthropic_completion_vcr.py
+TARGET ?= .
test-llm-translation-record: install-test-deps
- @if [ -z "$(FILE)" ]; then \
- echo "Usage: make test-llm-translation-record FILE=test_filename.py"; \
- exit 1; \
- fi
- LITELLM_VCR_RECORD_MODE=once \
- $(UV_RUN) pytest tests/llm_translation/$(FILE) -v --tb=short
+ $(UV_RUN) pytest tests/llm_translation/$(TARGET) \
+ -m vcr --record-mode=once -v --tb=short
diff --git a/pyproject.toml b/pyproject.toml
index 7db6c6d9b11..34003a19a73 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -150,6 +150,7 @@ dev = [
"openapi-core==0.22.0; python_version < '3.14'",
"pytest-timeout==2.4.0",
"vcrpy==8.1.1",
+ "pytest-recording==0.13.4",
]
proxy-dev = [
"prisma==0.11.0",
diff --git a/tests/llm_translation/Readme.md b/tests/llm_translation/Readme.md
index b5a76e48ea8..a7fcfe072a7 100644
--- a/tests/llm_translation/Readme.md
+++ b/tests/llm_translation/Readme.md
@@ -4,15 +4,24 @@ Name of the test file is the name of the LLM provider - e.g. `test_openai.py` is
## VCR-backed tests
-Files matching `*_vcr.py` (e.g. `test_anthropic_completion_vcr.py`) replay
-recorded HTTP traffic from `cassettes/` instead of calling the real provider.
-They run offline by default — no API keys required, no per-PR cost.
+Tests decorated with `@pytest.mark.vcr` (typically in `*_vcr.py` files,
+e.g. `test_anthropic_completion_vcr.py`) replay recorded HTTP traffic from
+`cassettes/` via [`pytest-recording`](https://github.com/kiwicom/pytest-recording)
+instead of calling the real provider. They run offline by default — no API
+keys required, no per-PR cost.
-To re-record against the live API:
+To re-record every marked test in one sweep:
+
+```bash
+ANTHROPIC_API_KEY=sk-ant-... OPENAI_API_KEY=sk-... \
+ make test-llm-translation-record
+```
+
+To scope to a single file:
```bash
ANTHROPIC_API_KEY=sk-ant-... \
- make test-llm-translation-record FILE=test_anthropic_completion_vcr.py
+ make test-llm-translation-record TARGET=test_anthropic_completion_vcr.py
```
See [`cassettes/README.md`](./cassettes/README.md) for the full workflow,
diff --git a/tests/llm_translation/cassettes/README.md b/tests/llm_translation/cassettes/README.md
index 0820d01ebd3..eff373a7685 100644
--- a/tests/llm_translation/cassettes/README.md
+++ b/tests/llm_translation/cassettes/README.md
@@ -11,70 +11,105 @@ and producing flaky CI on outages. Recording the HTTP exchange once and
replaying it on subsequent runs gives us realistic provider responses
(streaming, headers, edge-case payloads) at zero per-PR cost.
-## How to add a new cassette-backed test
+## Layout
+
+We use [`pytest-recording`](https://github.com/kiwicom/pytest-recording),
+which auto-resolves the cassette path from the test location:
+
+```
+tests/llm_translation/
+ cassettes/
+ <test_module>/
+ <test_name>.yaml
+ test_<provider>_completion_vcr.py
+ conftest.py # provides the shared vcr_config fixture
+```
+
+For example, a test
+`tests/llm_translation/test_anthropic_completion_vcr.py::test_basic` is backed by
+`tests/llm_translation/cassettes/test_anthropic_completion_vcr/test_basic.yaml`.
+
+## Adding a new cassette-backed test
1. Pick a small, deterministic call. Avoid prompts whose output depends on
wall-clock time, randomness, or live web data.
-2. Add a test in a `*_vcr.py` file under `tests/llm_translation/`. Wrap it
- with `@litellm_vcr.use_cassette("<some_name>.yaml")` from
- `tests/llm_translation/vcr_config.py`.
-3. Record the cassette once:
-
- ```bash
- LITELLM_VCR_RECORD_MODE=once \
- ANTHROPIC_API_KEY=sk-ant-... \
- uv run pytest tests/llm_translation/test_my_provider_vcr.py::test_my_case -v
- ```
-
- or, equivalently:
-
- ```bash
- ANTHROPIC_API_KEY=sk-ant-... \
- make test-llm-translation-record FILE=test_my_provider_vcr.py
- ```
-
-4. Inspect the resulting YAML file:
- - **Strip any secrets** that survived `vcr_config.py`'s header filter.
- `vcr_config.py` already removes the common ones (`Authorization`,
- `x-api-key`, `cookie`, AWS sigv4 headers, etc.) — but a request *body*
- might contain a token if your test passed one inline.
- - Trim very large response bodies if they aren't load-bearing for the
- assertion.
-5. Commit the cassette alongside the test.
-
-## Re-recording
-
-Run the same `make test-llm-translation-record` command. vcrpy's `once` mode
-will *not* overwrite an existing cassette — delete the file first if you're
-intentionally refreshing it:
+2. Write the test as you normally would and decorate it with
+ `@pytest.mark.vcr`. No imports beyond `pytest` are needed — the
+ `vcr_config` fixture in `conftest.py` is applied automatically.
+3. Run the sweep recorder once with the credentials you need. Recording is
+ strictly opt-in via `--record-mode=once`; the default replay mode never
+ touches the network.
+
+## Bulk re-record (the common path)
+
+A single sweep replays every `@pytest.mark.vcr` test under
+`tests/llm_translation`, hitting the live provider only for tests that don't
+yet have a cassette:
```bash
-rm tests/llm_translation/cassettes/anthropic_basic_completion.yaml
-ANTHROPIC_API_KEY=sk-ant-... make test-llm-translation-record \
- FILE=test_anthropic_completion_vcr.py
+ANTHROPIC_API_KEY=sk-ant-... \
+OPENAI_API_KEY=sk-... \
+AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... \
+ make test-llm-translation-record
```
-## Refreshing the canned Anthropic fixtures
+Or scope it to a single file:
+
+```bash
+ANTHROPIC_API_KEY=sk-ant-... \
+ make test-llm-translation-record TARGET=test_anthropic_completion_vcr.py
+```
-The two Anthropic cassettes in this directory
-(`anthropic_basic_completion.yaml` and `anthropic_streaming_completion.yaml`)
-are recorded against an in-process mock so contributors can regenerate them
-without an `ANTHROPIC_API_KEY`:
+vcrpy's `once` record mode does **not** overwrite an existing cassette —
+delete the file first if you're intentionally refreshing it:
+
+```bash
+rm tests/llm_translation/cassettes/test_anthropic_completion_vcr/test_basic.yaml
+ANTHROPIC_API_KEY=sk-ant-... \
+ make test-llm-translation-record TARGET=test_anthropic_completion_vcr.py
+```
+
+To force a full refresh of every cassette in one shot:
+
+```bash
+rm -rf tests/llm_translation/cassettes/test_*
+ANTHROPIC_API_KEY=... OPENAI_API_KEY=... AWS_* \
+ uv run pytest tests/llm_translation -m vcr --record-mode=all -v
+```
+
+## Refreshing the canned Anthropic fixtures (no API key)
+
+The two Anthropic cassettes shipped with this directory are recorded against
+an in-process mock so contributors can regenerate them without an
+`ANTHROPIC_API_KEY`:
```bash
uv run python tests/llm_translation/cassettes/_record_anthropic_fixtures.py
```
For a full refresh against the real API, delete the cassettes first and use
-the `LITELLM_VCR_RECORD_MODE=once` path with a real key.
+the bulk-record sweep above.
+
+## Cassette hygiene
+
+After recording, **always inspect the YAML before committing**:
+
+- The `vcr_config` fixture in `conftest.py` already filters the common
+ request headers (`Authorization`, `x-api-key`, `anthropic-api-key`, AWS
+ sigv4 headers, cookies, GCP keys, …) and per-request response headers
+ (`set-cookie`, `cf-ray`, request IDs, org IDs, dates).
+- A request *body* might still contain a token if your test passed one
+ inline — scrub it manually.
+- Quick sanity check: `grep -i 'sk-\|bearer\|api-key' cassettes/<dir>/*.yaml`
+ should be clean.
+- Trim unhelpful response bodies if they're megabytes large but the
+ assertion only needs a few fields.
## Don't
-- Don't commit cassettes containing real API keys, OAuth tokens, or PII.
- When in doubt, `grep -i 'sk-\|bearer\|api-key' cassettes/*.yaml` after
- recording.
+- Don't commit cassettes with real API keys, OAuth tokens, or PII.
- Don't rely on cassettes for tests of *non-deterministic* behavior
- (rate-limit retries, timeouts, the model itself making a creative choice).
- Mock those at the LiteLLM layer instead.
-- Don't record both real and mock host names into the same cassette without
- rewriting the URL — vcrpy matches on host/port by default.
+ (rate-limit retries, timeouts, model creativity). Mock those at the
+ LiteLLM layer instead.
+- Don't manually edit cassette YAML beyond scrubbing — the format is
+ byte-sensitive (e.g. content-length headers must match the body).
diff --git a/tests/llm_translation/cassettes/_record_anthropic_fixtures.py b/tests/llm_translation/cassettes/_record_anthropic_fixtures.py
index c17c56169ec..91472fbbd1e 100644
--- a/tests/llm_translation/cassettes/_record_anthropic_fixtures.py
+++ b/tests/llm_translation/cassettes/_record_anthropic_fixtures.py
@@ -1,9 +1,8 @@
"""Helper script that records Anthropic-shaped cassettes against a local mock.
-This is a *one-shot* utility, not a test. It exists so we can deterministically
-regenerate the canned Anthropic cassettes shipped under
-``tests/llm_translation/cassettes/`` without spending real provider credits and
-without needing an ``ANTHROPIC_API_KEY``.
+This is a *one-shot* utility, not a test. It exists so contributors can
+regenerate the canned Anthropic cassettes shipped with this PR without
+spending real provider credits and without needing an ``ANTHROPIC_API_KEY``.
Run it with::
@@ -17,9 +16,14 @@ The script:
3. Rewrites the cassette URL/Host so replay matches genuine
``https://api.anthropic.com/v1/messages`` traffic.
-If you want to refresh against the *real* Anthropic API instead, use the
-``LITELLM_VCR_RECORD_MODE=once`` workflow described in
-``tests/llm_translation/vcr_config.py`` — that path needs a real API key.
+The cassettes are written to the per-test paths that ``pytest-recording``
+expects (``cassettes/<test_module>/<test_name>.yaml``) so the existing tests
+in ``test_anthropic_completion_vcr.py`` pick them up unchanged.
+
+For a refresh against the *real* Anthropic API, use the
+``--record-mode=once`` sweep described in
+``tests/llm_translation/cassettes/README.md`` — that path needs a real
+``ANTHROPIC_API_KEY``.
"""
from __future__ import annotations
@@ -40,7 +44,7 @@ sys.path.insert(0, str(REPO_ROOT))
import litellm # noqa: E402
-CASSETTE_DIR = Path(__file__).parent
+CASSETTE_DIR = Path(__file__).parent / "test_anthropic_completion_vcr"
MOCK_HOST = "127.0.0.1"
NON_STREAM_PORT = 18765
STREAM_PORT = 18766
@@ -201,14 +205,18 @@ def _consume(iterable: Iterable[Any]) -> None:
def record_non_streaming() -> None:
- cassette = CASSETTE_DIR / "anthropic_basic_completion.yaml"
+ cassette = CASSETTE_DIR / "test_anthropic_basic_completion_replay.yaml"
if cassette.exists():
cassette.unlink()
server = _serve(NON_STREAM_PORT, "json")
try:
my_vcr = vcr.VCR(
record_mode="all",
- filter_headers=["authorization", "x-api-key", "anthropic-version"],
+ filter_headers=[
+ "authorization",
+ "x-api-key",
+ "anthropic-version",
+ ],
)
with my_vcr.use_cassette(str(cassette)):
response = litellm.completion(
@@ -224,14 +232,18 @@ def record_non_streaming() -> None:
def record_streaming() -> None:
- cassette = CASSETTE_DIR / "anthropic_streaming_completion.yaml"
+ cassette = CASSETTE_DIR / "test_anthropic_streaming_completion_replay.yaml"
if cassette.exists():
cassette.unlink()
server = _serve(STREAM_PORT, "stream")
try:
my_vcr = vcr.VCR(
record_mode="all",
- filter_headers=["authorization", "x-api-key", "anthropic-version"],
+ filter_headers=[
+ "authorization",
+ "x-api-key",
+ "anthropic-version",
+ ],
)
with my_vcr.use_cassette(str(cassette)):
stream = litellm.completion(
@@ -249,6 +261,7 @@ def record_streaming() -> None:
def main() -> None:
os.environ.setdefault("LITELLM_LOG", "WARNING")
+ CASSETTE_DIR.mkdir(parents=True, exist_ok=True)
record_non_streaming()
record_streaming()
print(f"Wrote cassettes to {CASSETTE_DIR}")
diff --git a/tests/llm_translation/cassettes/anthropic_basic_completion.yaml b/tests/llm_translation/cassettes/test_anthropic_completion_vcr/test_anthropic_basic_completion_replay.yaml
similarity index 100%
rename from tests/llm_translation/cassettes/anthropic_basic_completion.yaml
rename to tests/llm_translation/cassettes/test_anthropic_completion_vcr/test_anthropic_basic_completion_replay.yaml
diff --git a/tests/llm_translation/cassettes/anthropic_streaming_completion.yaml b/tests/llm_translation/cassettes/test_anthropic_completion_vcr/test_anthropic_streaming_completion_replay.yaml
similarity index 100%
rename from tests/llm_translation/cassettes/anthropic_streaming_completion.yaml
rename to tests/llm_translation/cassettes/test_anthropic_completion_vcr/test_anthropic_streaming_completion_replay.yaml
diff --git a/tests/llm_translation/conftest.py b/tests/llm_translation/conftest.py
index d315dc63bcd..831e62d67ec 100644
--- a/tests/llm_translation/conftest.py
+++ b/tests/llm_translation/conftest.py
@@ -18,6 +18,94 @@ import litellm
import asyncio
+
+# ---------------------------------------------------------------------------
+# VCR cassette infrastructure (pytest-recording)
+# ---------------------------------------------------------------------------
+# Tests marked with ``@pytest.mark.vcr`` replay HTTP traffic from a cassette
+# under ``cassettes/<test_module>/<test_name>.yaml`` instead of hitting the
+# live provider. Default record mode is ``none`` (replay only) so CI never
+# accidentally calls a real LLM. To re-record every marked test in one sweep::
+#
+# ANTHROPIC_API_KEY=sk-ant-... \
+# uv run pytest tests/llm_translation -m vcr --record-mode=once
+#
+# See ``tests/llm_translation/cassettes/README.md`` for the full workflow.
+
+# Headers that must never be persisted to a cassette. Matched
+# case-insensitively by vcrpy.
+_FILTERED_REQUEST_HEADERS = (
+ "authorization",
+ "x-api-key",
+ "anthropic-api-key",
+ "openai-api-key",
+ "azure-api-key",
+ "api-key",
+ "cookie",
+ "x-amz-security-token",
+ "x-amz-date",
+ "x-amz-content-sha256",
+ "amz-sdk-invocation-id",
+ "amz-sdk-request",
+ "x-goog-api-key",
+ "x-goog-user-project",
+)
+
+# Per-request response headers we strip so cassettes diff cleanly across
+# re-records.
+_FILTERED_RESPONSE_HEADERS = (
+ "set-cookie",
+ "x-request-id",
+ "request-id",
+ "cf-ray",
+ "anthropic-organization-id",
+ "openai-organization",
+ "x-amzn-requestid",
+ "x-amzn-trace-id",
+ "date",
+)
+
+
+def _scrub_response(response):
+ """Strip per-request response headers we don't want in the cassette."""
+ if not isinstance(response, dict):
+ return response
+ headers = response.get("headers") or {}
+ if isinstance(headers, dict):
+ for header in list(headers):
+ if header.lower() in _FILTERED_RESPONSE_HEADERS:
+ headers.pop(header, None)
+ return response
+
+
[email protected](scope="module")
+def vcr_config():
+ """Shared VCR config consumed by ``pytest-recording``.
+
+ Applied to every ``@pytest.mark.vcr`` test in this directory.
+ """
+ return {
+ "filter_headers": list(_FILTERED_REQUEST_HEADERS),
+ "decode_compressed_response": True,
+ # Match on full request shape so streaming vs non-streaming and
+ # different prompts produce distinct cassettes.
+ "match_on": (
+ "method",
+ "scheme",
+ "host",
+ "port",
+ "path",
+ "query",
+ "body",
+ ),
+ "before_record_response": _scrub_response,
+ }
+
+
+# pytest-recording's default cassette dir is
+# ``<test_dir>/cassettes/<test_module>``. Keep that — it gives every test its
+# own file and avoids name collisions across modules.
+
# ---------------------------------------------------------------------------
# Capture TRUE defaults at conftest import time (before test modules pollute).
# ---------------------------------------------------------------------------
diff --git a/tests/llm_translation/test_anthropic_completion_vcr.py b/tests/llm_translation/test_anthropic_completion_vcr.py
index 6367e65e016..04f2914deb4 100644
--- a/tests/llm_translation/test_anthropic_completion_vcr.py
+++ b/tests/llm_translation/test_anthropic_completion_vcr.py
@@ -1,21 +1,21 @@
"""
-VCR-backed Anthropic completion tests.
+Cassette-replayed Anthropic completion tests.
-These tests exercise the same end-to-end ``litellm.completion`` code paths
-as ``test_anthropic_completion.py`` but replay HTTP traffic from cassettes
-under ``cassettes/`` instead of calling ``api.anthropic.com``. CI can run
-them with no API key and zero cost.
+These tests exercise the same end-to-end ``litellm.completion`` code paths as
+``test_anthropic_completion.py`` but replay HTTP traffic from cassettes under
+``cassettes/test_anthropic_completion_vcr/`` instead of calling
+``api.anthropic.com``. CI runs them with no API key and zero cost.
-To re-record after a deliberate change to request shape (or to refresh
-against the live API), set ``LITELLM_VCR_RECORD_MODE=once`` and provide a
-real ``ANTHROPIC_API_KEY``::
+Add a new test by writing it normally and decorating with ``@pytest.mark.vcr``.
+The cassette path is resolved automatically from the test module + test name
+by ``pytest-recording`` (see ``conftest.py``).
- LITELLM_VCR_RECORD_MODE=once \\
- ANTHROPIC_API_KEY=sk-ant-... \\
- uv run pytest tests/llm_translation/test_anthropic_completion_vcr.py -v
+To re-record every marked test in one sweep::
-See ``tests/llm_translation/vcr_config.py`` and ``tests/llm_translation/cassettes/README.md``
-for the full workflow.
+ ANTHROPIC_API_KEY=sk-ant-... \\
+ uv run pytest tests/llm_translation -m vcr --record-mode=once
+
+See ``tests/llm_translation/cassettes/README.md`` for the full workflow.
"""
import os
@@ -24,39 +24,35 @@ import sys
import pytest
sys.path.insert(0, os.path.abspath("../.."))
-sys.path.insert(0, os.path.dirname(__file__))
import litellm # noqa: E402
-from vcr_config import litellm_vcr # noqa: E402
-
-
-# A non-secret placeholder API key. We never want a real key written to a
-# cassette, and ``vcr_config`` filters Authorization / x-api-key headers
-# anyway. Using a deterministic placeholder also stops the SDK from raising
-# when ``ANTHROPIC_API_KEY`` is unset (the common CI case).
+# A non-secret placeholder API key. The vcr_config fixture in conftest.py
+# filters Authorization / x-api-key headers from cassettes, so this value
+# never lands on disk; it only stops the SDK from raising when
+# ``ANTHROPIC_API_KEY`` is unset (the common CI case).
PLACEHOLDER_ANTHROPIC_API_KEY = "sk-ant-vcr-placeholder"
@pytest.fixture(autouse=True)
def _placeholder_anthropic_key(monkeypatch):
- """Provide a placeholder key when none is set so replay works offline.
+ """Ensure an API key is set so replay works offline.
- If a real key is present in the environment (e.g. when re-recording),
- we leave it untouched.
+ If a real key is present (e.g. when re-recording with
+ ``--record-mode=once``), we leave it untouched.
"""
if not os.environ.get("ANTHROPIC_API_KEY"):
monkeypatch.setenv("ANTHROPIC_API_KEY", PLACEHOLDER_ANTHROPIC_API_KEY)
-@litellm_vcr.use_cassette("anthropic_basic_completion.yaml")
def test_anthropic_basic_completion_replay():
"""Smoke-test that a vanilla Anthropic completion replays from a cassette.
- This is the canonical example for the cassette-based testing pattern:
- no API key required at runtime, deterministic output, and the full
- LiteLLM transformation pipeline (request shaping + response parsing)
- runs against a real-shape Anthropic payload.
+ This is the canonical example for the cassette-based testing pattern: no
+ API key required at runtime, deterministic output, and the full LiteLLM
+ transformation pipeline (request shaping + response parsing) runs against
+ a real-shape Anthropic payload.
"""
response = litellm.completion(
model="anthropic/claude-sonnet-4-5-20250929",
@@ -71,13 +67,14 @@ def test_anthropic_basic_completion_replay():
assert response.choices[0].finish_reason == "stop"
-@litellm_vcr.use_cassette("anthropic_streaming_completion.yaml")
def test_anthropic_streaming_completion_replay():
"""Replay a streaming Anthropic completion from a cassette.
Exercises the SSE chunk parser and the public streaming surface. The
underlying cassette captures every ``content_block_delta`` event Anthropic
- emits, so any regression in the streaming transformation will surface here.
+ emits, so any regression in the streaming transformation will surface
+ here.
"""
stream = litellm.completion(
model="anthropic/claude-sonnet-4-5-20250929",
diff --git a/tests/llm_translation/vcr_config.py b/tests/llm_translation/vcr_config.py
deleted file mode 100644
index 7e641c9cade..00000000000
--- a/tests/llm_translation/vcr_config.py
+++ /dev/null
@@ -1,123 +0,0 @@
-"""
-Shared VCR configuration for ``tests/llm_translation``.
-
-This module centralises the cassette setup used by tests that would otherwise
-hit a real LLM provider over the network. The goal is to let CI replay
-recorded HTTP traffic by default — no API keys required — and to provide a
-single switch for re-recording cassettes against the live provider.
-
-Usage in a test::
-
- from .vcr_config import litellm_vcr # noqa: E402
-
- @litellm_vcr.use_cassette("anthropic_basic_completion.yaml")
- def test_basic_completion():
- resp = litellm.completion(
- model="anthropic/claude-sonnet-4-5-20250929",
- messages=[{"role": "user", "content": "Hello!"}],
- )
- assert resp.choices[0].message.content
-
-Recording mode
---------------
-By default the cassette is replayed (``record_mode='none'``). To re-record:
-
- LITELLM_VCR_RECORD_MODE=once \\
- ANTHROPIC_API_KEY=sk-ant-... \\
- uv run pytest tests/llm_translation/test_anthropic_completion_vcr.py
-
-Valid values for ``LITELLM_VCR_RECORD_MODE`` mirror vcrpy's record modes:
-``none`` (replay only — fail on missing cassette), ``once`` (record if the
-cassette doesn't exist), ``new_episodes`` (append new interactions), and
-``all`` (always re-record). See the vcrpy docs for details.
-
-Why this exists
----------------
-Per the discussion that produced LIT-2683, our e2e tests repeatedly drained
-provider billing accounts and produced flaky CI on outages. Recording the
-HTTP exchange once and replaying it on subsequent runs gives us realistic
-provider responses (including streaming, headers, and edge-case payloads)
-without per-PR cost or rate-limit risk. Re-record periodically to catch
-real provider drift.
-"""
-
-from __future__ import annotations
-
-import os
-from pathlib import Path
-from typing import Any
-
-import vcr
-
-CASSETTE_DIR: Path = Path(__file__).parent / "cassettes"
-
-# Headers that must never be persisted to a cassette. These are matched
-# case-insensitively by vcrpy.
-_FILTERED_REQUEST_HEADERS = (
- "authorization",
- "x-api-key",
- "anthropic-api-key",
- "openai-api-key",
- "azure-api-key",
- "api-key",
- "cookie",
- "x-amz-security-token",
- "x-amz-date",
- "x-amz-content-sha256",
- "amz-sdk-invocation-id",
- "amz-sdk-request",
-)
-
-_FILTERED_RESPONSE_HEADERS = (
- "set-cookie",
- "x-request-id",
- "cf-ray",
- "anthropic-organization-id",
- "openai-organization",
- "request-id",
-)
-
-
-def _record_mode() -> str:
- """Resolve the active vcrpy record mode from the environment.
-
- Defaults to ``"none"`` so CI never accidentally hits the live provider.
- """
- mode = os.environ.get("LITELLM_VCR_RECORD_MODE", "none").strip().lower()
- if mode not in {"none", "once", "new_episodes", "all"}:
- raise ValueError(
- f"LITELLM_VCR_RECORD_MODE={mode!r} is not a valid vcrpy record mode."
- )
- return mode
-
-
-def _build_vcr() -> vcr.VCR:
- """Construct the shared ``VCR`` instance used by translation tests."""
- return vcr.VCR(
- cassette_library_dir=str(CASSETTE_DIR),
- record_mode=_record_mode(),
- # Match on method + URI + body so streaming vs non-streaming and
- # different prompts get distinct cassettes.
- match_on=("method", "scheme", "host", "port", "path", "query", "body"),
- filter_headers=list(_FILTERED_REQUEST_HEADERS),
- decode_compressed_response=True,
- )
-
-
-def _scrub_response(response: Any) -> Any:
- """Strip per-request response headers we don't want in the cassette."""
- if not isinstance(response, dict):
- return response
- headers = response.get("headers") or {}
- if isinstance(headers, dict):
- for header in list(headers):
- if header.lower() in _FILTERED_RESPONSE_HEADERS:
- headers.pop(header, None)
- return response
-
-
-litellm_vcr: vcr.VCR = _build_vcr()
-litellm_vcr.before_record_response = _scrub_response
-
-
-__all__ = ["litellm_vcr", "CASSETTE_DIR"]
diff --git a/uv.lock b/uv.lock
index b2e8aef8a2d..7308122e42d 100644
--- a/uv.lock
+++ b/uv.lock
@@ -9,7 +9,7 @@ resolution-markers = [
]
[options]
-exclude-newer = "2026-04-27T00:38:13.673780212Z"
+exclude-newer = "2026-04-27T18:03:18.987479976Z"
exclude-newer-span = "P3D"
[manifest]
@@ -3231,6 +3231,7 @@ dev = [
{ name = "pytest-cov" },
{ name = "pytest-mock" },
{ name = "pytest-postgresql" },
+ { name = "pytest-recording" },
{ name = "pytest-rerunfailures" },
{ name = "pytest-timeout" },
{ name = "pytest-xdist" },
@@ -3385,6 +3386,7 @@ dev = [
{ name = "pytest-cov", specifier = "==5.0.0" },
{ name = "pytest-mock", specifier = "==3.15.1" },
{ name = "pytest-postgresql", specifier = "==7.0.2" },
+ { name = "pytest-recording", specifier = "==0.13.4" },
{ name = "pytest-rerunfailures", specifier = "==15.1" },
{ name = "pytest-timeout", specifier = "==2.4.0" },
{ name = "pytest-xdist", specifier = "==3.8.0" },
@@ -5922,6 +5924,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/18/57/f2db5a80b10c3ac48ce41786cb9b14172f997509ee1b1055ab7db4238e5e/pytest_postgresql-7.0.2-py3-none-any.whl", hash = "sha256:0b0d31c51620a9c1d6be93286af354256bc58a47c379f56f4147b22da6e81fb5", size = 41447, upload-time = "2025-05-17T20:17:58.011Z" },
]
+[[package]]
+name = "pytest-recording"
+version = "0.13.4"
+source = { registry = "https://pypi.org/simple" }
+dependencies = [
+ { name = "pytest" },
+ { name = "vcrpy" },
+]
+sdist = { url = "https://files.pythonhosted.org/packages/32/9c/f4027c5f1693847b06d11caf4b4f6bb09f22c1581ada4663877ec166b8c6/pytest_recording-0.13.4.tar.gz", hash = "sha256:568d64b2a85992eec4ae0a419c855d5fd96782c5fb016784d86f18053792768c", size = 26576, upload-time = "2025-05-08T10:41:11.231Z" }
+wheels = [
+ { url = "https://files.pythonhosted.org/packages/42/c2/ce34735972cc42d912173e79f200fe66530225190c06655c5632a9d88f1e/pytest_recording-0.13.4-py3-none-any.whl", hash = "sha256:ad49a434b51b1c4f78e85b1e6b74fdcc2a0a581ca16e52c798c6ace971f7f439", size = 13723, upload-time = "2025-05-08T10:41:09.684Z" },
+]
+
[[package]]
name = "pytest-rerunfailures"
version = "15.1"