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]

test: add 24hr Redis-backed VCR cache to additional test suites (#27159)

Mateo Wang7e13256feec3
diff --git a/tests/_vcr_conftest_common.py b/tests/_vcr_conftest_common.py
new file mode 100644
index 00000000000..73a5635ab67
--- /dev/null
+++ b/tests/_vcr_conftest_common.py
@@ -0,0 +1,443 @@
+"""Shared VCR (Redis-backed) plumbing imported by per-directory conftests.
+
+See ``tests/llm_translation/Readme.md`` for the full design and
+``tests/llm_translation/conftest.py`` for the reference wiring."""
+
+from __future__ import annotations
+
+import atexit
+import hashlib
+import os
+import sys
+from typing import Iterable
+
+import pytest
+
+from tests._vcr_redis_persister import (
+ cassette_cache_capacity_snapshot,
+ cassette_cache_health,
+ filter_non_2xx_response,
+ format_vcr_verdict,
+ make_redis_persister,
+ mark_test_outcome_for_cassette,
+ patch_vcrpy_aiohttp_record_path,
+ vcr_verbose_enabled,
+)
+
+CASSETTE_CACHE_HIGH_WATER_FRACTION = 0.85
+
+
+SAFE_BODY_MATCHER_NAME = "safe_body"
+KEY_FINGERPRINT_MATCHER_NAME = "key_fingerprint"
+KEY_FINGERPRINT_HEADER = "x-litellm-key-fp"
+
+# Intentionally narrower than ``FILTERED_REQUEST_HEADERS``: AWS SigV4 headers
+# carry secrets but their values rotate on every call, so fingerprinting them
+# would defeat caching.
+API_KEY_HEADERS = (
+ "authorization",
+ "x-api-key",
+ "anthropic-api-key",
+ "openai-api-key",
+ "azure-api-key",
+ "api-key",
+ "x-goog-api-key",
+)
+
+FILTERED_REQUEST_HEADERS = (
+ "authorization",
+ "x-api-key",
+ "anthropic-api-key",
+ "anthropic-version",
+ "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",
+)
+
+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):
+ 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
+
+
+def _before_record_response(response):
+ return filter_non_2xx_response(_scrub_response(response))
+
+
+def _safe_body_matcher(r1, r2) -> None:
+ """Compare request bodies as bytes; never invokes ``json.loads``.
+
+ vcrpy's stock ``body`` matcher unconditionally json-decodes
+ ``application/json`` payloads, which raises on JSON Lines bodies
+ (e.g. the Bedrock batch S3 PUT) before it can return "no match".
+ This matcher is strictly more conservative — the only equivalence
+ it gives up vs. the default is "JSON key order doesn't matter".
+ """
+ body1 = getattr(r1, "body", None)
+ body2 = getattr(r2, "body", None)
+ if body1 == body2:
+ return
+
+ def _to_bytes(b):
+ if b is None:
+ return b""
+ if isinstance(b, bytes):
+ return b
+ if isinstance(b, str):
+ return b.encode("utf-8")
+ return None
+
+ n1 = _to_bytes(body1)
+ n2 = _to_bytes(body2)
+ if n1 is not None and n2 is not None and n1 == n2:
+ return
+ raise AssertionError("request bodies differ")
+
+
+def _iter_header_values(headers, name: str):
+ if headers is None:
+ return
+ target = name.lower()
+ try:
+ items = headers.items()
+ except AttributeError:
+ return
+ for key, value in items:
+ if str(key).lower() != target:
+ continue
+ if isinstance(value, (list, tuple)):
+ for v in value:
+ yield v
+ else:
+ yield value
+
+
+def _compute_key_fingerprint(request) -> str:
+ headers = getattr(request, "headers", None)
+ parts: list[str] = []
+ for header_name in API_KEY_HEADERS:
+ for value in _iter_header_values(headers, header_name):
+ if value is None:
+ continue
+ text = value if isinstance(value, str) else str(value)
+ text = text.strip()
+ if not text:
+ continue
+ parts.append(f"{header_name}={text}")
+ if not parts:
+ return "no-key"
+ digest = hashlib.sha256("\n".join(parts).encode("utf-8")).hexdigest()
+ return digest[:16]
+
+
+def _strip_headers(headers, names: Iterable[str]) -> None:
+ if headers is None:
+ return
+ targets = {n.lower() for n in names}
+ try:
+ keys = list(headers.keys())
+ except AttributeError:
+ return
+ for key in keys:
+ if str(key).lower() in targets:
+ try:
+ del headers[key]
+ except (KeyError, TypeError):
+ pass
+
+
+def _before_record_request(request):
+ """Fingerprint API keys, then scrub them.
+
+ Order matters in two ways:
+
+ 1. vcrpy's ``filter_headers`` config option runs *before*
+ ``before_record_request``, so the auth-header scrubbing has to
+ live here; otherwise the secret would already be gone when we
+ try to hash it.
+ 2. vcrpy invokes this hook more than once per request (e.g.
+ ``can_play_response_for`` calls it, then ``_responses`` calls it
+ again on the result). The second invocation sees a request whose
+ auth headers we already stripped, so re-hashing would yield
+ ``"no-key"`` and the stored vs. incoming fingerprints would
+ diverge. Skip the recompute when the header is already set so
+ this hook is idempotent.
+ """
+ headers = getattr(request, "headers", None)
+ if headers is None:
+ return request
+ if not any(_iter_header_values(headers, KEY_FINGERPRINT_HEADER)):
+ fingerprint = _compute_key_fingerprint(request)
+ try:
+ headers[KEY_FINGERPRINT_HEADER] = fingerprint
+ except (TypeError, AttributeError):
+ pass
+ _strip_headers(headers, FILTERED_REQUEST_HEADERS)
+ return request
+
+
+def _key_fingerprint_matcher(r1, r2) -> None:
+ def _fp(req):
+ for value in _iter_header_values(
+ getattr(req, "headers", None), KEY_FINGERPRINT_HEADER
+ ):
+ if value is None:
+ continue
+ return value if isinstance(value, str) else str(value)
+ return "no-key"
+
+ if _fp(r1) != _fp(r2):
+ raise AssertionError("API key fingerprints differ")
+
+
+def vcr_config_dict() -> dict:
+ return {
+ "decode_compressed_response": True,
+ "record_mode": "new_episodes",
+ "allow_playback_repeats": True,
+ "match_on": (
+ "method",
+ "scheme",
+ "host",
+ "port",
+ "path",
+ "query",
+ KEY_FINGERPRINT_MATCHER_NAME,
+ SAFE_BODY_MATCHER_NAME,
+ ),
+ "before_record_request": _before_record_request,
+ "before_record_response": _before_record_response,
+ }
+
+
+def vcr_disabled() -> bool:
+ if os.environ.get("LITELLM_VCR_DISABLE") == "1":
+ return True
+ return not os.environ.get("CASSETTE_REDIS_URL")
+
+
+_atexit_banner_registered = False
+
+
+def _print_atexit_banner() -> None:
+ """Fallback for conftests that don't wire up ``pytest_terminal_summary``."""
+ if vcr_disabled():
+ return
+ if os.environ.get("PYTEST_XDIST_WORKER"):
+ return
+ health = cassette_cache_health()
+ save_failures = int(health.get("save_failures", 0) or 0)
+ load_failures = int(health.get("load_failures", 0) or 0)
+ snapshot = cassette_cache_capacity_snapshot()
+
+ def _emit(line: str) -> None:
+ sys.stderr.write(f"{line}\n")
+
+ if save_failures or load_failures:
+ bar = "=" * 60
+ _emit(bar)
+ _emit("VCR CASSETTE CACHE DEGRADED")
+ if save_failures:
+ _emit(
+ f" {save_failures} cassette save failure(s); last error: "
+ f"{health.get('save_failure_last_error', '')}"
+ )
+ if load_failures:
+ _emit(
+ f" {load_failures} cassette load failure(s); last error: "
+ f"{health.get('load_failure_last_error', '')}"
+ )
+ if snapshot:
+ _emit(_format_capacity_line(snapshot))
+ _emit(bar)
+ return
+ if snapshot and snapshot["used_pct"] >= CASSETTE_CACHE_HIGH_WATER_FRACTION * 100:
+ bar = "=" * 60
+ _emit(bar)
+ _emit("VCR CASSETTE CACHE NEAR CAPACITY")
+ _emit(_format_capacity_line(snapshot))
+ _emit(bar)
+
+
+def register_persister_if_enabled(vcr) -> None:
+ """Call from ``pytest_recording_configure(config, vcr)`` in each conftest."""
+ if vcr_disabled():
+ return
+ vcr.register_persister(make_redis_persister())
+ vcr.register_matcher(SAFE_BODY_MATCHER_NAME, _safe_body_matcher)
+ vcr.register_matcher(KEY_FINGERPRINT_MATCHER_NAME, _key_fingerprint_matcher)
+ patch_vcrpy_aiohttp_record_path()
+ global _atexit_banner_registered
+ if not _atexit_banner_registered:
+ atexit.register(_print_atexit_banner)
+ _atexit_banner_registered = True
+
+
+def apply_vcr_auto_marker_to_items(
+ items,
+ *,
+ skip_files: Iterable[str] = (),
+ skip_nodeid_suffixes: Iterable[str] = (),
+) -> None:
+ """Auto-apply ``pytest.mark.vcr`` to collected items.
+
+ ``skip_files`` are basenames to leave un-marked (e.g. respx-using
+ files, since respx and vcrpy both patch the httpx transport).
+ ``skip_nodeid_suffixes`` are node-id suffixes for individual tests
+ that depend on live cross-call provider state.
+ """
+ if vcr_disabled():
+ return
+ skip_files = frozenset(skip_files)
+ skip_nodeid_suffixes = tuple(skip_nodeid_suffixes)
+ for item in items:
+ filename = os.path.basename(str(item.path))
+ if filename in skip_files:
+ continue
+ if any(item.nodeid.endswith(suffix) for suffix in skip_nodeid_suffixes):
+ continue
+ if item.get_closest_marker("vcr") is not None:
+ continue
+ item.add_marker(pytest.mark.vcr)
+
+
+def record_vcr_outcome(request, vcr) -> None:
+ """Call from the post-yield section of an autouse fixture per test."""
+ cassette = vcr
+ rep_call = getattr(request.node, "rep_call", None)
+ test_passed = bool(rep_call and rep_call.passed)
+ cassette_path = getattr(cassette, "_path", None) if cassette is not None else None
+ if cassette_path:
+ mark_test_outcome_for_cassette(cassette_path, test_passed)
+
+ if not vcr_verbose_enabled():
+ return
+ verdict = format_vcr_verdict(cassette)
+ request.node.user_properties.append(("vcr_verdict", verdict))
+
+
+def _format_capacity_line(snapshot: dict) -> str:
+ used = int(snapshot.get("used_memory_bytes", 0) or 0)
+ cap = int(snapshot.get("maxmemory_bytes", 0) or 0)
+ pct = float(snapshot.get("used_pct", 0.0) or 0.0)
+ used_mb = used / (1024 * 1024)
+ cap_mb = cap / (1024 * 1024)
+ return (
+ f" Cassette Redis usage: {used_mb:.1f} MiB / {cap_mb:.1f} MiB "
+ f"({pct:.1f}% of maxmemory)"
+ )
+
+
+def emit_cassette_cache_session_banner(terminalreporter) -> None:
+ """Call from ``pytest_terminal_summary``. No-op on xdist workers."""
+ if vcr_disabled():
+ return
+ if os.environ.get("PYTEST_XDIST_WORKER"):
+ return
+
+ health = cassette_cache_health()
+ save_failures = int(health.get("save_failures", 0) or 0)
+ load_failures = int(health.get("load_failures", 0) or 0)
+ snapshot = cassette_cache_capacity_snapshot()
+
+ if save_failures or load_failures:
+ terminalreporter.write_sep(
+ "=", "VCR CASSETTE CACHE DEGRADED", red=True, bold=True
+ )
+ if save_failures:
+ terminalreporter.write_line(
+ f" {save_failures} cassette save failure(s); last error: "
+ f"{health.get('save_failure_last_error', '')}"
+ )
+ if load_failures:
+ terminalreporter.write_line(
+ f" {load_failures} cassette load failure(s); last error: "
+ f"{health.get('load_failure_last_error', '')}"
+ )
+ terminalreporter.write_line(
+ " Tests still passed because cassette persistence is best-effort, "
+ "but the Redis cache may be degraded (e.g. at maxmemory cap, "
+ "unreachable, or read-only)."
+ )
+ if snapshot:
+ terminalreporter.write_line(_format_capacity_line(snapshot))
+ terminalreporter.write_sep("=", red=True, bold=True)
+ return
+
+ if snapshot and snapshot["used_pct"] >= CASSETTE_CACHE_HIGH_WATER_FRACTION * 100:
+ terminalreporter.write_sep(
+ "=", "VCR CASSETTE CACHE NEAR CAPACITY", yellow=True, bold=True
+ )
+ terminalreporter.write_line(_format_capacity_line(snapshot))
+ terminalreporter.write_line(
+ " No save failures yet, but Redis is approaching maxmemory. "
+ "Consider running tests/_flush_vcr_cache.py or letting more "
+ "keys age out before the next session."
+ )
+ terminalreporter.write_sep("=", yellow=True, bold=True)
+
+
+class VerboseReporterState:
+ """Holds the controller's plugin manager / terminal reporter so each
+ consuming conftest can print ``[VCR HIT|MISS|...]`` lines next to tests."""
+
+ def __init__(self) -> None:
+ self.pluginmanager = None
+ self.terminal_reporter = None
+
+ def remember_pluginmanager(self, config) -> None:
+ if os.environ.get("PYTEST_XDIST_WORKER"):
+ return
+ self.pluginmanager = config.pluginmanager
+
+ def resolve_terminal_reporter(self):
+ if self.terminal_reporter is not None:
+ return self.terminal_reporter
+ if self.pluginmanager is None:
+ return None
+ self.terminal_reporter = self.pluginmanager.getplugin("terminalreporter")
+ return self.terminal_reporter
+
+ def maybe_emit_verdict(self, report) -> None:
+ if report.when != "teardown":
+ return
+ if os.environ.get("PYTEST_XDIST_WORKER"):
+ return
+ if not vcr_verbose_enabled():
+ return
+ reporter = self.resolve_terminal_reporter()
+ if reporter is None:
+ return
+ verdict = next(
+ (v for k, v in (report.user_properties or []) if k == "vcr_verdict"),
+ None,
+ )
+ if not verdict:
+ return
+ reporter.write_line(f"{verdict} :: {report.nodeid}")
diff --git a/tests/_vcr_redis_persister.py b/tests/_vcr_redis_persister.py
index a6ed448f1cb..7fdb7267a38 100644
--- a/tests/_vcr_redis_persister.py
+++ b/tests/_vcr_redis_persister.py
@@ -2,6 +2,7 @@ from __future__ import annotations
import logging
import os
+import warnings
from typing import Any, Optional
from vcr.persisters.filesystem import CassetteNotFoundError
@@ -19,6 +20,74 @@ _log = logging.getLogger(__name__)
_passed_by_cassette_key: dict[str, bool] = {}
+class VCRCassetteCacheWarning(UserWarning):
+ """Emitted when the cassette Redis cache fails to load or save.
+
+ Surfaced in pytest's session-end warnings summary so failures are
+ visible in CI logs even when the underlying tests pass.
+ """
+
+
+# Per-process counters; surfaced via :func:`cassette_cache_health` so
+# conftests can emit a session-end banner when failures occurred.
+_cache_health = {
+ "save_failures": 0,
+ "save_failure_last_error": "",
+ "load_failures": 0,
+ "load_failure_last_error": "",
+}
+
+
+def _record_cache_failure(kind: str, exc: BaseException) -> None:
+ err = f"{type(exc).__name__}: {exc}"
+ if kind == "save":
+ _cache_health["save_failures"] = int(_cache_health["save_failures"]) + 1
+ _cache_health["save_failure_last_error"] = err
+ elif kind == "load":
+ _cache_health["load_failures"] = int(_cache_health["load_failures"]) + 1
+ _cache_health["load_failure_last_error"] = err
+
+
+def cassette_cache_health() -> dict:
+ return dict(_cache_health)
+
+
+def reset_cassette_cache_health() -> None:
+ _cache_health["save_failures"] = 0
+ _cache_health["save_failure_last_error"] = ""
+ _cache_health["load_failures"] = 0
+ _cache_health["load_failure_last_error"] = ""
+
+
+def cassette_cache_capacity_snapshot(client: Optional[Any] = None) -> Optional[dict]:
+ """Probe Redis ``INFO memory`` and return used/max bytes and percent.
+
+ Returns ``None`` if Redis is unreachable, the server didn't report
+ ``maxmemory``, or ``maxmemory`` is 0 (uncapped). Best-effort: any
+ exception turns into ``None`` so this never breaks a test session.
+ """
+ try:
+ if client is None:
+ client = _build_default_client()
+ info = client.info(section="memory")
+ except Exception: # pragma: no cover - best-effort probe
+ return None
+ used = info.get("used_memory")
+ maxmem = info.get("maxmemory")
+ try:
+ used = int(used) if used is not None else None
+ maxmem = int(maxmem) if maxmem is not None else None
+ except (TypeError, ValueError): # pragma: no cover - defensive
+ return None
+ if not used or not maxmem or maxmem <= 0:
+ return None
+ return {
+ "used_memory_bytes": used,
+ "maxmemory_bytes": maxmem,
+ "used_pct": (used / maxmem) * 100.0,
+ }
+
+
def mark_test_outcome_for_cassette(cassette_path: str, passed: bool) -> None:
_passed_by_cassette_key[redis_key_for(cassette_path)] = passed
@@ -70,24 +139,23 @@ def make_redis_persister(
redis_client = client if client is not None else _build_default_client()
try:
- from redis.exceptions import ConnectionError as RedisConnectionError
- from redis.exceptions import TimeoutError as RedisTimeoutError
-
- _transient_errors: tuple = (RedisConnectionError, RedisTimeoutError)
+ from redis.exceptions import RedisError
except ImportError: # pragma: no cover - redis is a hard test dep
- _transient_errors = ()
+ RedisError = Exception # type: ignore[assignment,misc]
class _RedisPersister:
@staticmethod
def load_cassette(cassette_path, serializer):
try:
data = redis_client.get(redis_key_for(cassette_path))
- except _transient_errors as exc:
- _log.warning(
- "VCR redis load failed for %s; treating as cache miss: %s",
- cassette_path,
- exc,
+ except RedisError as exc:
+ _record_cache_failure("load", exc)
+ msg = (
+ f"VCR redis load failed for {cassette_path}; treating "
+ f"as cache miss: {type(exc).__name__}: {exc}"
)
+ _log.warning(msg)
+ warnings.warn(msg, VCRCassetteCacheWarning, stacklevel=2)
raise CassetteNotFoundError() from exc
if data is None:
raise CassetteNotFoundError()
@@ -123,12 +191,21 @@ def make_redis_persister(
payload = data.encode("utf-8") if isinstance(data, str) else data
try:
redis_client.set(key, payload, ex=ttl_seconds)
- except _transient_errors as exc:
- _log.warning(
- "VCR redis save failed for %s; cassette not persisted: %s",
- cassette_path,
- exc,
+ except RedisError as exc:
+ # Cassette persistence is strictly best-effort: connection
+ # blips, timeouts, OOM at the maxmemory cap, READONLY
+ # replicas, etc. should all degrade gracefully to "test
+ # passed but cassette not cached" rather than failing the
+ # test on teardown. We still want a loud signal so the
+ # failure shows up in pytest's warnings summary at the
+ # end of the session and feeds the session-end banner.
+ _record_cache_failure("save", exc)
+ msg = (
+ f"VCR redis save failed for {cassette_path}; cassette "
+ f"not persisted: {type(exc).__name__}: {exc}"
)
+ _log.warning(msg)
+ warnings.warn(msg, VCRCassetteCacheWarning, stacklevel=2)
return _RedisPersister
diff --git a/tests/audio_tests/conftest.py b/tests/audio_tests/conftest.py
new file mode 100644
index 00000000000..d07057a4b63
--- /dev/null
+++ b/tests/audio_tests/conftest.py
@@ -0,0 +1,50 @@
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../.."))
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
+def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
diff --git a/tests/batches_tests/conftest.py b/tests/batches_tests/conftest.py
index f0a28236596..e6e31546a82 100644
--- a/tests/batches_tests/conftest.py
+++ b/tests/batches_tests/conftest.py
@@ -1,5 +1,6 @@
# conftest.py
+import asyncio
import importlib
import os
import sys
@@ -9,8 +10,17 @@ import pytest
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
-import litellm
-import asyncio
+import litellm # noqa: E402,F401
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
@pytest.fixture(scope="session")
@@ -21,3 +31,37 @@ def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
+def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
diff --git a/tests/guardrails_tests/conftest.py b/tests/guardrails_tests/conftest.py
index c57d4ed5de7..674d5500c3c 100644
--- a/tests/guardrails_tests/conftest.py
+++ b/tests/guardrails_tests/conftest.py
@@ -16,6 +16,46 @@ sys.path.insert(
) # Adds the parent directory to the system path
import litellm
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
@pytest.fixture(scope="function", autouse=True)
def isolate_litellm_state():
@@ -97,6 +137,8 @@ def setup_and_teardown():
def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
+
# Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
custom_logger_tests = [
item for item in items if "custom_logger" in item.parent.name
diff --git a/tests/image_gen_tests/conftest.py b/tests/image_gen_tests/conftest.py
index c0b1a44be84..ae67a4a9243 100644
--- a/tests/image_gen_tests/conftest.py
+++ b/tests/image_gen_tests/conftest.py
@@ -1,15 +1,23 @@
-import importlib
+import asyncio
import os
import sys
-import asyncio
+
import pytest
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
-import litellm
+import litellm # noqa: E402,F401
-import asyncio
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
@pytest.fixture(scope="session")
@@ -20,3 +28,37 @@ def event_loop():
loop = asyncio.new_event_loop()
yield loop
loop.close()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
+def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
diff --git a/tests/litellm_utils_tests/conftest.py b/tests/litellm_utils_tests/conftest.py
index eca0bc431a5..a110128d2ff 100644
--- a/tests/litellm_utils_tests/conftest.py
+++ b/tests/litellm_utils_tests/conftest.py
@@ -1,5 +1,6 @@
# conftest.py
+import asyncio
import importlib
import os
import sys
@@ -9,7 +10,29 @@ import pytest
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
-import litellm
+import litellm # noqa: E402,F401
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
+
+
+# Files where VCR replay breaks the test:
+# - ``test_litellm_overhead.py``: asserts overhead/total < 40%, which
+# inverts when cached replay collapses the upstream time to microseconds.
+_VCR_INCOMPATIBLE_FILES = frozenset(
+ {
+ "test_litellm_overhead.py",
+ }
+)
+
+_VCR_INCOMPATIBLE_NODEID_SUFFIXES: tuple[str, ...] = ()
@pytest.fixture(scope="function", autouse=True)
@@ -17,21 +40,17 @@ def setup_and_teardown():
"""
This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
"""
- curr_dir = os.getcwd() # Get the current working directory
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the project directory to the system path
import litellm
- from litellm import Router
importlib.reload(litellm)
- import asyncio
loop = asyncio.get_event_loop_policy().new_event_loop()
asyncio.set_event_loop(loop)
print(litellm)
- # from litellm import Router, completion, aembedding, acompletion, embedding
yield
# Teardown code (executes after the yield point)
@@ -39,7 +58,43 @@ def setup_and_teardown():
asyncio.set_event_loop(None) # Remove the reference to the loop
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(
+ items,
+ skip_files=_VCR_INCOMPATIBLE_FILES,
+ skip_nodeid_suffixes=_VCR_INCOMPATIBLE_NODEID_SUFFIXES,
+ )
+
# Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
custom_logger_tests = [
item for item in items if "custom_logger" in item.parent.name
diff --git a/tests/llm_responses_api_testing/conftest.py b/tests/llm_responses_api_testing/conftest.py
index 80f36e159a9..e16d3cb4a3f 100644
--- a/tests/llm_responses_api_testing/conftest.py
+++ b/tests/llm_responses_api_testing/conftest.py
@@ -13,97 +13,24 @@ sys.path.insert(
import litellm # noqa: E402
-from tests._vcr_redis_persister import ( # noqa: E402
- filter_non_2xx_response,
- format_vcr_verdict,
- make_redis_persister,
- mark_test_outcome_for_cassette,
- patch_vcrpy_aiohttp_record_path,
- vcr_verbose_enabled,
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
)
-
-_controller_pluginmanager = None
-_controller_terminal_reporter = None
-
-
-_FILTERED_REQUEST_HEADERS = (
- "authorization",
- "x-api-key",
- "anthropic-api-key",
- "anthropic-version",
- "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",
-)
-
-_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):
- 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
-
-
-def _before_record_response(response):
- return filter_non_2xx_response(_scrub_response(response))
+_verbose_state = VerboseReporterState()
@pytest.fixture(scope="module")
def vcr_config():
- return {
- "filter_headers": list(_FILTERED_REQUEST_HEADERS),
- "decode_compressed_response": True,
- "record_mode": "new_episodes",
- "allow_playback_repeats": True,
- "match_on": (
- "method",
- "scheme",
- "host",
- "port",
- "path",
- "query",
- "body",
- ),
- "before_record_response": _before_record_response,
- }
-
-
-def _vcr_disabled() -> bool:
- if os.environ.get("LITELLM_VCR_DISABLE") == "1":
- return True
- return not os.environ.get("CASSETTE_REDIS_URL")
+ return vcr_config_dict()
def pytest_recording_configure(config, vcr):
- if _vcr_disabled():
- return
- vcr.register_persister(make_redis_persister())
- patch_vcrpy_aiohttp_record_path()
+ register_persister_if_enabled(vcr)
@pytest.hookimpl(hookwrapper=True)
@@ -116,55 +43,15 @@ def pytest_runtest_makereport(item, call):
@pytest.fixture(autouse=True)
def _vcr_outcome_gate(request, vcr):
yield
- cassette = vcr
- rep_call = getattr(request.node, "rep_call", None)
- test_passed = bool(rep_call and rep_call.passed)
- cassette_path = getattr(cassette, "_path", None) if cassette is not None else None
- if cassette_path:
- mark_test_outcome_for_cassette(cassette_path, test_passed)
-
- if not vcr_verbose_enabled():
- return
- verdict = format_vcr_verdict(cassette)
- request.node.user_properties.append(("vcr_verdict", verdict))
+ record_vcr_outcome(request, vcr)
def pytest_configure(config):
- global _controller_pluginmanager
- if os.environ.get("PYTEST_XDIST_WORKER"):
- return
- _controller_pluginmanager = config.pluginmanager
-
-
-def _resolve_terminal_reporter():
- global _controller_terminal_reporter
- if _controller_terminal_reporter is not None:
- return _controller_terminal_reporter
- if _controller_pluginmanager is None:
- return None
- _controller_terminal_reporter = _controller_pluginmanager.getplugin(
- "terminalreporter"
- )
- return _controller_terminal_reporter
+ _verbose_state.remember_pluginmanager(config)
def pytest_runtest_logreport(report):
- if report.when != "teardown":
- return
- if os.environ.get("PYTEST_XDIST_WORKER"):
- return
- if not vcr_verbose_enabled():
- return
- reporter = _resolve_terminal_reporter()
- if reporter is None:
- return
- verdict = next(
- (v for k, v in (report.user_properties or []) if k == "vcr_verdict"),
- None,
- )
- if not verdict:
- return
- reporter.write_line(f"{verdict} :: {report.nodeid}")
+ _verbose_state.maybe_emit_verdict(report)
@pytest.fixture(scope="session")
@@ -182,13 +69,11 @@ def setup_and_teardown():
"""
This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
"""
- curr_dir = os.getcwd() # Get the current working directory
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the project directory to the system path
import litellm
- from litellm import Router
importlib.reload(litellm)
@@ -200,12 +85,9 @@ def setup_and_teardown():
except Exception as e:
print(f"Error reloading litellm.proxy.proxy_server: {e}")
- import asyncio
-
loop = asyncio.get_event_loop_policy().new_event_loop()
asyncio.set_event_loop(loop)
print(litellm)
- # from litellm import Router, completion, aembedding, acompletion, embedding
yield
# Teardown code (executes after the yield point)
@@ -214,11 +96,7 @@ def setup_and_teardown():
def pytest_collection_modifyitems(config, items):
- if not _vcr_disabled():
- for item in items:
- if item.get_closest_marker("vcr") is not None:
- continue
- item.add_marker(pytest.mark.vcr)
+ apply_vcr_auto_marker_to_items(items)
custom_logger_tests = [
item for item in items if "custom_logger" in item.parent.name
diff --git a/tests/llm_translation/Readme.md b/tests/llm_translation/Readme.md
index 958adbd9755..813c188ee7b 100644
--- a/tests/llm_translation/Readme.md
+++ b/tests/llm_translation/Readme.md
@@ -16,12 +16,38 @@ The persister, header scrubbing, and 2xx-only filtering are defined in
patches the same httpx transport vcrpy does) are excluded from the
auto-marker — see `_RESPX_CONFLICTING_FILES` in `conftest.py`.
+The same VCR cache is used by other test directories that exercise live
+provider APIs. The reusable conftest plumbing lives in
+`tests/_vcr_conftest_common.py` and is wired into:
+
+- `tests/llm_translation/`
+- `tests/llm_responses_api_testing/`
+- `tests/audio_tests/`
+- `tests/batches_tests/`
+- `tests/guardrails_tests/`
+- `tests/image_gen_tests/`
+- `tests/litellm_utils_tests/`
+- `tests/local_testing/` (covers `local_testing_part1`, `local_testing_part2`,
+ `litellm_router_testing`, `litellm_assistants_api_testing`,
+ `langfuse_logging_unit_tests`)
+- `tests/logging_callback_tests/`
+- `tests/pass_through_unit_tests/`
+- `tests/router_unit_tests/`
+- `tests/unified_google_tests/`
+
+Test directories that run LiteLLM proxy in Docker (e.g. `build_and_test`,
+`proxy_logging_guardrails_model_info_tests`, `proxy_store_model_in_db_tests`)
+are intentionally not included: VCR.py patches the in-process httpx
+transport, so it cannot intercept the LLM calls that originate inside the
+Docker container.
+
### Required environment
-`REDIS_HOST`, `REDIS_PORT`, `REDIS_PASSWORD` — same vars CircleCI uses for
-its other Redis-backed jobs. Provider credentials
-(`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `AWS_*`, etc.) are needed only on
-cache-miss (the daily re-record), not on replay.
+`CASSETTE_REDIS_URL` — separate Redis instance from the application
+Redis (`REDIS_URL`/`REDIS_HOST`) so test cassettes are not flushed by
+proxy tests. Provider credentials (`ANTHROPIC_API_KEY`, `OPENAI_API_KEY`,
+`AWS_*`, etc.) are needed only on cache-miss (the daily re-record), not
+on replay.
### Flushing the cache
diff --git a/tests/llm_translation/conftest.py b/tests/llm_translation/conftest.py
index 17ffb800ea0..a059c4540c7 100644
--- a/tests/llm_translation/conftest.py
+++ b/tests/llm_translation/conftest.py
@@ -18,20 +18,14 @@ sys.path.insert(
import litellm # noqa: E402
-from tests._vcr_redis_persister import ( # noqa: E402
- filter_non_2xx_response,
- format_vcr_verdict,
- make_redis_persister,
- mark_test_outcome_for_cassette,
- patch_vcrpy_aiohttp_record_path,
- vcr_verbose_enabled,
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
)
-
-_controller_pluginmanager = None
-_controller_terminal_reporter = None
-
-
# vcrpy and respx both patch the httpx transport — applying both makes one
# silently win, so respx-using files opt out of the auto-marker.
_RESPX_CONFLICTING_FILES = frozenset(
@@ -51,96 +45,23 @@ _VCR_AUTO_MARKER_SKIP_FILES = _RESPX_CONFLICTING_FILES | frozenset(
# Tests that observe live cross-call provider state (e.g. prompt-cache
# warm-up between two consecutive calls); replay can't reproduce that state.
-_VCR_INCOMPATIBLE_NODEID_SUFFIXES = frozenset(
- {
- "::test_prompt_caching",
- "TestBedrockInvokeNovaJson::test_json_response_pydantic_obj",
- "::test_bedrock_converse__streaming_passthrough",
- }
-)
-
-
-def _is_vcr_incompatible(nodeid: str) -> bool:
- return any(nodeid.endswith(suffix) for suffix in _VCR_INCOMPATIBLE_NODEID_SUFFIXES)
-
-
-_FILTERED_REQUEST_HEADERS = (
- "authorization",
- "x-api-key",
- "anthropic-api-key",
- "anthropic-version",
- "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",
-)
-
-_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",
+_VCR_INCOMPATIBLE_NODEID_SUFFIXES = (
+ "::test_prompt_caching",
+ "TestBedrockInvokeNovaJson::test_json_response_pydantic_obj",
+ "::test_bedrock_converse__streaming_passthrough",
)
-def _scrub_response(response):
- 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
-
-
-def _before_record_response(response):
- return filter_non_2xx_response(_scrub_response(response))
+_verbose_state = VerboseReporterState()
@pytest.fixture(scope="module")
def vcr_config():
- return {
- "filter_headers": list(_FILTERED_REQUEST_HEADERS),
- "decode_compressed_response": True,
- "record_mode": "new_episodes",
- "allow_playback_repeats": True,
- "match_on": (
- "method",
- "scheme",
- "host",
- "port",
- "path",
- "query",
- "body",
- ),
- "before_record_response": _before_record_response,
- }
-
-
-def _vcr_disabled() -> bool:
- if os.environ.get("LITELLM_VCR_DISABLE") == "1":
- return True
- return not os.environ.get("CASSETTE_REDIS_URL")
+ return vcr_config_dict()
def pytest_recording_configure(config, vcr):
- if _vcr_disabled():
- return
- vcr.register_persister(make_redis_persister())
- patch_vcrpy_aiohttp_record_path()
+ register_persister_if_enabled(vcr)
@pytest.hookimpl(hookwrapper=True)
@@ -153,55 +74,15 @@ def pytest_runtest_makereport(item, call):
@pytest.fixture(autouse=True)
def _vcr_outcome_gate(request, vcr):
yield
- cassette = vcr
- rep_call = getattr(request.node, "rep_call", None)
- test_passed = bool(rep_call and rep_call.passed)
- cassette_path = getattr(cassette, "_path", None) if cassette is not None else None
- if cassette_path:
- mark_test_outcome_for_cassette(cassette_path, test_passed)
-
- if not vcr_verbose_enabled():
- return
- verdict = format_vcr_verdict(cassette)
- request.node.user_properties.append(("vcr_verdict", verdict))
+ record_vcr_outcome(request, vcr)
def pytest_configure(config):
- global _controller_pluginmanager
- if os.environ.get("PYTEST_XDIST_WORKER"):
- return
- _controller_pluginmanager = config.pluginmanager
-
-
-def _resolve_terminal_reporter():
- global _controller_terminal_reporter
- if _controller_terminal_reporter is not None:
- return _controller_terminal_reporter
- if _controller_pluginmanager is None:
- return None
- _controller_terminal_reporter = _controller_pluginmanager.getplugin(
- "terminalreporter"
- )
- return _controller_terminal_reporter
+ _verbose_state.remember_pluginmanager(config)
def pytest_runtest_logreport(report):
- if report.when != "teardown":
- return
- if os.environ.get("PYTEST_XDIST_WORKER"):
- return
- if not vcr_verbose_enabled():
- return
- reporter = _resolve_terminal_reporter()
- if reporter is None:
- return
- verdict = next(
- (v for k, v in (report.user_properties or []) if k == "vcr_verdict"),
- None,
- )
- if not verdict:
- return
- reporter.write_line(f"{verdict} :: {report.nodeid}")
+ _verbose_state.maybe_emit_verdict(report)
# ---------------------------------------------------------------------------
@@ -282,16 +163,11 @@ def setup_and_teardown(event_loop): # Add event_loop as a dependency
def pytest_collection_modifyitems(config, items):
- if not _vcr_disabled():
- for item in items:
- filename = os.path.basename(str(item.fspath))
- if filename in _VCR_AUTO_MARKER_SKIP_FILES:
- continue
- if _is_vcr_incompatible(item.nodeid):
- continue
- if item.get_closest_marker("vcr") is not None:
- continue
- item.add_marker(pytest.mark.vcr)
+ apply_vcr_auto_marker_to_items(
+ items,
+ skip_files=_VCR_AUTO_MARKER_SKIP_FILES,
+ skip_nodeid_suffixes=_VCR_INCOMPATIBLE_NODEID_SUFFIXES,
+ )
custom_logger_tests = [
item for item in items if "custom_logger" in item.parent.name
diff --git a/tests/llm_translation/test_vcr_conftest_common_banner.py b/tests/llm_translation/test_vcr_conftest_common_banner.py
new file mode 100644
index 00000000000..70ee39abd39
--- /dev/null
+++ b/tests/llm_translation/test_vcr_conftest_common_banner.py
@@ -0,0 +1,181 @@
+from __future__ import annotations
+
+import os
+import sys
+from io import StringIO
+
+import pytest
+
+sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ emit_cassette_cache_session_banner,
+)
+from tests._vcr_redis_persister import ( # noqa: E402
+ _cache_health,
+ reset_cassette_cache_health,
+)
+
+
+class _FakeTerminalReporter:
+ def __init__(self) -> None:
+ self.buf = StringIO()
+
+ def write_sep(self, sep, title="", **kwargs):
+ if title:
+ self.buf.write(f"{sep * 5} {title} {sep * 5}\n")
+ else:
+ self.buf.write(f"{sep * 60}\n")
+
+ def write_line(self, line):
+ self.buf.write(f"{line}\n")
+
+ @property
+ def output(self) -> str:
+ return self.buf.getvalue()
+
+
+def health_reset():
+ reset_cassette_cache_health()
+ yield
+ reset_cassette_cache_health()
+
+
+def vcr_enabled(monkeypatch):
+ """Make :func:`vcr_disabled` return False so the banner emits."""
+ monkeypatch.setenv("CASSETTE_REDIS_URL", "redis://stub")
+ monkeypatch.delenv("LITELLM_VCR_DISABLE", raising=False)
+ monkeypatch.delenv("PYTEST_XDIST_WORKER", raising=False)
+
+
+def patch_capacity_snapshot(monkeypatch):
+ """Stub :func:`cassette_cache_capacity_snapshot` so we don't try to
+ open a real Redis connection. The fixture returns a setter that
+ each test uses to inject the snapshot it wants."""
+ state = {"snapshot": None}
+
+ def _stub():
+ return state["snapshot"]
+
+ import tests._vcr_conftest_common as common
+
+ monkeypatch.setattr(common, "cassette_cache_capacity_snapshot", _stub)
+
+ def _set(snapshot):
+ state["snapshot"] = snapshot
+
+ return _set
+
+
+def test_banner_silent_when_no_failures_and_capacity_healthy(
+ health_reset, vcr_enabled, patch_capacity_snapshot
+):
+ patch_capacity_snapshot(
+ {"used_memory_bytes": 100, "maxmemory_bytes": 1000, "used_pct": 10.0}
+ )
+ reporter = _FakeTerminalReporter()
+
+ emit_cassette_cache_session_banner(reporter)
+
+ assert reporter.output == ""
+
+
+def test_banner_red_section_when_save_failures_recorded(
+ health_reset, vcr_enabled, patch_capacity_snapshot
+):
+ _cache_health["save_failures"] = 3
+ _cache_health["save_failure_last_error"] = (
+ "OutOfMemoryError: command not allowed when used memory > 'maxmemory'."
+ )
+ patch_capacity_snapshot(
+ {"used_memory_bytes": 990, "maxmemory_bytes": 1000, "used_pct": 99.0}
+ )
+ reporter = _FakeTerminalReporter()
+
+ emit_cassette_cache_session_banner(reporter)
+
+ out = reporter.output
+ assert "VCR CASSETTE CACHE DEGRADED" in out
+ assert "3 cassette save failure(s)" in out
+ assert "OutOfMemoryError" in out
+ assert "99.0% of maxmemory" in out
+
+
+def test_banner_red_section_when_load_failures_recorded(
+ health_reset, vcr_enabled, patch_capacity_snapshot
+):
+ _cache_health["load_failures"] = 2
+ _cache_health["load_failure_last_error"] = "ConnectionError: simulated outage"
+ patch_capacity_snapshot(None)
+ reporter = _FakeTerminalReporter()
+
+ emit_cassette_cache_session_banner(reporter)
+
+ out = reporter.output
+ assert "VCR CASSETTE CACHE DEGRADED" in out
+ assert "2 cassette load failure(s)" in out
+ assert "ConnectionError" in out
+
+
+def test_banner_yellow_high_water_when_no_failures_but_near_capacity(
+ health_reset, vcr_enabled, patch_capacity_snapshot
+):
+ patch_capacity_snapshot(
+ {"used_memory_bytes": 900, "maxmemory_bytes": 1000, "used_pct": 90.0}
+ )
+ reporter = _FakeTerminalReporter()
+
+ emit_cassette_cache_session_banner(reporter)
+
+ out = reporter.output
+ assert "VCR CASSETTE CACHE NEAR CAPACITY" in out
+ assert "90.0% of maxmemory" in out
+ assert "VCR CASSETTE CACHE DEGRADED" not in out
+
+
+def test_banner_silent_when_below_high_water_and_no_failures(
+ health_reset, vcr_enabled, patch_capacity_snapshot
+):
+ patch_capacity_snapshot(
+ {"used_memory_bytes": 800, "maxmemory_bytes": 1000, "used_pct": 80.0}
+ )
+ reporter = _FakeTerminalReporter()
+
+ emit_cassette_cache_session_banner(reporter)
+
+ assert reporter.output == ""
+
+
+def test_banner_silent_when_vcr_disabled(
+ monkeypatch, health_reset, patch_capacity_snapshot
+):
+ monkeypatch.delenv("CASSETTE_REDIS_URL", raising=False)
+ _cache_health["save_failures"] = 5
+ _cache_health["save_failure_last_error"] = "OutOfMemoryError: foo"
+ patch_capacity_snapshot(
+ {"used_memory_bytes": 999, "maxmemory_bytes": 1000, "used_pct": 99.9}
+ )
+ reporter = _FakeTerminalReporter()
+
+ emit_cassette_cache_session_banner(reporter)
+
+ assert reporter.output == ""
+
+
+def test_banner_silent_on_xdist_worker(
+ monkeypatch, vcr_enabled, health_reset, patch_capacity_snapshot
+):
+ monkeypatch.setenv("PYTEST_XDIST_WORKER", "gw3")
+ _cache_health["save_failures"] = 1
+ _cache_health["save_failure_last_error"] = "OutOfMemoryError: bar"
+ patch_capacity_snapshot(
+ {"used_memory_bytes": 999, "maxmemory_bytes": 1000, "used_pct": 99.9}
+ )
+ reporter = _FakeTerminalReporter()
+
+ emit_cassette_cache_session_banner(reporter)
+
+ assert reporter.output == ""
diff --git a/tests/llm_translation/test_vcr_redis_persister.py b/tests/llm_translation/test_vcr_redis_persister.py
index 6e62e4491cb..ec86ee73597 100644
--- a/tests/llm_translation/test_vcr_redis_persister.py
+++ b/tests/llm_translation/test_vcr_redis_persister.py
@@ -6,6 +6,8 @@ import sys
import fakeredis
import pytest
from redis.exceptions import ConnectionError as RedisConnectionError
+from redis.exceptions import OutOfMemoryError as RedisOutOfMemoryError
+from redis.exceptions import TimeoutError as RedisTimeoutError
from vcr.persisters.filesystem import CassetteNotFoundError
from vcr.request import Request
from vcr.serializers import yamlserializer
@@ -15,10 +17,14 @@ sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..",
from tests._vcr_redis_persister import ( # noqa: E402
CASSETTE_TTL_SECONDS,
MAX_EPISODES_PER_CASSETTE,
+ VCRCassetteCacheWarning,
+ cassette_cache_capacity_snapshot,
+ cassette_cache_health,
filter_non_2xx_response,
make_redis_persister,
mark_test_outcome_for_cassette,
redis_key_for,
+ reset_cassette_cache_health,
)
@@ -107,23 +113,42 @@ def test_redis_key_is_stable_across_working_directories(tmp_path, monkeypatch):
class _FlakyRedis:
- def __init__(self, inner, fail_on: str):
+ def __init__(self, inner, fail_on: str, exc=None):
self._inner = inner
self._fail_on = fail_on
+ self._exc = exc if exc is not None else RedisConnectionError("simulated outage")
def get(self, *args, **kwargs):
if self._fail_on == "get":
- raise RedisConnectionError("simulated outage")
+ raise self._exc
return self._inner.get(*args, **kwargs)
def set(self, *args, **kwargs):
if self._fail_on == "set":
- raise RedisConnectionError("simulated outage")
+ raise self._exc
return self._inner.set(*args, **kwargs)
-def test_save_swallows_connection_errors_so_teardown_does_not_fail():
- flaky = _FlakyRedis(fakeredis.FakeStrictRedis(), fail_on="set")
+ "exc",
+ [
+ RedisConnectionError("simulated outage"),
+ RedisTimeoutError("simulated timeout"),
+ RedisOutOfMemoryError("command not allowed when used memory > 'maxmemory'."),
+ ],
+ ids=["connection_error", "timeout", "out_of_memory"],
+)
+def test_save_swallows_redis_errors_so_teardown_does_not_fail(exc):
+ """Redis-side failures during cassette persistence must never fail
+ the test on teardown.
+
+ Regression: previously the persister only swallowed
+ ConnectionError/TimeoutError, so OutOfMemoryError (raised by Redis
+ Cloud when the cassette cache hit its maxmemory cap) propagated out
+ of vcrpy's autouse fixture and failed otherwise-passing tests on
+ teardown.
+ """
+ flaky = _FlakyRedis(fakeredis.FakeStrictRedis(), fail_on="set", exc=exc)
persister = make_redis_persister(client=flaky)
persister.save_cassette(
@@ -229,8 +254,17 @@ def test_save_proceeds_when_outcome_unknown():
assert fake.get(key) is not None
-def test_load_treats_connection_errors_as_cassette_miss():
- flaky = _FlakyRedis(fakeredis.FakeStrictRedis(), fail_on="get")
+ "exc",
+ [
+ RedisConnectionError("simulated outage"),
+ RedisTimeoutError("simulated timeout"),
+ RedisOutOfMemoryError("command not allowed when used memory > 'maxmemory'."),
+ ],
+ ids=["connection_error", "timeout", "out_of_memory"],
+)
+def test_load_treats_redis_errors_as_cassette_miss(exc):
+ flaky = _FlakyRedis(fakeredis.FakeStrictRedis(), fail_on="get", exc=exc)
persister = make_redis_persister(client=flaky)
with pytest.raises(CassetteNotFoundError):
@@ -266,3 +300,125 @@ def test_only_2xx_responses_are_cached(status_code, expect_dropped):
assert (result is None) == expect_dropped
if not expect_dropped:
assert result is response
+
+
+def reset_health():
+ reset_cassette_cache_health()
+ yield
+ reset_cassette_cache_health()
+
+
+def test_save_failure_increments_health_counter_and_emits_warning(reset_health):
+ flaky = _FlakyRedis(
+ fakeredis.FakeStrictRedis(),
+ fail_on="set",
+ exc=RedisOutOfMemoryError(
+ "command not allowed when used memory > 'maxmemory'."
+ ),
+ )
+ persister = make_redis_persister(client=flaky)
+
+ with pytest.warns(VCRCassetteCacheWarning, match="OutOfMemoryError"):
+ persister.save_cassette(
+ "tests/llm_translation/test_x/test_save_outage",
+ _sample_cassette_dict(),
+ yamlserializer,
+ )
+
+ health = cassette_cache_health()
+ assert health["save_failures"] == 1
+ assert "OutOfMemoryError" in health["save_failure_last_error"]
+ assert health["load_failures"] == 0
+
+
+def test_load_failure_increments_health_counter_and_emits_warning(reset_health):
+ flaky = _FlakyRedis(
+ fakeredis.FakeStrictRedis(),
+ fail_on="get",
+ exc=RedisConnectionError("simulated outage"),
+ )
+ persister = make_redis_persister(client=flaky)
+
+ with pytest.warns(VCRCassetteCacheWarning, match="ConnectionError"):
+ with pytest.raises(CassetteNotFoundError):
+ persister.load_cassette(
+ "tests/llm_translation/test_x/test_load_outage", yamlserializer
+ )
+
+ health = cassette_cache_health()
+ assert health["load_failures"] == 1
+ assert "ConnectionError" in health["load_failure_last_error"]
+ assert health["save_failures"] == 0
+
+
+def test_health_counters_accumulate_across_failures(reset_health):
+ flaky = _FlakyRedis(
+ fakeredis.FakeStrictRedis(),
+ fail_on="set",
+ exc=RedisConnectionError("simulated outage"),
+ )
+ persister = make_redis_persister(client=flaky)
+
+ for i in range(3):
+ with pytest.warns(VCRCassetteCacheWarning):
+ persister.save_cassette(
+ f"tests/llm_translation/test_x/test_outage_{i}",
+ _sample_cassette_dict(),
+ yamlserializer,
+ )
+
+ assert cassette_cache_health()["save_failures"] == 3
+
+
+def test_successful_save_does_not_emit_warning_or_increment_counter(reset_health):
+ _, persister = _persister_with_fake_redis()
+
+ import warnings as _warnings
+
+ with _warnings.catch_warnings():
+ _warnings.simplefilter("error", VCRCassetteCacheWarning)
+ persister.save_cassette(
+ "tests/llm_translation/test_x/test_happy",
+ _sample_cassette_dict(),
+ yamlserializer,
+ )
+
+ assert cassette_cache_health()["save_failures"] == 0
+
+
+class _FakeRedisWithInfo:
+ def __init__(self, used: int, maxmem: int):
+ self._used = used
+ self._maxmem = maxmem
+
+ def info(self, section=None):
+ return {"used_memory": self._used, "maxmemory": self._maxmem}
+
+
+def test_capacity_snapshot_returns_used_max_and_pct():
+ client = _FakeRedisWithInfo(used=900, maxmem=1000)
+ snap = cassette_cache_capacity_snapshot(client=client)
+ assert snap == {
+ "used_memory_bytes": 900,
+ "maxmemory_bytes": 1000,
+ "used_pct": 90.0,
+ }
+
+
+def test_capacity_snapshot_returns_none_when_uncapped():
+ client = _FakeRedisWithInfo(used=900, maxmem=0)
+ assert cassette_cache_capacity_snapshot(client=client) is None
+
+
+def test_capacity_snapshot_returns_none_when_used_unknown():
+ client = _FakeRedisWithInfo(used=0, maxmem=1000)
+ assert cassette_cache_capacity_snapshot(client=client) is None
+
+
+def test_capacity_snapshot_swallows_exceptions():
+ class _Boom:
+ def info(self, section=None):
+ raise RuntimeError("redis offline")
+
+ assert cassette_cache_capacity_snapshot(client=_Boom()) is None
diff --git a/tests/local_testing/conftest.py b/tests/local_testing/conftest.py
index 94d4f135a56..cad27869ad2 100644
--- a/tests/local_testing/conftest.py
+++ b/tests/local_testing/conftest.py
@@ -22,6 +22,72 @@ sys.path.insert(
) # Adds the parent directory to the system path
import litellm
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+# vcrpy and respx both patch the httpx transport — applying both makes one
+# silently win, so respx-using files opt out of the auto-marker.
+_RESPX_CONFLICTING_FILES = frozenset(
+ {
+ "test_router.py",
+ "test_amazing_vertex_completion.py",
+ "test_azure_openai.py",
+ }
+)
+
+# Files where VCR replay breaks the test:
+# - ``test_assistants.py``: polls fresh per-session run IDs that no cassette
+# can match, so every CI run re-records and the suite times out.
+# - ``test_router_caching.py``: asserts upstream returns a *new* id per call,
+# which a deterministic cassette replay violates.
+_VCR_INCOMPATIBLE_FILES = frozenset(
+ {
+ "test_assistants.py",
+ "test_router_caching.py",
+ }
+)
+
+_VCR_INCOMPATIBLE_NODEID_SUFFIXES: tuple[str, ...] = ()
+
+
+_verbose_state = VerboseReporterState()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
# ---------------------------------------------------------------------------
# Capture TRUE defaults at conftest import time. This runs before any test
# module's top-level code (e.g. `litellm.num_retries = 3`) executes, so
@@ -147,6 +213,12 @@ def setup_and_teardown():
def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(
+ items,
+ skip_files=_RESPX_CONFLICTING_FILES | _VCR_INCOMPATIBLE_FILES,
+ skip_nodeid_suffixes=_VCR_INCOMPATIBLE_NODEID_SUFFIXES,
+ )
+
# Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
custom_logger_tests = [
item for item in items if "custom_logger" in item.parent.name
diff --git a/tests/logging_callback_tests/conftest.py b/tests/logging_callback_tests/conftest.py
index 7100c8456a9..4f847d93a52 100644
--- a/tests/logging_callback_tests/conftest.py
+++ b/tests/logging_callback_tests/conftest.py
@@ -19,6 +19,67 @@ sys.path.insert(
) # Adds the parent directory to the system path
import litellm
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+# vcrpy and respx both patch the httpx transport — applying both makes one
+# silently win, so respx-using files opt out of the auto-marker.
+_RESPX_CONFLICTING_FILES = frozenset(
+ {
+ "test_assemble_streaming_responses.py",
+ "test_langfuse_unit_tests.py",
+ }
+)
+
+# Files where VCR replay breaks the test:
+# - ``test_amazing_s3_logs.py``: vcrpy's boto3 stub intercepts a real S3
+# PUT/LIST round-trip the test asserts on, so the per-run id is never found.
+_VCR_INCOMPATIBLE_FILES = frozenset(
+ {
+ "test_amazing_s3_logs.py",
+ }
+)
+
+_VCR_INCOMPATIBLE_NODEID_SUFFIXES: tuple[str, ...] = ()
+
+
+_verbose_state = VerboseReporterState()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
_LIST_ATTRS = (
"callbacks",
@@ -137,6 +198,12 @@ def setup_and_teardown():
def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(
+ items,
+ skip_files=_RESPX_CONFLICTING_FILES | _VCR_INCOMPATIBLE_FILES,
+ skip_nodeid_suffixes=_VCR_INCOMPATIBLE_NODEID_SUFFIXES,
+ )
+
# Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
custom_logger_tests = [
item for item in items if "custom_logger" in item.parent.name
diff --git a/tests/ocr_tests/conftest.py b/tests/ocr_tests/conftest.py
new file mode 100644
index 00000000000..db48e2db2a5
--- /dev/null
+++ b/tests/ocr_tests/conftest.py
@@ -0,0 +1,57 @@
+# conftest.py
+#
+# Wires OCR tests into the Redis-backed VCR cache so live provider
+# calls (Mistral OCR, Azure AI OCR, Azure Document Intelligence,
+# Vertex AI OCR) are replayed for 24h. See tests/llm_translation/Readme.md
+# for the design overview.
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../.."))
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
+def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
diff --git a/tests/pass_through_unit_tests/conftest.py b/tests/pass_through_unit_tests/conftest.py
new file mode 100644
index 00000000000..d07057a4b63
--- /dev/null
+++ b/tests/pass_through_unit_tests/conftest.py
@@ -0,0 +1,50 @@
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../.."))
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
+def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
diff --git a/tests/router_unit_tests/conftest.py b/tests/router_unit_tests/conftest.py
index 6e331d3a4c0..a210244b3df 100644
--- a/tests/router_unit_tests/conftest.py
+++ b/tests/router_unit_tests/conftest.py
@@ -1,5 +1,6 @@
# conftest.py
+import asyncio
import importlib
import os
import sys
@@ -9,9 +10,17 @@ import pytest
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
-import litellm
+import litellm # noqa: E402,F401
-import asyncio
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
@pytest.fixture(scope="session")
@@ -29,14 +38,11 @@ def setup_and_teardown():
"""
This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
"""
- curr_dir = os.getcwd() # Get the current working directory
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the project directory to the system path
import litellm
- from litellm import Router
- import asyncio
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
@@ -53,12 +59,9 @@ def setup_and_teardown():
except Exception as e:
print(f"Error reloading litellm.proxy.proxy_server: {e}")
- import asyncio
-
loop = asyncio.get_event_loop_policy().new_event_loop()
asyncio.set_event_loop(loop)
print(litellm)
- # from litellm import Router, completion, aembedding, acompletion, embedding
yield
# Teardown code (executes after the yield point)
@@ -66,7 +69,39 @@ def setup_and_teardown():
asyncio.set_event_loop(None) # Remove the reference to the loop
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
+
# Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
custom_logger_tests = [
item for item in items if "custom_logger" in item.parent.name
diff --git a/tests/search_tests/conftest.py b/tests/search_tests/conftest.py
new file mode 100644
index 00000000000..3b4623c53a5
--- /dev/null
+++ b/tests/search_tests/conftest.py
@@ -0,0 +1,58 @@
+# conftest.py
+#
+# Wires search tests into the Redis-backed VCR cache so live provider
+# calls (Brave, DataForSEO, DuckDuckGo, Exa, Firecrawl, Google PSE,
+# Linkup, Parallel.ai, Perplexity, SearchAPI, Searxng, Serper, Tavily)
+# are replayed for 24h. See tests/llm_translation/Readme.md for the
+# design overview.
+
+import os
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.abspath("../.."))
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
+
+
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
+def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
diff --git a/tests/test_litellm/test_vcr_safe_body_matcher.py b/tests/test_litellm/test_vcr_safe_body_matcher.py
new file mode 100644
index 00000000000..0ed6ad69e3c
--- /dev/null
+++ b/tests/test_litellm/test_vcr_safe_body_matcher.py
@@ -0,0 +1,168 @@
+from __future__ import annotations
+
+import os
+import sys
+from types import SimpleNamespace
+
+import pytest
+
+_REPO_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
+if _REPO_ROOT not in sys.path:
+ sys.path.insert(0, _REPO_ROOT)
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ KEY_FINGERPRINT_HEADER,
+ KEY_FINGERPRINT_MATCHER_NAME,
+ SAFE_BODY_MATCHER_NAME,
+ _before_record_request,
+ _key_fingerprint_matcher,
+ _safe_body_matcher,
+ vcr_config_dict,
+)
+
+
+def _req(body):
+ return SimpleNamespace(body=body, headers={"Content-Type": "application/json"})
+
+
+def _req_with_headers(headers, body=b""):
+ return SimpleNamespace(headers=dict(headers), body=body)
+
+
+def test_safe_body_matcher_is_in_match_on():
+ cfg = vcr_config_dict()
+ assert SAFE_BODY_MATCHER_NAME in cfg["match_on"]
+ assert "body" not in cfg["match_on"]
+
+
+def test_safe_body_matcher_accepts_identical_bytes():
+ _safe_body_matcher(_req(b"hello"), _req(b"hello"))
+
+
+def test_safe_body_matcher_accepts_str_bytes_equivalent():
+ _safe_body_matcher(_req("hello"), _req(b"hello"))
+
+
+def test_safe_body_matcher_handles_jsonl_without_crashing():
+ jsonl = (
+ b'{"recordId": "request-1", "modelInput": {}}\n'
+ b'{"recordId": "request-2", "modelInput": {}}\n'
+ )
+ _safe_body_matcher(_req(jsonl), _req(jsonl))
+
+
+def test_safe_body_matcher_rejects_different_jsonl_bodies():
+ a = b'{"recordId": "request-1"}\n{"recordId": "request-2"}\n'
+ b = b'{"recordId": "request-1"}\n{"recordId": "request-3"}\n'
+ with pytest.raises(AssertionError):
+ _safe_body_matcher(_req(a), _req(b))
+
+
+def test_safe_body_matcher_rejects_different_bytes():
+ with pytest.raises(AssertionError):
+ _safe_body_matcher(_req(b"a"), _req(b"b"))
+
+
+def test_safe_body_matcher_treats_none_bodies_as_equal():
+ _safe_body_matcher(_req(None), _req(None))
+
+
+def test_safe_body_matcher_does_not_normalize_json_key_order():
+ with pytest.raises(AssertionError):
+ _safe_body_matcher(_req(b'{"a":1,"b":2}'), _req(b'{"b":2,"a":1}'))
+
+
+def test_default_vcrpy_body_matcher_crashes_on_jsonl_for_documentation():
+ """Pin the upstream behavior our ``safe_body`` matcher exists to work around."""
+ import json
+
+ from vcr.matchers import body as vcrpy_body # type: ignore
+
+ jsonl = b'{"recordId": "request-1"}\n{"recordId": "request-2"}\n'
+ with pytest.raises(json.JSONDecodeError):
+ vcrpy_body(_req(jsonl), _req(jsonl))
+
+
+def test_key_fingerprint_matcher_is_in_match_on():
+ cfg = vcr_config_dict()
+ assert KEY_FINGERPRINT_MATCHER_NAME in cfg["match_on"]
+
+
+def test_before_record_request_strips_auth_and_adds_fingerprint():
+ req = _req_with_headers(
+ {
+ "Authorization": "Bearer sk-real-key-1234567890",
+ "Content-Type": "application/json",
+ "x-amz-date": "20240115T120000Z",
+ }
+ )
+ out = _before_record_request(req)
+ assert "Authorization" not in out.headers
+ assert "x-amz-date" not in out.headers
+ fp = out.headers.get(KEY_FINGERPRINT_HEADER)
+ assert fp and isinstance(fp, str)
+ assert len(fp) >= 8
+ assert "sk-real" not in fp
+
+
+def test_before_record_request_no_auth_yields_stable_no_key_bucket():
+ a = _before_record_request(_req_with_headers({"Content-Type": "application/json"}))
+ b = _before_record_request(_req_with_headers({}))
+ assert a.headers[KEY_FINGERPRINT_HEADER] == b.headers[KEY_FINGERPRINT_HEADER]
+ _key_fingerprint_matcher(a, b)
+
+
+def test_key_fingerprint_matcher_distinguishes_good_and_bad_keys():
+ good = _before_record_request(
+ _req_with_headers({"Authorization": "Bearer sk-real-good-key"})
+ )
+ bad = _before_record_request(
+ _req_with_headers({"Authorization": "Bearer my-bad-key"})
+ )
+ assert good.headers[KEY_FINGERPRINT_HEADER] != bad.headers[KEY_FINGERPRINT_HEADER]
+ with pytest.raises(AssertionError):
+ _key_fingerprint_matcher(good, bad)
+
+
+def test_key_fingerprint_matcher_matches_repeated_good_key_calls():
+ a = _before_record_request(
+ _req_with_headers({"Authorization": "Bearer sk-same-key"})
+ )
+ b = _before_record_request(
+ _req_with_headers({"Authorization": "Bearer sk-same-key"})
+ )
+ _key_fingerprint_matcher(a, b)
+
+
+def test_key_fingerprint_matcher_distinguishes_x_api_key_callers():
+ a = _before_record_request(_req_with_headers({"x-api-key": "anthropic-real"}))
+ b = _before_record_request(_req_with_headers({"x-api-key": "anthropic-bad"}))
+ with pytest.raises(AssertionError):
+ _key_fingerprint_matcher(a, b)
+
+
+def test_before_record_request_is_deterministic_across_distinct_requests():
+ payload = {"Authorization": "Bearer sk-deterministic"}
+ first = _before_record_request(_req_with_headers(payload))
+ second = _before_record_request(_req_with_headers(payload))
+ assert (
+ first.headers[KEY_FINGERPRINT_HEADER] == second.headers[KEY_FINGERPRINT_HEADER]
+ )
+
+
+def test_before_record_request_is_idempotent_on_the_same_request_object():
+ """vcrpy invokes ``before_record_request`` more than once per request.
+
+ ``can_play_response_for`` calls it, then ``__contains__`` /
+ ``_responses`` call it again on the result. The second call sees a
+ request whose auth headers are already gone, so a naive recompute
+ would produce ``"no-key"`` and the matcher would consider the
+ request distinct from anything it just stored — manifesting in CI as
+ ``UnhandledHTTPRequestError`` from ``play_response``.
+ """
+ req = _req_with_headers({"Authorization": "Bearer sk-someone"})
+ _before_record_request(req)
+ fp_after_first = req.headers[KEY_FINGERPRINT_HEADER]
+ _before_record_request(req)
+ assert req.headers[KEY_FINGERPRINT_HEADER] == fp_after_first
+ assert fp_after_first != "no-key"
diff --git a/tests/unified_google_tests/conftest.py b/tests/unified_google_tests/conftest.py
index 01d5f69974e..bae5769ad3c 100644
--- a/tests/unified_google_tests/conftest.py
+++ b/tests/unified_google_tests/conftest.py
@@ -1,5 +1,6 @@
# conftest.py
+import asyncio
import importlib
import os
import sys
@@ -9,8 +10,17 @@ import pytest
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
-import litellm
-import asyncio
+import litellm # noqa: E402,F401
+
+from tests._vcr_conftest_common import ( # noqa: E402
+ VerboseReporterState,
+ apply_vcr_auto_marker_to_items,
+ record_vcr_outcome,
+ register_persister_if_enabled,
+ vcr_config_dict,
+)
+
+_verbose_state = VerboseReporterState()
@pytest.fixture(scope="session")
@@ -28,21 +38,17 @@ def setup_and_teardown():
"""
This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
"""
- curr_dir = os.getcwd() # Get the current working directory
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the project directory to the system path
import litellm
- from litellm import Router
importlib.reload(litellm)
- import asyncio
loop = asyncio.get_event_loop_policy().new_event_loop()
asyncio.set_event_loop(loop)
print(litellm)
- # from litellm import Router, completion, aembedding, acompletion, embedding
yield
# Teardown code (executes after the yield point)
@@ -50,7 +56,39 @@ def setup_and_teardown():
asyncio.set_event_loop(None) # Remove the reference to the loop
[email protected](scope="module")
+def vcr_config():
+ return vcr_config_dict()
+
+
+def pytest_recording_configure(config, vcr):
+ register_persister_if_enabled(vcr)
+
+
[email protected](hookwrapper=True)
+def pytest_runtest_makereport(item, call):
+ outcome = yield
+ rep = outcome.get_result()
+ setattr(item, f"rep_{rep.when}", rep)
+
+
[email protected](autouse=True)
+def _vcr_outcome_gate(request, vcr):
+ yield
+ record_vcr_outcome(request, vcr)
+
+
+def pytest_configure(config):
+ _verbose_state.remember_pluginmanager(config)
+
+
+def pytest_runtest_logreport(report):
+ _verbose_state.maybe_emit_verdict(report)
+
+
def pytest_collection_modifyitems(config, items):
+ apply_vcr_auto_marker_to_items(items)
+
# Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
custom_logger_tests = [
item for item in items if "custom_logger" in item.parent.name