litellm/tests/unit/proxy/guardrails/test_guardrail_load_balancing.py
devin-ai-integration[bot] 1dbde0845e
test: migrate SDK and proxy-booting legacy CircleCI tests to their tiers (#45758)
* test: move guardrails, image, audio, batches, search legacy tests to unit

* test: restore the custom guardrail and remaining chunk 1 unit rows

* test: move the ocr matrix to e2e

* test: drop comments from moved tests and fix vertex ocr credentials

* test: move litellm utils and unified google legacy tests to their tiers

* test: move logging callback and pass-through unit legacy tests to their tiers

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: move store_model_in_db legacy tests and start the admin ui migration

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* test: finish the proxy job rows and drop their CircleCI jobs

Moves the remaining multi-instance, openai endpoint, otel, pass-through and
top-level proxy tests into tests/integration with scripted upstreams, rewrites
the weak replacements to assert the outbound wire and exact responses, and
removes the build_and_test job group this PR owns from CircleCI

* test: tighten the key generation and error log assertions, rename migrated unit files to their mapped names

* test: shard the pagerduty unit tests and record the rust harness file on the coverage allowlist

* test: drive the SSO sign-in tests through a scripted IdP and isolate the cost center stand-in

* test: type the e2e beta header, prompt cache and secret manager values

* test: assert the missing model error message on the OpenAI routes

* test: drop the deleted otel base class import and restore mcp redaction and exact langfuse usage checks

* test: make the langfuse fixture directory a package for the layout check

* test: restore collected no-match cases, real langfuse and gcs payload checks, and gate the aws secret lane

* test: keep the ocr e2e pdf fixture next to the test

* test: put meta below covers on the streaming tool search e2e

* test: run the OCR matrix against a scripted upstream and fix two runner-only e2e failures

* test: count only OCR calls in the OCR matrix recorder

* test: pin OCR parse bodies and billed cost, group new e2e cases into classes

* ci: restore the python image anchor dropped in the main sync

---------

Co-authored-by: yuneng <yuneng@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-10-11 00:17:21 -07:00

94 lines
2.9 KiB
Python

"""
Test guardrail load balancing through the Router and ProxyLogging.
"""
from unittest.mock import MagicMock, patch, AsyncMock
import litellm
import pytest
from litellm import Router
from litellm.caching import DualCache
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.proxy.utils import ProxyLogging
class MockGuardrail(CustomGuardrail):
"""Mock guardrail that tracks calls."""
call_count = 0
def __init__(self, guardrail_name: str, guardrail_id: str):
super().__init__(guardrail_name=guardrail_name)
self.guardrail_id = guardrail_id
self.calls = 0
def should_run_guardrail(self, data, event_type) -> bool:
return True
async def async_pre_call_hook(self, user_api_key_dict, cache, data, call_type):
self.calls += 1
MockGuardrail.call_count += 1
return None
@pytest.mark.asyncio
async def test_proxy_logging_pre_call_hook_load_balancing():
"""Test that async_pre_call_hook load balances across multiple guardrails."""
MockGuardrail.call_count = 0
guardrail_1 = MockGuardrail(guardrail_name="content-filter", guardrail_id="g1")
guardrail_2 = MockGuardrail(guardrail_name="content-filter", guardrail_id="g2")
guardrail_list = [
{
"guardrail_name": "content-filter",
"litellm_params": {"guardrail": "custom", "mode": "pre_call"},
"callback": guardrail_1,
"id": "guardrail-1",
},
{
"guardrail_name": "content-filter",
"litellm_params": {"guardrail": "custom", "mode": "pre_call"},
"callback": guardrail_2,
"id": "guardrail-2",
},
]
router = Router(
model_list=[
{
"model_name": "gpt-5.5",
"litellm_params": {"model": "gpt-5.5", "api_key": "fake-key"},
}
],
guardrail_list=guardrail_list,
)
proxy_logging = ProxyLogging(user_api_key_cache=DualCache())
original_callbacks = litellm.callbacks.copy()
litellm.callbacks = [guardrail_1]
try:
with patch("litellm.proxy.proxy_server.llm_router", router):
for _ in range(50):
await proxy_logging.pre_call_hook(
user_api_key_dict=MagicMock(),
data={"messages": [{"role": "user", "content": "test"}]},
call_type="completion",
)
assert guardrail_1.calls > 0, "Guardrail 1 should have been called"
assert guardrail_2.calls > 0, "Guardrail 2 should have been called"
total = guardrail_1.calls + guardrail_2.calls
assert total == 50, f"Expected 50 total calls, got {total}"
min_calls = min(guardrail_1.calls, guardrail_2.calls)
assert (
min_calls >= 10
), f"Expected at least 10 calls to each guardrail, got min={min_calls}"
finally:
litellm.callbacks = original_callbacks