mirror of
https://github.com/BerriAI/litellm.git
synced 2026-09-08 22:21:35 +00:00
* test: drop the cwd-relative sys.path.insert calls from the test suite
TQ003 stands at 1,077 across 1,058 files, and 1,015 of them are the same shape:
sys.path.insert(0, os.path.abspath("../..")) and its deeper siblings. The
argument resolves against the working directory rather than the file, so from
the repo root, where every job runs pytest, it inserts the directory two levels
above the checkout. It has never pointed at litellm. The package is installed
into the environment anyway, which is what actually makes the import work, and
what the rule's message has said all along.
Removing them leaves 1,634 imports of sys and os with no remaining reference,
and those go too, except where another test module imports the name back out of
the file. The rest of TQ003 is 62 call sites that resolve against __file__ or a
variable, which are a different question and are left alone.
Collection is identical either way: 45,871 tests and the same 51 pre-existing
collection errors before and after, and ruff reports no new undefined name.
* test: drop the duplicate imports the sys.path sweep exposed to F811
* test(pre-call-utils): restore the os import the new bedrock tests need
113 lines
3.4 KiB
Python
113 lines
3.4 KiB
Python
# What is this?
|
|
## Unit Tests for guardrails config
|
|
import asyncio
|
|
import inspect
|
|
import time
|
|
import traceback
|
|
from litellm._uuid import uuid
|
|
from datetime import datetime
|
|
|
|
import pytest
|
|
from pydantic import BaseModel
|
|
|
|
import litellm.litellm_core_utils
|
|
import litellm.litellm_core_utils.litellm_logging
|
|
|
|
from typing import Any, List, Literal, Optional, Tuple, Union
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import litellm
|
|
from litellm import Cache, completion, embedding
|
|
from litellm.integrations.custom_logger import CustomLogger
|
|
from litellm.types.utils import LiteLLMCommonStrings
|
|
|
|
|
|
class CustomLoggingIntegration(CustomLogger):
|
|
def __init__(self) -> None:
|
|
super().__init__()
|
|
|
|
def logging_hook(
|
|
self, kwargs: dict, result: Any, call_type: str
|
|
) -> Tuple[dict, Any]:
|
|
input: Optional[Any] = kwargs.get("input", None)
|
|
messages: Optional[List] = kwargs.get("messages", None)
|
|
if call_type == "completion":
|
|
# assume input is of type messages
|
|
if input is not None and isinstance(input, list):
|
|
input[0]["content"] = "Hey, my name is [NAME]."
|
|
if messages is not None and isinstance(messages, List):
|
|
messages[0]["content"] = "Hey, my name is [NAME]."
|
|
|
|
kwargs["input"] = input
|
|
kwargs["messages"] = messages
|
|
return kwargs, result
|
|
|
|
|
|
def test_guardrail_masking_logging_only():
|
|
"""
|
|
Assert response is unmasked.
|
|
|
|
Assert logged response is masked.
|
|
"""
|
|
callback = CustomLoggingIntegration()
|
|
|
|
with patch.object(callback, "log_success_event", new=MagicMock()) as mock_call:
|
|
litellm.callbacks = [callback]
|
|
messages = [{"role": "user", "content": "Hey, my name is Peter."}]
|
|
response = completion(
|
|
model="gpt-5-mini", messages=messages, mock_response="Hi Peter!"
|
|
)
|
|
|
|
assert response.choices[0].message.content == "Hi Peter!" # type: ignore
|
|
|
|
time.sleep(3)
|
|
mock_call.assert_called_once()
|
|
|
|
print(mock_call.call_args.kwargs["kwargs"]["messages"][0]["content"])
|
|
|
|
assert (
|
|
mock_call.call_args.kwargs["kwargs"]["messages"][0]["content"]
|
|
== "Hey, my name is [NAME]."
|
|
)
|
|
|
|
|
|
def test_guardrail_list_of_event_hooks():
|
|
from litellm.integrations.custom_guardrail import CustomGuardrail
|
|
from litellm.types.guardrails import GuardrailEventHooks
|
|
|
|
cg = CustomGuardrail(
|
|
guardrail_name="custom-guard", event_hook=["pre_call", "post_call"]
|
|
)
|
|
|
|
data = {"model": "gpt-5-mini", "metadata": {"guardrails": ["custom-guard"]}}
|
|
assert cg.should_run_guardrail(data=data, event_type=GuardrailEventHooks.pre_call)
|
|
|
|
assert cg.should_run_guardrail(data=data, event_type=GuardrailEventHooks.post_call)
|
|
|
|
assert not cg.should_run_guardrail(
|
|
data=data, event_type=GuardrailEventHooks.during_call
|
|
)
|
|
|
|
|
|
def test_guardrail_info_response():
|
|
from litellm.types.guardrails import (
|
|
GuardrailInfoResponse,
|
|
LitellmParams,
|
|
)
|
|
|
|
guardrail_info = GuardrailInfoResponse(
|
|
guardrail_name="aporia-pre-guard",
|
|
litellm_params=LitellmParams(
|
|
guardrail="aporia",
|
|
mode="pre_call",
|
|
),
|
|
guardrail_info={
|
|
"guardrail_name": "aporia-pre-guard",
|
|
"litellm_params": {
|
|
"guardrail": "aporia",
|
|
"mode": "always_on",
|
|
},
|
|
},
|
|
)
|
|
|
|
assert guardrail_info.litellm_params.default_on == False
|