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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix mapped tests (#12320)
Ishaan Jaff39955129f5bc
diff --git a/.circleci/config.yml b/.circleci/config.ymlindex 52c2115bf5f..527b6467be3 100644--- a/.circleci/config.yml+++ b/.circleci/config.yml@@ -950,14 +950,14 @@ jobs:command: |pwdls- python -m pytest -vv tests/test_litellm --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit-litellm.xml --durations=10 -n 4+ python -m pytest -vv tests/test_litellm --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit-litellm.xml --durations=10 -n 8no_output_timeout: 120m- run:name: Run enterprise testscommand: |pwdls- python -m pytest -vv tests/enterprise --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit-enterprise.xml --durations=10 -n 4+ python -m pytest -vv tests/enterprise --cov=litellm --cov-report=xml -x -s -v --junitxml=test-results/junit-enterprise.xml --durations=10 -n 8no_output_timeout: 120m- run:name: Rename the coverage filesdiff --git a/litellm/_logging.py b/litellm/_logging.pyindex c0ab6615eaa..356bb3dcaf7 100644--- a/litellm/_logging.py+++ b/litellm/_logging.py@@ -160,11 +160,6 @@ def _enable_debugging():verbose_proxy_logger.disabled = False-# If JSON logging is enabled, properly initialize all loggers-if json_logs:- _initialize_loggers_with_handler(handler)--def print_verbose(print_statement):try:if set_verbose:diff --git a/tests/test_litellm/conftest.py b/tests/test_litellm/conftest.pyindex b3561d8a626..a88148f9d11 100644--- a/tests/test_litellm/conftest.py+++ b/tests/test_litellm/conftest.py@@ -35,6 +35,8 @@ def setup_and_teardown():except Exception as e:print(f"Error reloading litellm.proxy.proxy_server: {e}")+ litellm.in_memory_llm_clients_cache.flush_cache()+import asyncioloop = asyncio.get_event_loop_policy().new_event_loop()diff --git a/tests/test_litellm/litellm_core_utils/test_json_logs_initialization.py b/tests/test_litellm/litellm_core_utils/test_json_logs_initialization.pydeleted file mode 100644index 00c6e6baa4f..00000000000--- a/tests/test_litellm/litellm_core_utils/test_json_logs_initialization.py+++ /dev/null@@ -1,172 +0,0 @@-"""-Unit tests for JSON logging initialization.-Tests that all loggers are properly configured when JSON_LOGS=True.-"""--import json-import logging-import os-import sys-from io import StringIO-from unittest import mock--import pytest---def test_json_logs_initialization():- """Test that all loggers are properly configured when JSON_LOGS=True"""- # Reset modules to ensure clean import- for module in list(sys.modules.keys()):- if module.startswith("litellm"):- del sys.modules[module]-- # Set environment variable before import- with mock.patch.dict(os.environ, {"JSON_LOGS": "True", "LITELLM_LOG": "DEBUG"}):- # Import litellm with JSON_LOGS enabled- import litellm- from litellm._logging import (- ALL_LOGGERS,- json_logs,- verbose_logger,- verbose_proxy_logger,- verbose_router_logger,- )-- # Verify json_logs is enabled- assert json_logs is True- assert litellm.json_logs is True-- # Check that all loggers have handlers with JsonFormatter- for logger in ALL_LOGGERS:- assert len(logger.handlers) > 0, f"Logger {logger.name} has no handlers"- assert logger.propagate is False, f"Logger {logger.name} should not propagate"-- # Check that at least one handler has JsonFormatter- has_json_formatter = False- for handler in logger.handlers:- if handler.formatter and handler.formatter.__class__.__name__ == "JsonFormatter":- has_json_formatter = True- break- assert has_json_formatter, f"Logger {logger.name} does not have JsonFormatter"---def test_json_logs_output_format():- """Test that log output is valid JSON when JSON_LOGS=True"""- # Reset modules- for module in list(sys.modules.keys()):- if module.startswith("litellm"):- del sys.modules[module]-- with mock.patch.dict(os.environ, {"JSON_LOGS": "True", "LITELLM_LOG": "ERROR"}):- # Capture stderr- captured_output = StringIO()-- with mock.patch("sys.stderr", captured_output):- # Import and use litellm- import litellm- from litellm._logging import verbose_logger-- # Log an error- verbose_logger.error("Test error message")-- # Log with exception- try:- raise ValueError("Test exception")- except Exception:- verbose_logger.error("Error with exception", exc_info=True)-- # Get output- output = captured_output.getvalue()- lines = output.strip().split("\n")-- # Verify each line is valid JSON- assert len(lines) >= 2, "Should have at least 2 log lines"-- for line in lines:- if line: # Skip empty lines- # Parse JSON- data = json.loads(line)-- # Check required fields- assert "message" in data- assert "level" in data- assert "timestamp" in data- assert data["level"] == "ERROR"-- # Check optional stacktrace field- if "Error with exception" in data["message"]:- assert "stacktrace" in data- assert "ValueError: Test exception" in data["stacktrace"]---def test_root_logger_configured():- """Test that the root logger is configured for JSON logging"""- # Reset modules- for module in list(sys.modules.keys()):- if module.startswith("litellm"):- del sys.modules[module]-- with mock.patch.dict(os.environ, {"JSON_LOGS": "True", "LITELLM_LOG": "ERROR"}):- # Capture stderr- captured_output = StringIO()-- with mock.patch("sys.stderr", captured_output):- # Import litellm- import litellm-- # Use root logger- root_logger = logging.getLogger()- root_logger.error("Root logger error")-- # Use a custom module logger (inherits from root)- custom_logger = logging.getLogger("my.custom.module")- custom_logger.error("Custom module error")-- # Get output- output = captured_output.getvalue()- lines = output.strip().split("\n")-- # Verify we got JSON output from both loggers- messages = []- for line in lines:- if line:- data = json.loads(line)- messages.append(data["message"])-- assert "Root logger error" in messages- assert "Custom module error" in messages---def test_json_logs_disabled():- """Test that JSON logging is not used when JSON_LOGS is not set"""- # Reset modules- for module in list(sys.modules.keys()):- if module.startswith("litellm"):- del sys.modules[module]-- # Ensure JSON_LOGS is not set- env = os.environ.copy()- env.pop("JSON_LOGS", None)-- with mock.patch.dict(os.environ, env, clear=True):- # Import litellm- import litellm- from litellm._logging import json_logs, verbose_logger-- # Verify json_logs is disabled- assert json_logs is False-- # Capture output- captured_output = StringIO()- with mock.patch("sys.stderr", captured_output):- verbose_logger.error("Test error without JSON")-- output = captured_output.getvalue().strip()-- # Output should not be JSON- if output: # May be empty if logging is disabled- try:- json.loads(output)- pytest.fail("Output should not be valid JSON when JSON_LOGS is disabled")- except json.JSONDecodeError:- pass # Expected\ No newline at end of filediff --git a/tests/test_litellm/llms/azure/response/test_azure_transformation.py b/tests/test_litellm/llms/azure/response/test_azure_transformation.pyindex 8edd87a12fc..de416bcf433 100644--- a/tests/test_litellm/llms/azure/response/test_azure_transformation.py+++ b/tests/test_litellm/llms/azure/response/test_azure_transformation.py@@ -2,6 +2,8 @@ import osimport sysfrom unittest.mock import patch+import pytest+sys.path.insert(0, os.path.abspath("../../../../..")) # Adds the parent directory to the system path@@ -10,6 +12,7 @@ from litellm.llms.azure.responses.transformation import AzureOpenAIResponsesAPICfrom litellm.types.router import GenericLiteLLMParamsdef test_validate_environment_api_key_within_litellm_params():azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()litellm_params = GenericLiteLLMParams(api_key="test-api-key")@@ -22,7 +25,7 @@ def test_validate_environment_api_key_within_litellm_params():assert result == expected-def test_validate_environment_api_key_within_litellm():azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()@@ -36,7 +39,7 @@ def test_validate_environment_api_key_within_litellm():assert result == expected-def test_validate_environment_azure_key_within_litellm():azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()@@ -50,7 +53,7 @@ def test_validate_environment_azure_key_within_litellm():assert result == expected-def test_validate_environment_azure_openai_api_key_within_secret_str():azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()@@ -70,7 +73,7 @@ def test_validate_environment_azure_openai_api_key_within_secret_str():assert result == expected-def test_validate_environment_azure_api_key_within_secret_str():azure_openai_responses_apiconfig = AzureOpenAIResponsesAPIConfig()diff --git a/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py b/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.pyindex db0a69482b2..1ed2266d1f1 100644--- a/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py+++ b/tests/test_litellm/llms/openai/responses/test_openai_responses_transformation.py@@ -147,7 +147,8 @@ class TestOpenAIResponsesAPIConfig:assert result.type == ResponsesAPIStreamEvents.RESPONSE_COMPLETEDassert result.response.id == "resp_123"-++ @pytest.mark.serialdef test_validate_environment(self):"""Test that validate_environment correctly sets the Authorization header"""# Test with provided API keydiff --git a/tests/test_litellm/proxy/test_team_member_update.py b/tests/test_litellm/proxy/test_team_member_update.pyindex 77ca01beeeb..6561ec9e7fd 100644--- a/tests/test_litellm/proxy/test_team_member_update.py+++ b/tests/test_litellm/proxy/test_team_member_update.py@@ -8,7 +8,7 @@ from litellm.proxy.management_endpoints.team_endpoints import team_member_update@pytest.mark.asyncio-async def test_team_member_update_admin_requires_premium(monkeypatch):+async def test_ateam_member_update_admin_requires_premium(monkeypatch):# Arrange: patch prisma_client and premium_usermonkeypatch.setattr(proxy_server, "prisma_client", object())monkeypatch.setattr(proxy_server, "premium_user", False)diff --git a/tests/test_litellm/router_utils/pre_call_checks/test_responses_api_deployment_check.py b/tests/test_litellm/router_utils/pre_call_checks/test_responses_api_deployment_check.pyindex c9dcf1c9573..5db5cb853cd 100644--- a/tests/test_litellm/router_utils/pre_call_checks/test_responses_api_deployment_check.py+++ b/tests/test_litellm/router_utils/pre_call_checks/test_responses_api_deployment_check.py@@ -23,7 +23,7 @@ from litellm.types.utils import StandardLoggingPayload@pytest.mark.asyncio-async def test_responses_api_routing_with_previous_response_id():+async def test_async_responses_api_routing_with_previous_response_id():"""Test that when using a previous_response_id, the request is sent to the same model_id"""@@ -150,7 +150,7 @@ async def test_responses_api_routing_with_previous_response_id():@pytest.mark.asyncio-async def test_routing_without_previous_response_id():+async def test_async_routing_without_previous_response_id():"""Test that normal routing (load balancing) works when no previous_response_id is provided"""@@ -274,7 +274,7 @@ async def test_routing_without_previous_response_id():@pytest.mark.asyncio-async def test_previous_response_id_not_in_cache():+async def test_async_previous_response_id_not_in_cache():"""Test behavior when a previous_response_id is provided but not found in cache"""@@ -382,7 +382,7 @@ async def test_previous_response_id_not_in_cache():@pytest.mark.asyncio-async def test_multiple_response_ids_routing():+async def test_async_multiple_response_ids_routing():"""Test that different response IDs correctly route to their respective original deployments"""