Skip to content

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]

ci: lint the test tree for undefined names and fix all 30 (#37671)

ryan-crabbe-berri4af59d7c6e38
diff --git a/.github/workflows/test-linting.yml b/.github/workflows/test-linting.yml
index 5a180c13c53..f98077ea2f0 100644
--- a/.github/workflows/test-linting.yml
+++ b/.github/workflows/test-linting.yml
@@ -122,6 +122,11 @@ jobs:
uv run --no-sync ruff check .
cd ..
+ - name: Run Ruff linting (test tree)
+ if: steps.changes.outputs.decision != 'skip'
+ run: |
+ uv run --no-sync ruff check --config ruff-tests.toml tests
+
- name: Check strict-rule budget (delta vs base)
if: steps.changes.outputs.decision != 'skip'
run: |
diff --git a/Makefile b/Makefile
index 5ae2638fbaa..580d663ba53 100644
--- a/Makefile
+++ b/Makefile
@@ -160,6 +160,7 @@ lint-format-check-changed: $(LINT_DEP_INSTALL) $(LINT_DEP_BASE)
# Linting targets
lint-ruff: $(LINT_DEP_INSTALL)
cd litellm && $(UV_RUN) ruff check . && cd ..
+ $(UV_RUN) ruff check --config ruff-tests.toml tests
# faster linter for developing ...
# inspiration from:
diff --git a/ruff-tests.toml b/ruff-tests.toml
new file mode 100644
index 00000000000..c1bdcc755a7
--- /dev/null
+++ b/ruff-tests.toml
@@ -0,0 +1,15 @@
+# Lint config for the test tree, which ruff.toml excludes from `ruff check`.
+#
+# Deliberately one rule. F821 is the cheapest guard against a test that cannot fail:
+# a name that does not exist raises NameError, and a test whose body is wrapped in
+# `except Exception: pass` swallows that NameError and reports green. Widening this
+# select list means ratcheting thousands of pre-existing findings, so new rules go in
+# one at a time, each with its violations already fixed.
+#
+# No target-version here on purpose: it resolves from requires-python (>=3.10), so
+# 3.11-only builtins like BaseExceptionGroup are correctly flagged in a tree that
+# still has to run on 3.10.
+
+line-length = 120
+
+lint.select = ["F821"]
diff --git a/tests/documentation_tests/test_router_settings.py b/tests/documentation_tests/test_router_settings.py
index 290aa283af4..a1b6f1dac1d 100644
--- a/tests/documentation_tests/test_router_settings.py
+++ b/tests/documentation_tests/test_router_settings.py
@@ -61,7 +61,7 @@ try:
documented_keys.update(doc_key_pattern.findall(table_content))
except Exception as e:
raise Exception(
- f"Error reading documentation: {e}, \n repo base - {os.listdir(repo_base)}"
+ f"Error reading documentation: {e}, \n repo base - {os.listdir(_repo_root)}"
)
diff --git a/tests/local_testing/test_completion.py b/tests/local_testing/test_completion.py
index 6f58bb2eb35..01fd35cb42d 100644
--- a/tests/local_testing/test_completion.py
+++ b/tests/local_testing/test_completion.py
@@ -842,6 +842,8 @@ def test_completion_mistral_api_modified_input():
@pytest.mark.skip(reason="this test is flaky")
def test_completion_gpt4_vision():
+ import openai
+
try:
litellm.set_verbose = True
response = completion(
@@ -1820,6 +1822,8 @@ def test_completion_openai_litellm_key():
@pytest.mark.skip(reason="Unresponsive endpoint.[TODO] Rehost this somewhere else")
def test_completion_ollama_hosted():
+ import openai
+
try:
litellm.request_timeout = 20 # give ollama 20 seconds to response
litellm.set_verbose = True
@@ -2057,17 +2061,12 @@ def test_completion_openrouter_reasoning_effort():
def test_completion_hf_model_no_provider():
- try:
- response = completion(
+ with pytest.raises(litellm.BadRequestError, match="LLM Provider NOT provided"):
+ completion(
model="WizardLM/WizardLM-70B-V1.0",
messages=messages,
max_tokens=5,
)
- # Add any assertions here to check the response
- print(response)
- pytest.fail(f"Error occurred: {e}")
- except Exception as e:
- pass
# test_completion_hf_model_no_provider()
@@ -2546,7 +2545,7 @@ def test_completion_replicate_vicuna():
response_str = response["choices"][0]["message"]["content"]
print("RESPONSE STRING\n", response_str)
if type(response_str) != str:
- pytest.fail(f"Error occurred: {e}")
+ pytest.fail(f"Expected a string response, got {type(response_str)}: {response_str}")
except Exception as e:
pytest.fail(f"Error occurred: {e}")
diff --git a/tests/local_testing/test_exceptions.py b/tests/local_testing/test_exceptions.py
index e02d9e21171..8c1df52e28e 100644
--- a/tests/local_testing/test_exceptions.py
+++ b/tests/local_testing/test_exceptions.py
@@ -573,7 +573,7 @@ def test_content_policy_violation_error_streaming():
num_finish_reason += 1
print("finish_reason", chunk["choices"][0].get("finish_reason"))
- pytest.fail(f"Expected to return 400 error In streaming{e}")
+ pytest.fail("Expected a content-policy error in streaming, got a clean stream")
except Exception as e:
pass
diff --git a/tests/local_testing/test_llm_guard.py b/tests/local_testing/test_llm_guard.py
index 78bbd1c0af8..86fa80ee944 100644
--- a/tests/local_testing/test_llm_guard.py
+++ b/tests/local_testing/test_llm_guard.py
@@ -15,6 +15,8 @@ sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
import pytest
+from fastapi import HTTPException
+
import litellm
from litellm_enterprise.enterprise_callbacks.llm_guard import _ENTERPRISE_LLMGuard
from litellm import Router, mock_completion
@@ -128,7 +130,7 @@ async def test_llm_guard_error_raising():
user_api_key_dict = UserAPIKeyAuth(api_key=_api_key)
local_cache = DualCache()
- try:
+ with pytest.raises(HTTPException) as exc_info:
await llm_guard.async_moderation_hook(
data={
"messages": [
@@ -141,9 +143,9 @@ async def test_llm_guard_error_raising():
user_api_key_dict=user_api_key_dict,
call_type="completion",
)
- pytest.fail(f"Should have failed - {str(e)}")
- except Exception as e:
- pass
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == {"error": "Violated content safety policy"}
def test_llm_guard_key_specific_mode():
diff --git a/tests/proxy_e2e_anthropic_messages_tests/test_claude_agent_sdk.py b/tests/proxy_e2e_anthropic_messages_tests/test_claude_agent_sdk.py
index 48eb7d85ec1..c1339ce6280 100644
--- a/tests/proxy_e2e_anthropic_messages_tests/test_claude_agent_sdk.py
+++ b/tests/proxy_e2e_anthropic_messages_tests/test_claude_agent_sdk.py
@@ -148,65 +148,6 @@ async def test_claude_agent_sdk_streaming(
f"Test failed for {model_name} ({model_description}) after {MAX_RETRIES} attempts: {last_error}"
)
- # Test query
- test_query = "Say 'Hello from LiteLLM!' and nothing else."
-
- # Track streaming
- received_chunks = []
- full_response = ""
-
- try:
- async with ClaudeSDKClient(options=options) as client:
- await client.query(test_query)
-
- # Collect streaming response
- async for msg in client.receive_response():
- # Handle different message types
- if hasattr(msg, "type"):
- if msg.type == "content_block_delta":
- # Streaming text delta
- if hasattr(msg, "delta") and hasattr(msg.delta, "text"):
- chunk_text = msg.delta.text
- received_chunks.append(chunk_text)
- full_response += chunk_text
- elif msg.type == "content_block_start":
- # Start of content block
- if hasattr(msg, "content_block") and hasattr(
- msg.content_block, "text"
- ):
- chunk_text = msg.content_block.text
- received_chunks.append(chunk_text)
- full_response += chunk_text
-
- # Fallback to content handling
- if hasattr(msg, "content"):
- for content_block in msg.content:
- if hasattr(content_block, "text"):
- chunk_text = content_block.text
- received_chunks.append(chunk_text)
- full_response += chunk_text
-
- # Assertions
- print(f"\n✅ Received {len(received_chunks)} chunks")
- print(f"📝 Full response: {full_response[:100]}...")
-
- # Verify we got a response
- assert len(full_response) > 0, f"No response received from {model_name}"
-
- # Verify streaming (should have multiple chunks for most responses)
- # Note: Very short responses might come in 1 chunk, so we just verify we got content
- assert len(received_chunks) > 0, f"No chunks received from {model_name}"
-
- # Verify response is non-empty (don't assert on specific LLM content — it's non-deterministic)
- assert (
- len(full_response.strip()) > 0
- ), f"Empty response received from {model_name}"
-
- print(f"✅ Test passed for {model_name}")
-
- except Exception as e:
- pytest.fail(f"Test failed for {model_name} ({model_description}): {str(e)}")
-
if __name__ == "__main__":
# Run tests
diff --git a/tests/proxy_unit_tests/test_custom_callback_input.py b/tests/proxy_unit_tests/test_custom_callback_input.py
index 71a7e94b180..a032b8706bc 100644
--- a/tests/proxy_unit_tests/test_custom_callback_input.py
+++ b/tests/proxy_unit_tests/test_custom_callback_input.py
@@ -2,6 +2,7 @@
## This test asserts the type of data passed into each method of the custom callback handler
import asyncio
import inspect
+import json
import os
import sys
import time
diff --git a/tests/test_end_users.py b/tests/test_end_users.py
index ff3cc4ec94b..bc1fcbb662d 100644
--- a/tests/test_end_users.py
+++ b/tests/test_end_users.py
@@ -14,47 +14,6 @@ from typing import Optional
"""
-async def chat_completion_with_headers(session, key, model="gpt-4"):
- url = "http://0.0.0.0:4000/chat/completions"
- headers = {
- "Authorization": f"Bearer {key}",
- "Content-Type": "application/json",
- }
- data = {
- "model": model,
- "messages": [
- {"role": "system", "content": "You are a helpful assistant."},
- {"role": "user", "content": "Hello!"},
- ],
- }
-
- async with session.post(url, headers=headers, json=data) as response:
- status = response.status
- response_text = await response.text()
-
- print(response_text)
- print()
-
- if status != 200:
- raise Exception(f"Request did not return a 200 status code: {status}")
-
- response_header_check(
- response
- ) # calling the function to check response headers
-
- raw_headers = response.raw_headers
- raw_headers_json = {}
-
- for (
- item
- ) in (
- response.raw_headers
- ): # ((b'date', b'Fri, 19 Apr 2024 21:17:29 GMT'), (), )
- raw_headers_json[item[0].decode("utf-8")] = item[1].decode("utf-8")
-
- return raw_headers_json
-
-
async def generate_key(
session,
i,
diff --git a/tests/test_litellm/llms/oci/test_oci_coverage_boost.py b/tests/test_litellm/llms/oci/test_oci_coverage_boost.py
index 0b7afa3775d..7c91ece70b5 100644
--- a/tests/test_litellm/llms/oci/test_oci_coverage_boost.py
+++ b/tests/test_litellm/llms/oci/test_oci_coverage_boost.py
@@ -11,11 +11,16 @@ All tests are self-contained and require no real OCI credentials or network acce
"""
import json
+from typing import TYPE_CHECKING
+
import pytest
from unittest.mock import patch, MagicMock, AsyncMock
import httpx
+if TYPE_CHECKING:
+ from litellm.llms.oci.chat.transformation import OCIStreamWrapper
+
from litellm import ModelResponse
from litellm.llms.oci.chat.cohere import (
_extract_text_content,
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_list_outcomes.py b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_list_outcomes.py
index 64afa52ab55..65e2faee1b2 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_list_outcomes.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_list_outcomes.py
@@ -2,6 +2,11 @@
to exactly one category, wire values never carry upstream prose, and single-upstream HTTP statuses
stay truthful to who failed."""
+import sys
+
+if sys.version_info < (3, 11): # BaseExceptionGroup is a builtin only from 3.11
+ from exceptiongroup import BaseExceptionGroup
+
import httpx
import pytest
from mcp import McpError
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_traversal.py b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_traversal.py
index a12c02339e6..b8bf4da1dc4 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_traversal.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/faults/test_traversal.py
@@ -2,6 +2,11 @@
links win (the ``raise ... from`` cause subtree, then ExceptionGroup members in raise order,
then the incidental ``__context__`` chain last), and adversarial shapes terminate."""
+import sys
+
+if sys.version_info < (3, 11): # BaseExceptionGroup is a builtin only from 3.11
+ from exceptiongroup import BaseExceptionGroup
+
from litellm.proxy._experimental.mcp_server.faults import iter_exception_tree
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
index bdaf1458fb0..34852850de6 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_discoverable_endpoints.py
@@ -4,6 +4,7 @@ import hashlib
import json
import time
from base64 import urlsafe_b64encode
+from typing import TYPE_CHECKING
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -11,6 +12,11 @@ from fastapi import HTTPException
from litellm.types.mcp import MCPAuth
+if TYPE_CHECKING:
+ import httpx
+
+ from litellm.types.mcp_server.mcp_server_manager import MCPServer
+
# Fixture to mock IP address check for all MCP tests
# This prevents tests from failing due to IP-based access control
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_stale_session.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_stale_session.py
index 7bdd3b36763..feab179570b 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_stale_session.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_mcp_stale_session.py
@@ -1411,6 +1411,8 @@ async def _run_passthrough_connect(
):
"""Drive handle_streamable_http_mcp through the preemptive-401 gate and report whether it
challenged (raised) or forwarded to the session manager. Returns (challenged, www_authenticate)."""
+ from fastapi import HTTPException
+
from litellm.proxy._experimental.mcp_server.server import (
handle_streamable_http_mcp,
session_manager_stateless,
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
index 7ba9f463197..d7fb121ef9b 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_rest_endpoints.py
@@ -1,9 +1,13 @@
import asyncio
import json
+import sys
from datetime import datetime
from typing import Any, Dict, Optional
from unittest.mock import AsyncMock, MagicMock
+if sys.version_info < (3, 11): # BaseExceptionGroup is a builtin only from 3.11
+ from exceptiongroup import BaseExceptionGroup
+
import httpx
import pytest
from fastapi import HTTPException
diff --git a/tests/test_litellm/proxy/_experimental/mcp_server/test_semantic_tool_filter.py b/tests/test_litellm/proxy/_experimental/mcp_server/test_semantic_tool_filter.py
index 83e4dcf5677..da7f43c7118 100644
--- a/tests/test_litellm/proxy/_experimental/mcp_server/test_semantic_tool_filter.py
+++ b/tests/test_litellm/proxy/_experimental/mcp_server/test_semantic_tool_filter.py
@@ -12,6 +12,9 @@ from unittest.mock import AsyncMock, Mock, patch
import pytest
+if sys.version_info < (3, 11): # BaseExceptionGroup is a builtin only from 3.11
+ from exceptiongroup import BaseExceptionGroup
+
sys.path.insert(0, os.path.abspath("../.."))
from mcp.types import Tool as MCPTool
diff --git a/tests/test_litellm/proxy/auth/test_auth_checks.py b/tests/test_litellm/proxy/auth/test_auth_checks.py
index 1d1bd9ebf8a..7a3288dec37 100644
--- a/tests/test_litellm/proxy/auth/test_auth_checks.py
+++ b/tests/test_litellm/proxy/auth/test_auth_checks.py
@@ -13,7 +13,7 @@ from datetime import datetime, timedelta, timezone
import httpx
import pytest
-from fastapi import status
+from fastapi import Request, status
import litellm
from litellm.proxy._types import (
@@ -2760,11 +2760,9 @@ async def test_common_checks_metadata_route_keeps_key_tags_out_of_provider_metad
assert "metadata" not in request_body
-def _pass_through_request() -> "Request":
+def _pass_through_request() -> Request:
"""A Request whose FastAPI-resolved endpoint carries the pass-through marker,
i.e. the request was dispatched to a user-defined pass-through handler."""
- from fastapi import Request
-
from litellm.types.passthrough_endpoints.pass_through_endpoints import (
LITELLM_PASS_THROUGH_ENDPOINT_MARKER,
)
@@ -2776,10 +2774,9 @@ def _pass_through_request() -> "Request":
return Request(scope={"type": "http", "headers": [], "endpoint": pass_through_endpoint})
-def _builtin_request() -> "Request":
+def _builtin_request() -> Request:
"""A Request dispatched to a built-in (non-pass-through) handler, e.g. what a
custom path colliding with a core route actually resolves to."""
- from fastapi import Request
def chat_completions():
...
diff --git a/tests/test_litellm/proxy/guardrails/test_pillar_guardrails.py b/tests/test_litellm/proxy/guardrails/test_pillar_guardrails.py
index c977223bfab..48f6b3ba2b9 100644
--- a/tests/test_litellm/proxy/guardrails/test_pillar_guardrails.py
+++ b/tests/test_litellm/proxy/guardrails/test_pillar_guardrails.py
@@ -9,7 +9,7 @@ and following LiteLLM testing patterns and best practices.
import importlib
import os
import sys
-from typing import Dict
+from typing import Any, Dict
from unittest.mock import Mock, patch
# Add parent directory to path for imports
diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.py
index 355c6d27eb2..510fb977a61 100644
--- a/tests/test_litellm/proxy/test_common_request_processing.py
+++ b/tests/test_litellm/proxy/test_common_request_processing.py
@@ -3,7 +3,7 @@ import copy
import datetime
import json
from types import SimpleNamespace
-from typing import AsyncGenerator, Callable, Optional
+from typing import AsyncGenerator, Callable, Final, Optional
from unittest.mock import AsyncMock, MagicMock, patch
import httpx