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
litellm_fix_mapped_tests_core: fix test isolation and mock injection issues (#20209)
shin-bot-litellm0c006794f182
diff --git a/tests/otel_tests/test_prometheus.py b/tests/otel_tests/test_prometheus.pyindex dc037f6f621..4030ce56641 100644--- a/tests/otel_tests/test_prometheus.py+++ b/tests/otel_tests/test_prometheus.py@@ -108,7 +108,7 @@ async def test_proxy_failure_metrics():# Check if the failure metric is present and correct - use pattern matching for robustness# Labels are ordered alphabetically by Prometheus: api_key_alias, client_ip, end_user, exception_class,# exception_status, hashed_api_key, model_id, requested_model, route, team, team_alias, user, user_agent, user_email- expected_metric_pattern = 'litellm_proxy_failed_requests_metric_total{api_key_alias="None",client_ip="None",end_user="None",exception_class="Openai.RateLimitError",exception_status="429",hashed_api_key="88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",model_id="None",requested_model="fake-azure-endpoint",route="/chat/completions",team="None",team_alias="None",user="*******_user_id",user_agent="None",user_email="None"}'+ expected_metric_pattern = 'litellm_proxy_failed_requests_metric_total{api_key_alias="None",client_ip="None",end_user="None",exception_class="Openai.RateLimitError",exception_status="429",hashed_api_key="88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",model_id="None",requested_model="fake-azure-endpoint",route="/chat/completions",team="None",team_alias="None",user="default_user_id",user_agent="None",user_email="None"}'# Check if the pattern is in metricsassert any(@@ -118,7 +118,7 @@ async def test_proxy_failure_metrics():# Check total requests metric# Labels are ordered alphabetically: api_key_alias, client_ip, end_user, hashed_api_key, model_id,# requested_model, route, status_code, team, team_alias, user, user_agent, user_email- total_requests_pattern = 'litellm_proxy_total_requests_metric_total{api_key_alias="None",client_ip="None",end_user="None",hashed_api_key="88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",model_id="None",requested_model="fake-azure-endpoint",route="/chat/completions",status_code="429",team="None",team_alias="None",user="*******_user_id",user_agent="None",user_email="None"}'+ total_requests_pattern = 'litellm_proxy_total_requests_metric_total{api_key_alias="None",client_ip="None",end_user="None",hashed_api_key="88dc28d0f030c55ed4ab77ed8faf098196cb1c05df778539800c9f1243fe6b4b",model_id="None",requested_model="fake-azure-endpoint",route="/chat/completions",status_code="429",team="None",team_alias="None",user="default_user_id",user_agent="None",user_email="None"}'assert any(total_requests_pattern in line for line in metrics.split("\n")diff --git a/tests/test_litellm/containers/test_container_api.py b/tests/test_litellm/containers/test_container_api.pyindex ddfe7c9ef14..9dcd9312ef3 100644--- a/tests/test_litellm/containers/test_container_api.py+++ b/tests/test_litellm/containers/test_container_api.py@@ -22,6 +22,7 @@ from litellm.containers.main import (list_containers,retrieve_container,)+from litellm.main import base_llm_http_handlerfrom litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingfrom litellm.llms.openai.containers.transformation import OpenAIContainerConfigfrom litellm.router import Router@@ -63,9 +64,7 @@ class TestContainerAPI:name="Test Container")- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_create_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_create_handler', return_value=mock_response):response = create_container(name="Test Container",custom_llm_provider="openai"@@ -89,9 +88,7 @@ class TestContainerAPI:name="Expiring Container")- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_create_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_create_handler', return_value=mock_response):response = create_container(name="Expiring Container",expires_after={"anchor": "last_active_at", "minutes": 30},@@ -113,9 +110,7 @@ class TestContainerAPI:name="Container with Files")- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_create_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_create_handler', return_value=mock_response):response = create_container(name="Container with Files",file_ids=["file_123", "file_456"],@@ -137,9 +132,7 @@ class TestContainerAPI:name="Async Test Container")- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_create_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_create_handler', return_value=mock_response):response = await acreate_container(name="Async Test Container",custom_llm_provider="openai"@@ -171,9 +164,7 @@ class TestContainerAPI:has_more=False)- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_list_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_list_handler', return_value=mock_response):response = await alist_containers(custom_llm_provider="openai")@@ -208,9 +199,7 @@ class TestContainerAPI:name=container_name)- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_retrieve_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_retrieve_handler', return_value=mock_response) as mock_method:# Act: Call retrieve_containerresponse = retrieve_container(container_id=container_id,@@ -218,8 +207,8 @@ class TestContainerAPI:)# Assert: Verify the handler was called correctly- mock_handler.container_retrieve_handler.assert_called_once()- call_kwargs = mock_handler.container_retrieve_handler.call_args.kwargs+ mock_method.assert_called_once()+ call_kwargs = mock_method.call_args.kwargsassert call_kwargs["container_id"] == container_id# Assert: Verify response structure and content@@ -245,9 +234,7 @@ class TestContainerAPI:name="Async Retrieved Container")- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_retrieve_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_retrieve_handler', return_value=mock_response):response = await aretrieve_container(container_id=container_id,custom_llm_provider="openai"@@ -265,9 +252,7 @@ class TestContainerAPI:deleted=True)- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_delete_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_delete_handler', return_value=mock_response):response = delete_container(container_id=container_id,custom_llm_provider="openai"@@ -288,9 +273,7 @@ class TestContainerAPI:deleted=True)- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_delete_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_delete_handler', return_value=mock_response):response = await adelete_container(container_id=container_id,custom_llm_provider="openai"@@ -302,9 +285,7 @@ class TestContainerAPI:def test_create_container_error_handling(self):"""Test error handling in container creation."""- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_create_handler.side_effect = Exception("API Error")-+ with patch.object(base_llm_http_handler, 'container_create_handler', side_effect=Exception("API Error")):with pytest.raises(Exception):create_container(name="Error Test Container",@@ -313,21 +294,20 @@ class TestContainerAPI:def test_container_provider_config_retrieval(self):"""Test that provider config is retrieved correctly."""+ mock_response = ContainerObject(+ id="cntr_config_test",+ object="container",+ created_at=1747857508,+ status="running",+ expires_after={"anchor": "last_active_at", "minutes": 20},+ last_active_at=1747857508,+ name="Config Test"+ )+with patch('litellm.containers.main.ProviderConfigManager') as mock_config_manager:mock_config_manager.get_provider_container_config.return_value = OpenAIContainerConfig()- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_response = ContainerObject(- id="cntr_config_test",- object="container",- created_at=1747857508,- status="running",- expires_after={"anchor": "last_active_at", "minutes": 20},- last_active_at=1747857508,- name="Config Test"- )- mock_handler.container_create_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_create_handler', return_value=mock_response):response = create_container(name="Config Test",custom_llm_provider="openai"@@ -355,9 +335,7 @@ class TestContainerAPI:name="Test Container")- with patch('litellm.containers.main.base_llm_http_handler') as mock_handler:- mock_handler.container_create_handler.return_value = mock_response-+ with patch.object(base_llm_http_handler, 'container_create_handler', return_value=mock_response):result = await router.acreate_container(name="Test Container",custom_llm_provider="openai"diff --git a/tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_resend_email.py b/tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_resend_email.pyindex 1065a8ed514..b07216921eb 100644--- a/tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_resend_email.py+++ b/tests/test_litellm/enterprise/enterprise_callbacks/send_emails/test_resend_email.py@@ -2,9 +2,7 @@ import osimport sysimport unittest.mock as mock-import httpximport pytest-import respxfrom httpx import Responsesys.path.insert(0, os.path.abspath("../../.."))@@ -38,32 +36,8 @@ def mock_env_vars():yield-def mock_httpx_client():- with mock.patch(- "litellm_enterprise.enterprise_callbacks.send_emails.resend_email.get_async_httpx_client"- ) as mock_client:-- mock_response = mock.Mock(spec=Response)- mock_response.status_code = 200- mock_response.json.return_value = {"id": "test_email_id"}- mock_response.raise_for_status.return_value = None-- mock_async_client = mock.AsyncMock()- mock_async_client.post.return_value = mock_response-- mock_client.return_value = mock_async_client- yield mock_async_client--@pytest.mark.asyncio-async def test_send_email_success(mock_env_vars, mock_httpx_client):- # Block all HTTP requests at network level to prevent real API calls- respx.post("https://api.resend.com/emails").mock(- return_value=httpx.Response(200, json={"id": "test_email_id"})- )-+async def test_send_email_success(mock_env_vars):# Initialize the loggerlogger = ResendEmailLogger()@@ -73,14 +47,27 @@ async def test_send_email_success(mock_env_vars, mock_httpx_client):subject = "Test Subject"html_body = "<p>Test email body</p>"+ # Create mock HTTP client and inject it directly into the logger+ # This ensures the mock is used regardless of any caching/import issues+ mock_response = mock.Mock(spec=Response)+ mock_response.status_code = 200+ mock_response.json.return_value = {"id": "test_email_id"}+ mock_response.raise_for_status.return_value = None++ mock_async_client = mock.AsyncMock()+ mock_async_client.post.return_value = mock_response++ # Directly inject the mock client to bypass any caching+ logger.async_httpx_client = mock_async_client+# Send emailawait logger.send_email(from_email=from_email, to_email=to_email, subject=subject, html_body=html_body)# Verify the HTTP client was called correctly- mock_httpx_client.post.assert_called_once()- call_args = mock_httpx_client.post.call_args+ mock_async_client.post.assert_called_once()+ call_args = mock_async_client.post.call_args# Verify the URLassert call_args[1]["url"] == "https://api.resend.com/emails"@@ -97,13 +84,7 @@ async def test_send_email_success(mock_env_vars, mock_httpx_client):@pytest.mark.asyncio-async def test_send_email_missing_api_key(mock_httpx_client):- # Block all HTTP requests at network level to prevent real API calls- respx.post("https://api.resend.com/emails").mock(- return_value=httpx.Response(200, json={"id": "test_email_id"})- )-+async def test_send_email_missing_api_key():# Remove the API key from environment before initializing loggeroriginal_key = os.environ.pop("RESEND_API_KEY", None)@@ -117,13 +98,18 @@ async def test_send_email_missing_api_key(mock_httpx_client):subject = "Test Subject"html_body = "<p>Test email body</p>"- # Mock the response to avoid making real HTTP requests+ # Create mock HTTP client and inject it directly into the logger+ # This ensures the mock is used regardless of any caching issuesmock_response = mock.Mock(spec=Response)mock_response.raise_for_status.return_value = None-mock_response.status_code = 200mock_response.json.return_value = {"id": "test_email_id"}- mock_httpx_client.post.return_value = mock_response++ mock_async_client = mock.AsyncMock()+ mock_async_client.post.return_value = mock_response++ # Directly inject the mock client to bypass any caching+ logger.async_httpx_client = mock_async_client# Send emailawait logger.send_email(@@ -131,8 +117,8 @@ async def test_send_email_missing_api_key(mock_httpx_client):)# Verify the HTTP client was called with None as the API key- mock_httpx_client.post.assert_called_once()- call_args = mock_httpx_client.post.call_args+ mock_async_client.post.assert_called_once()+ call_args = mock_async_client.post.call_argsassert call_args[1]["headers"] == {"Authorization": "Bearer None"}finally:# Restore the original key if it existed@@ -141,13 +127,7 @@ async def test_send_email_missing_api_key(mock_httpx_client):@pytest.mark.asyncio-async def test_send_email_multiple_recipients(mock_env_vars, mock_httpx_client):- # Block all HTTP requests at network level to prevent real API calls- respx.post("https://api.resend.com/emails").mock(- return_value=httpx.Response(200, json={"id": "test_email_id"})- )-+async def test_send_email_multiple_recipients(mock_env_vars):# Initialize the loggerlogger = ResendEmailLogger()@@ -157,13 +137,17 @@ async def test_send_email_multiple_recipients(mock_env_vars, mock_httpx_client):subject = "Test Subject"html_body = "<p>Test email body</p>"- # Mock the response to avoid making real HTTP requests+ # Create mock HTTP client and inject it directly into the loggermock_response = mock.Mock(spec=Response)- mock_response.raise_for_status.return_value = None-mock_response.status_code = 200mock_response.json.return_value = {"id": "test_email_id"}- mock_httpx_client.post.return_value = mock_response+ mock_response.raise_for_status.return_value = None++ mock_async_client = mock.AsyncMock()+ mock_async_client.post.return_value = mock_response++ # Directly inject the mock client to bypass any caching+ logger.async_httpx_client = mock_async_client# Send emailawait logger.send_email(@@ -171,7 +155,7 @@ async def test_send_email_multiple_recipients(mock_env_vars, mock_httpx_client):)# Verify the HTTP client was called with multiple recipients- mock_httpx_client.post.assert_called_once()- call_args = mock_httpx_client.post.call_args+ mock_async_client.post.assert_called_once()+ call_args = mock_async_client.post.call_argsrequest_body = call_args[1]["json"]assert request_body["to"] == to_emaildiff --git a/tests/test_litellm/google_genai/test_google_genai_handler.py b/tests/test_litellm/google_genai/test_google_genai_handler.pyindex fc120280511..17a6cba2d63 100644--- a/tests/test_litellm/google_genai/test_google_genai_handler.py+++ b/tests/test_litellm/google_genai/test_google_genai_handler.py@@ -183,10 +183,8 @@ def test_stream_transformation_error_sync():"translate_completion_output_params_streaming",return_value=None):- # Mock litellm.completion at the module level where it's imported- # We need to patch it in the handler module, not in litellm itself- with patch("litellm.google_genai.adapters.handler.litellm") as mock_litellm:- mock_litellm.completion.return_value = mock_stream+ # Patch litellm.completion directly to prevent real API calls+ with patch("litellm.completion", return_value=mock_stream):# Call the handler with stream=True and expect a ValueErrorwith pytest.raises(ValueError, match="Failed to transform streaming response"):GenerateContentToCompletionHandler.generate_content_handler(diff --git a/tests/test_litellm/test_main.py b/tests/test_litellm/test_main.pyindex bc630fc5b81..70664827253 100644--- a/tests/test_litellm/test_main.py+++ b/tests/test_litellm/test_main.py@@ -1335,6 +1335,8 @@ def test_anthropic_text_disable_url_suffix_env_var():def test_image_edit_merges_headers_and_extra_headers():+ from litellm.images.main import base_llm_http_handler+combined_headers = {"x-test-header-one": "value-1","x-test-header-two": "value-2",@@ -1351,8 +1353,9 @@ def test_image_edit_merges_headers_and_extra_headers():"litellm.images.main.ProviderConfigManager.get_provider_image_edit_config",return_value=mock_image_edit_config,) as mock_config,- patch(- "litellm.images.main.base_llm_http_handler.image_edit_handler",+ patch.object(+ base_llm_http_handler,+ "image_edit_handler",return_value="ok",) as mock_handler,):diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.pyindex d11fe8d921f..14ba94f47d7 100644--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@ -2282,8 +2282,19 @@ def test_register_model_with_scientific_notation():"""Test that the register_model function can handle scientific notation in the model name."""+ # Use a unique model name to avoid conflicts with other tests+ test_model_name = "test-scientific-notation-model-unique-12345"++ # Clean up any pre-existing entry and clear caches+ if test_model_name in litellm.model_cost:+ del litellm.model_cost[test_model_name]++ # Clear LRU caches that might have stale data+ from litellm.utils import get_model_info, _cached_get_model_info_helper, _invalidate_model_cost_lowercase_map+ _invalidate_model_cost_lowercase_map()+model_cost_dict = {- "my-custom-model": {+ test_model_name: {"max_tokens": 8192,"input_cost_per_token": "3e-07","output_cost_per_token": "6e-07",@@ -2294,12 +2305,17 @@ def test_register_model_with_scientific_notation():litellm.register_model(model_cost_dict)- registered_model = litellm.model_cost["my-custom-model"]+ registered_model = litellm.model_cost[test_model_name]print(registered_model)assert registered_model["input_cost_per_token"] == 3e-07assert registered_model["output_cost_per_token"] == 6e-07assert registered_model["litellm_provider"] == "openai"assert registered_model["mode"] == "chat"++ # Clean up after test+ if test_model_name in litellm.model_cost:+ del litellm.model_cost[test_model_name]+ _invalidate_model_cost_lowercase_map()def test_reasoning_content_preserved_in_text_completion_wrapper():diff --git a/tests/test_litellm/vector_stores/test_vector_store_registry.py b/tests/test_litellm/vector_stores/test_vector_store_registry.pyindex 9fbef21c294..ef8afe31c65 100644--- a/tests/test_litellm/vector_stores/test_vector_store_registry.py+++ b/tests/test_litellm/vector_stores/test_vector_store_registry.py@@ -133,11 +133,10 @@ def test_add_vector_store_to_registry():def test_search_uses_registry_credentials():"""search() should pull credentials from vector_store_registry when available"""- # Block all HTTP requests at the network level to prevent real API calls- respx.route().mock(return_value=httpx.Response(200, json={"object": "list", "data": []}))+ # Import the module to get the actual handler instance+ import litellm.vector_stores.main as vector_stores_mainvector_store = LiteLLM_ManagedVectorStore(vector_store_id="vs1",@@ -168,8 +167,9 @@ def test_search_uses_registry_credentials():) as mock_get_creds, patch("litellm.vector_stores.main.ProviderConfigManager.get_provider_vector_stores_config",return_value=MagicMock(),- ), patch(- "litellm.vector_stores.main.base_llm_http_handler.vector_store_search_handler",+ ), patch.object(+ vector_stores_main.base_llm_http_handler,+ "vector_store_search_handler",return_value=mock_search_response,) as mock_handler:search(vector_store_id="vs1", query="test", litellm_logging_obj=logger)