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(audit-logs): let monkeypatch own the audit log and s3 callback globals (#37842)

yuneng-jiang49da936efb8f
diff --git a/tests/test_litellm/proxy/management_helpers/test_audit_log_callbacks.py b/tests/test_litellm/proxy/management_helpers/test_audit_log_callbacks.py
index 2d54d249713..b1d111bf1f9 100644
--- a/tests/test_litellm/proxy/management_helpers/test_audit_log_callbacks.py
+++ b/tests/test_litellm/proxy/management_helpers/test_audit_log_callbacks.py
@@ -25,12 +25,9 @@ from litellm.types.utils import StandardAuditLogPayload
@pytest.fixture(autouse=True)
-def reset_audit_log_callbacks():
- """Reset audit_log_callbacks before and after each test."""
- original = litellm.audit_log_callbacks
- litellm.audit_log_callbacks = []
- yield
- litellm.audit_log_callbacks = original
+def reset_audit_log_callbacks(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Every test starts with no audit log callbacks registered."""
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [])
def _make_audit_log(
@@ -115,10 +112,10 @@ class TestBuildAuditLogPayload:
class TestDispatchAuditLogToCallbacks:
@pytest.mark.asyncio
- async def test_dispatches_to_custom_logger_instance(self):
+ async def test_dispatches_to_custom_logger_instance(self, monkeypatch: pytest.MonkeyPatch):
mock_logger = MagicMock(spec=CustomLogger)
mock_logger.async_log_audit_log_event = AsyncMock()
- litellm.audit_log_callbacks = [mock_logger]
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [mock_logger])
audit_log = _make_audit_log()
await _dispatch_audit_log_to_callbacks(audit_log)
@@ -132,18 +129,18 @@ class TestDispatchAuditLogToCallbacks:
assert payload["action"] == "created"
@pytest.mark.asyncio
- async def test_no_dispatch_when_callbacks_empty(self):
- litellm.audit_log_callbacks = []
+ async def test_no_dispatch_when_callbacks_empty(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [])
audit_log = _make_audit_log()
# Should return immediately without error
await _dispatch_audit_log_to_callbacks(audit_log)
@pytest.mark.asyncio
- async def test_resolves_string_callback(self):
+ async def test_resolves_string_callback(self, monkeypatch: pytest.MonkeyPatch):
mock_logger = MagicMock(spec=CustomLogger)
mock_logger.async_log_audit_log_event = AsyncMock()
- litellm.audit_log_callbacks = ["s3_v2"]
+ monkeypatch.setattr(litellm, "audit_log_callbacks", ["s3_v2"])
with patch(
"litellm.proxy.management_helpers.audit_logs._resolve_audit_log_callback",
@@ -156,13 +153,13 @@ class TestDispatchAuditLogToCallbacks:
mock_logger.async_log_audit_log_event.assert_called_once()
@pytest.mark.asyncio
- async def test_nonblocking_on_callback_failure(self):
+ async def test_nonblocking_on_callback_failure(self, monkeypatch: pytest.MonkeyPatch):
"""Callback errors should not propagate."""
mock_logger = MagicMock(spec=CustomLogger)
mock_logger.async_log_audit_log_event = AsyncMock(
side_effect=RuntimeError("boom")
)
- litellm.audit_log_callbacks = [mock_logger]
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [mock_logger])
audit_log = _make_audit_log()
# Should not raise
@@ -170,8 +167,8 @@ class TestDispatchAuditLogToCallbacks:
await asyncio.sleep(0.1)
@pytest.mark.asyncio
- async def test_skips_unresolvable_string_callback(self):
- litellm.audit_log_callbacks = ["nonexistent_callback"]
+ async def test_skips_unresolvable_string_callback(self, monkeypatch: pytest.MonkeyPatch):
+ monkeypatch.setattr(litellm, "audit_log_callbacks", ["nonexistent_callback"])
with patch(
"litellm.proxy.management_helpers.audit_logs._resolve_audit_log_callback",
@@ -184,10 +181,10 @@ class TestDispatchAuditLogToCallbacks:
class TestCreateAuditLogForUpdateWithCallbacks:
@pytest.mark.asyncio
- async def test_dispatches_to_callbacks_after_db_write(self):
+ async def test_dispatches_to_callbacks_after_db_write(self, monkeypatch: pytest.MonkeyPatch):
mock_logger = MagicMock(spec=CustomLogger)
mock_logger.async_log_audit_log_event = AsyncMock()
- litellm.audit_log_callbacks = [mock_logger]
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [mock_logger])
with (
patch("litellm.proxy.proxy_server.premium_user", True),
@@ -206,10 +203,10 @@ class TestCreateAuditLogForUpdateWithCallbacks:
mock_logger.async_log_audit_log_event.assert_called_once()
@pytest.mark.asyncio
- async def test_no_dispatch_when_not_premium(self):
+ async def test_no_dispatch_when_not_premium(self, monkeypatch: pytest.MonkeyPatch):
mock_logger = MagicMock(spec=CustomLogger)
mock_logger.async_log_audit_log_event = AsyncMock()
- litellm.audit_log_callbacks = [mock_logger]
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [mock_logger])
with (
patch("litellm.proxy.proxy_server.premium_user", False),
@@ -224,10 +221,10 @@ class TestCreateAuditLogForUpdateWithCallbacks:
mock_prisma.db.litellm_auditlog.create.assert_not_called()
@pytest.mark.asyncio
- async def test_no_dispatch_when_store_audit_logs_false(self):
+ async def test_no_dispatch_when_store_audit_logs_false(self, monkeypatch: pytest.MonkeyPatch):
mock_logger = MagicMock(spec=CustomLogger)
mock_logger.async_log_audit_log_event = AsyncMock()
- litellm.audit_log_callbacks = [mock_logger]
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [mock_logger])
with patch("litellm.store_audit_logs", False):
audit_log = _make_audit_log()
@@ -237,11 +234,11 @@ class TestCreateAuditLogForUpdateWithCallbacks:
mock_logger.async_log_audit_log_event.assert_not_called()
@pytest.mark.asyncio
- async def test_dispatches_even_when_prisma_client_is_none(self):
+ async def test_dispatches_even_when_prisma_client_is_none(self, monkeypatch: pytest.MonkeyPatch):
"""Callbacks should fire even if DB is unavailable."""
mock_logger = MagicMock(spec=CustomLogger)
mock_logger.async_log_audit_log_event = AsyncMock()
- litellm.audit_log_callbacks = [mock_logger]
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [mock_logger])
with (
patch("litellm.proxy.proxy_server.premium_user", True),
@@ -256,11 +253,11 @@ class TestCreateAuditLogForUpdateWithCallbacks:
mock_logger.async_log_audit_log_event.assert_called_once()
@pytest.mark.asyncio
- async def test_dispatches_even_when_db_write_fails(self):
+ async def test_dispatches_even_when_db_write_fails(self, monkeypatch: pytest.MonkeyPatch):
"""Callbacks should fire even if the DB write raises."""
mock_logger = MagicMock(spec=CustomLogger)
mock_logger.async_log_audit_log_event = AsyncMock()
- litellm.audit_log_callbacks = [mock_logger]
+ monkeypatch.setattr(litellm, "audit_log_callbacks", [mock_logger])
with (
patch("litellm.proxy.proxy_server.premium_user", True),
@@ -384,21 +381,21 @@ class TestS3AuditCallbackParamsDecoupling:
S3Logger instance, distinct from the singleton serving normal logs."""
@pytest.fixture(autouse=True)
- def _isolate_caches_and_globals(self):
+ def _isolate_caches_and_globals(self, monkeypatch: pytest.MonkeyPatch):
from litellm.litellm_core_utils import litellm_logging as ll_logging
from litellm.proxy.management_helpers import audit_logs as ll_audit_logs
- original_s3 = litellm.s3_callback_params
- original_audit = getattr(litellm, "s3_audit_callback_params", None)
+ monkeypatch.setattr(litellm, "s3_callback_params", litellm.s3_callback_params)
+ monkeypatch.setattr(
+ litellm, "s3_audit_callback_params", getattr(litellm, "s3_audit_callback_params", None)
+ )
ll_audit_logs._audit_log_callback_cache.clear()
ll_logging._in_memory_loggers.clear()
yield
- litellm.s3_callback_params = original_s3
- litellm.s3_audit_callback_params = original_audit
ll_audit_logs._audit_log_callback_cache.clear()
ll_logging._in_memory_loggers.clear()
- def test_opt_in_constructs_separate_instance_with_audit_config(self):
+ def test_opt_in_constructs_separate_instance_with_audit_config(self, monkeypatch: pytest.MonkeyPatch):
"""Audit config set → audit resolver returns a fresh S3Logger pointing
at the audit bucket, distinct from the normal-log singleton."""
from litellm.integrations.s3_v2 import S3Logger
@@ -409,8 +406,8 @@ class TestS3AuditCallbackParamsDecoupling:
_resolve_audit_log_callback,
)
- litellm.s3_callback_params = {"s3_bucket_name": "normal-bucket"}
- litellm.s3_audit_callback_params = {"s3_bucket_name": "audit-bucket"}
+ monkeypatch.setattr(litellm, "s3_callback_params", {"s3_bucket_name": "normal-bucket"})
+ monkeypatch.setattr(litellm, "s3_audit_callback_params", {"s3_bucket_name": "audit-bucket"})
with patch("asyncio.create_task"):
audit_instance = _resolve_audit_log_callback("s3_v2")
@@ -426,7 +423,7 @@ class TestS3AuditCallbackParamsDecoupling:
assert audit_instance.s3_bucket_name == "audit-bucket"
assert normal_instance.s3_bucket_name == "normal-bucket"
- def test_opt_out_preserves_singleton_behavior(self):
+ def test_opt_out_preserves_singleton_behavior(self, monkeypatch: pytest.MonkeyPatch):
"""No `s3_audit_callback_params` → audit and normal share the singleton
(existing behavior, regression guard)."""
from litellm.integrations.s3_v2 import S3Logger
@@ -437,8 +434,8 @@ class TestS3AuditCallbackParamsDecoupling:
_resolve_audit_log_callback,
)
- litellm.s3_callback_params = {"s3_bucket_name": "shared-bucket"}
- litellm.s3_audit_callback_params = None
+ monkeypatch.setattr(litellm, "s3_callback_params", {"s3_bucket_name": "shared-bucket"})
+ monkeypatch.setattr(litellm, "s3_audit_callback_params", None)
with patch("asyncio.create_task"):
normal_instance = _init_custom_logger_compatible_class(
@@ -452,7 +449,7 @@ class TestS3AuditCallbackParamsDecoupling:
assert id(audit_instance) == id(normal_instance)
assert audit_instance.s3_bucket_name == "shared-bucket"
- def test_empty_dict_opts_in(self):
+ def test_empty_dict_opts_in(self, monkeypatch: pytest.MonkeyPatch):
"""`s3_audit_callback_params = {}` is opt-in (truthy-by-presence) and
produces a separate instance with no bucket configured (env/IAM-only)."""
from litellm.integrations.s3_v2 import S3Logger
@@ -463,8 +460,8 @@ class TestS3AuditCallbackParamsDecoupling:
_resolve_audit_log_callback,
)
- litellm.s3_callback_params = {"s3_bucket_name": "normal-bucket"}
- litellm.s3_audit_callback_params = {}
+ monkeypatch.setattr(litellm, "s3_callback_params", {"s3_bucket_name": "normal-bucket"})
+ monkeypatch.setattr(litellm, "s3_audit_callback_params", {})
with patch("asyncio.create_task"):
audit_instance = _resolve_audit_log_callback("s3_v2")
@@ -478,7 +475,7 @@ class TestS3AuditCallbackParamsDecoupling:
assert audit_instance.s3_bucket_name is None
assert normal_instance.s3_bucket_name == "normal-bucket"
- def test_reset_audit_log_callback_cache_clears_audit_instance(self):
+ def test_reset_audit_log_callback_cache_clears_audit_instance(self, monkeypatch: pytest.MonkeyPatch):
"""`reset_audit_log_callback_cache()` must drop the cached audit
instance so a config reload picks up the new params."""
from litellm.proxy.management_helpers.audit_logs import (
@@ -487,7 +484,7 @@ class TestS3AuditCallbackParamsDecoupling:
reset_audit_log_callback_cache,
)
- litellm.s3_audit_callback_params = {"s3_bucket_name": "first"}
+ monkeypatch.setattr(litellm, "s3_audit_callback_params", {"s3_bucket_name": "first"})
with patch("asyncio.create_task"):
first = _resolve_audit_log_callback("s3_v2")
assert first is not None and "s3_v2" in _audit_log_callback_cache
@@ -495,7 +492,7 @@ class TestS3AuditCallbackParamsDecoupling:
reset_audit_log_callback_cache()
assert "s3_v2" not in _audit_log_callback_cache
- litellm.s3_audit_callback_params = {"s3_bucket_name": "second"}
+ monkeypatch.setattr(litellm, "s3_audit_callback_params", {"s3_bucket_name": "second"})
second = _resolve_audit_log_callback("s3_v2")
assert second is not None
assert id(second) != id(first)