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
test: catch regressions in the validation lines #44798 added (#47420)
Mateo Wang8b9cd12a8930
diff --git a/tests/unit/containers/test_endpoint_factory.py b/tests/unit/containers/test_endpoint_factory.pyindex 8de0d039afc..cf640f0e281 100644--- a/tests/unit/containers/test_endpoint_factory.py+++ b/tests/unit/containers/test_endpoint_factory.py@@ -1,4 +1,9 @@+import json+from pathlib import Path+from typing import Final+import pytest+from pydantic import ValidationErrorfrom litellm.containers import endpoint_factoryfrom litellm.containers.endpoint_factory import (@@ -52,6 +57,25 @@ class TestEndpointsConfig:assert first["endpoints"] is not second["endpoints"]assert first == second+ @pytest.mark.parametrize("document", ['["only-in-the-file"]', '"only-in-the-file"', "null"])+ def test_a_packaged_file_that_is_not_a_json_object_is_rejected_without_quoting_it(+ self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, document: str+ ):+ (tmp_path / "endpoints.json").write_text(document)+ monkeypatch.setattr(endpoint_factory, "__file__", str(tmp_path / "endpoint_factory.py"))++ with pytest.raises(ValidationError) as rejected:+ _load_endpoints_config()++ assert "only-in-the-file" not in str(rejected.value)++ def test_a_packaged_json_object_is_returned_as_written(self, monkeypatch: pytest.MonkeyPatch, tmp_path: Path):+ document: Final = {"endpoints": [{"name": "list_container_files"}], "schema_version": 2}+ (tmp_path / "endpoints.json").write_text(json.dumps(document))+ monkeypatch.setattr(endpoint_factory, "__file__", str(tmp_path / "endpoint_factory.py"))++ assert _load_endpoints_config() == document+class TestResponseTypeMapping:def test_mapping_resolves_every_named_response_type(self):diff --git a/tests/unit/interactions/test_litellm_responses_bridge.py b/tests/unit/interactions/test_litellm_responses_bridge.pyindex 58f2756e7fb..9330ae44ad8 100644--- a/tests/unit/interactions/test_litellm_responses_bridge.py+++ b/tests/unit/interactions/test_litellm_responses_bridge.py@@ -10,6 +10,7 @@ from datetime import datetimefrom typing import Finalimport pytest+from pydantic import ValidationErrorfrom litellm.interactions.litellm_responses_transformation.transformation import (LiteLLMResponsesInteractionsConfig,@@ -142,3 +143,9 @@ class TestBridgeResponseTransformation:assert interaction.created is not Noneassert datetime.fromisoformat(interaction.created).timestamp() == 1700000000assert interaction.updated == interaction.created++ def test_responses_response_with_a_status_that_is_not_text_is_refused(self):+ reply: Final = _responses_api_response("completed", None).model_copy(update={"status": 7})++ with pytest.raises(ValidationError):+ LiteLLMResponsesInteractionsConfig.transform_responses_response_to_interactions_response(reply, None)diff --git a/tests/unit/litellm_core_utils/test_get_model_cost_map.py b/tests/unit/litellm_core_utils/test_get_model_cost_map.pyindex eca9bbdc170..84e785ac99a 100644--- a/tests/unit/litellm_core_utils/test_get_model_cost_map.py+++ b/tests/unit/litellm_core_utils/test_get_model_cost_map.py@@ -8,12 +8,15 @@ import asyncio, importlib, importlib.resources as importlib_get_model, json, litimport osimport sysimport threading+from pathlib import Pathfrom typing import Finalimport boto3import pytest+from pydantic import ValidationErrorfrom typing_extensions import NotRequired, ReadOnly, TypedDict+from litellm.litellm_core_utils import get_model_cost_map as get_model_cost_map_modulefrom litellm.litellm_core_utils.fallback_generalizations import (get_fallback_generalization_rules,match_capability_generalizations,@@ -1246,3 +1249,16 @@ def test_get_backup_model_cost_map():print("inside backup")content = json.load(f)print("content", content)++[email protected]("backup", [b'["only-in-the-backup"]', b'"only-in-the-backup"', b"null"])+def test_a_bundled_backup_that_is_not_a_json_object_is_rejected_without_quoting_it(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, backup: bytes+):+ (tmp_path / "model_prices_and_context_window_backup.json").write_bytes(backup)+ monkeypatch.setattr(get_model_cost_map_module, "files", lambda _package: tmp_path)++ with pytest.raises(ValidationError) as rejected:+ GetModelCostMap.load_local_model_cost_map_with_revision()++ assert "only-in-the-backup" not in str(rejected.value)diff --git a/tests/unit/llms/bedrock/test_bedrock_common_utils.py b/tests/unit/llms/bedrock/test_bedrock_common_utils.pyindex d5bd7d44223..7bde1805e18 100644--- a/tests/unit/llms/bedrock/test_bedrock_common_utils.py+++ b/tests/unit/llms/bedrock/test_bedrock_common_utils.py@@ -1197,6 +1197,15 @@ def test_get_anthropic_beta_from_headers_reads_a_json_array_header(header_value:assert get_anthropic_beta_from_headers({"anthropic-beta": header_value}) == expected+def test_get_anthropic_beta_from_headers_never_splits_a_json_array_of_numbers_as_text():+ from litellm.llms.bedrock.common_utils import get_anthropic_beta_from_headers++ betas: Final = get_anthropic_beta_from_headers({"anthropic-beta": "[1, 2]"})++ assert all(isinstance(beta, str) for beta in betas)+ assert not any("[" in beta or "]" in beta for beta in betas)++@pytest.fixture()def _vcr_outcome_gate(request, vcr):install_live_call_probe(request, vcr)@@ -2126,3 +2135,18 @@ def test_without_bedrock_native_output_opt_in_turns_the_opt_in_off_and_keeps_theassert turned_off["api_base"] == "https://bedrock.example"assert deployment_model_info(turned_off)["id"] == "deployment-1"assert litellm_params["model_info"] == {"id": "deployment-1"}+++def test_bedrock_response_stream_shape_is_unavailable_when_botocore_describes_the_service_as_a_list():+ import litellm.llms.bedrock.common_utils as mod++ pytest.importorskip("botocore")+ with (+ patch("botocore.loaders.Loader.load_service_model", return_value=["only-in-the-description"]),+ patch.object(mod.verbose_logger, "warning") as warning,+ ):+ shape: Final = mod._load_bedrock_response_stream_shape()++ assert shape is None+ (logged,) = warning.call_args_list+ assert "only-in-the-description" not in logged.args[0] % logged.args[1:]diff --git a/tests/unit/llms/custom_httpx/test_container_handler.py b/tests/unit/llms/custom_httpx/test_container_handler.pyindex 1b09165087a..0393f12564e 100644--- a/tests/unit/llms/custom_httpx/test_container_handler.py+++ b/tests/unit/llms/custom_httpx/test_container_handler.py@@ -1,11 +1,16 @@+import json+from importlib.resources import files+from pathlib import Pathfrom typing import Finalfrom unittest.mock import MagicMockimport httpximport pytest+from pydantic import ValidationErrorimport litellmfrom litellm.llms.base_llm.chat.transformation import BaseLLMException+from litellm.llms.custom_httpx import container_handlerfrom litellm.llms.custom_httpx.container_handler import generic_container_handlerfrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandlerfrom litellm.types.containers.main import DeleteContainerFileResponse@@ -124,3 +129,22 @@ def test_json_endpoint_sends_the_configured_route_and_parses_its_response_model(assert type(response) is DeleteContainerFileResponseassert response.id.endswith("/containers/cntr_real/files/cfile_nonexistent")assert response.deleted is True++[email protected]("missing_key", ["path_params", "query_params"])+def test_an_endpoint_table_without_a_param_list_fails_the_call(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path, missing_key: str+):+ packaged: Final = json.loads(files("litellm.containers").joinpath("endpoints.json").read_text())+ trimmed: Final = {+ "endpoints": [+ {key: value for key, value in entry.items() if key != missing_key} for entry in packaged["endpoints"]+ ]+ }+ (tmp_path / "containers").mkdir()+ (tmp_path / "containers" / "endpoints.json").write_text(json.dumps(trimmed))+ monkeypatch.setattr(container_handler, "__file__", str(tmp_path / "llms" / "custom_httpx" / "container_handler.py"))+ empty_list: Final = {"object": "list", "data": [], "first_id": None, "last_id": None, "has_more": False}++ with pytest.raises(ValidationError):+ _handle("list_container_files", _sync_client(httpx.Response(200, json=empty_list)))diff --git a/tests/unit/llms/gemini/test_gemini_common_utils.py b/tests/unit/llms/gemini/test_gemini_common_utils.pyindex 918a7475eec..196b912752b 100644--- a/tests/unit/llms/gemini/test_gemini_common_utils.py+++ b/tests/unit/llms/gemini/test_gemini_common_utils.py@@ -1,3 +1,4 @@+import contextlibfrom typing import Finalfrom unittest.mock import AsyncMock, patch@@ -8,7 +9,11 @@ from pydantic import JsonValue, TypeAdapterimport litellmfrom litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler-from litellm.llms.gemini.common_utils import GeminiModelInfo, GoogleAIStudioTokenCounter+from litellm.llms.gemini.common_utils import (+ GeminiModelInfo,+ GoogleAIStudioTokenCounter,+ map_openai_image_params_to_gemini,+)from litellm.llms.gemini.count_tokens import handler as gemini_count_tokens_handlerfrom litellm.llms.gemini.count_tokens.handler import GoogleAIStudioTokenCounter as GeminiCountTokensHandler@@ -473,3 +478,22 @@ class TestGoogleAIStudioTokenCounter:# Verify the contents are unchangedassert cleaned_contents == contents_without_function_response+++def _map_image_config(raw_image_config: str) -> dict[str, object]:+ return map_openai_image_params_to_gemini(+ {"imageConfig": raw_image_config},+ "gemini-3.1-flash-image",+ ["imageConfig"],+ parse_image_config_string=True,+ )+++def test_map_openai_image_params_to_gemini_forwards_a_json_object_image_config():+ assert _map_image_config('{"aspectRatio": "1:1"}') == {"imageConfig": {"aspectRatio": "1:1"}}++[email protected]("raw_image_config", ["[1, 2]", '"16:9"', "null"])+def test_map_openai_image_params_to_gemini_drops_or_refuses_a_non_object_image_config(raw_image_config: str):+ with contextlib.suppress(litellm.UnsupportedParamsError):+ assert "imageConfig" not in _map_image_config(raw_image_config)diff --git a/tests/unit/llms/gemini/test_image_usage_transformation.py b/tests/unit/llms/gemini/test_image_usage_transformation.pyindex 54e0668d2d9..f2f1c3d999f 100644--- a/tests/unit/llms/gemini/test_image_usage_transformation.py+++ b/tests/unit/llms/gemini/test_image_usage_transformation.py@@ -1,6 +1,7 @@from typing import Finalimport pytest+from pydantic import ValidationErrorfrom litellm.llms.gemini.image_usage_transformation import transform_gemini_image_usage@@ -45,3 +46,11 @@ def test_transform_gemini_image_usage_reports_image_and_chat_style_counts("completion_tokens_details": expected_output_details,"output_tokens_details": expected_output_details,}++[email protected]("count_field", ["promptTokenCount", "totalTokenCount"])+def test_transform_gemini_image_usage_rejects_a_count_that_is_not_a_number(count_field: str):+ with pytest.raises(ValidationError):+ transform_gemini_image_usage(+ {"promptTokenCount": 35, "candidatesTokenCount": 4, "totalTokenCount": 39, count_field: "many"}+ )