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]

test: add six ruff rules that catch tests which cannot fail (#37709)

ryan-crabbe-berri21e9632713d3
diff --git a/ruff-tests.toml b/ruff-tests.toml
index c1bdcc755a7..c760a53ed91 100644
--- a/ruff-tests.toml
+++ b/ruff-tests.toml
@@ -1,10 +1,19 @@
# 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.
+# Every rule here catches a test that cannot fail. Rules land one at a time, each
+# with its existing violations already fixed, so this list never needs a budget
+# file or a ratchet.
+#
+# F821 a name that does not exist raises NameError, and a test body wrapped in
+# `except Exception: pass` swallows that NameError and reports green
+# B011 `assert False` inside `try:` raises AssertionError, which the `except
+# Exception` below it catches. `pytest.fail` raises BaseException and escapes
+# PT015 same site as B011, from the pytest ruleset
+# B015 a bare `a == b` statement is evaluated and thrown away; the missing `assert`
+# means the test checks nothing
+# B018 a bare attribute access or literal, usually a call missing its parens
+# PLW0127 `x = x` self-assignment, dead code that reads like a narrowing or a fixup
+# PLR0133 comparison of two constants, e.g. `assert True == True`
#
# 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
@@ -12,4 +21,4 @@
line-length = 120
-lint.select = ["F821"]
+lint.select = ["F821", "B011", "B015", "B018", "PT015", "PLR0133", "PLW0127"]
diff --git a/tests/e2e/quota_management/budgets/budget_client.py b/tests/e2e/quota_management/budgets/budget_client.py
index 5b9253928af..543d5f959e0 100644
--- a/tests/e2e/quota_management/budgets/budget_client.py
+++ b/tests/e2e/quota_management/budgets/budget_client.py
@@ -460,7 +460,7 @@ class BudgetClient:
time.sleep(_TEAM_READY_SLEEP_SECONDS)
continue
break
- assert False, last_body
+ raise AssertionError(last_body)
def update_team_member(
self,
diff --git a/tests/litellm_utils_tests/test_health_check.py b/tests/litellm_utils_tests/test_health_check.py
index de6f7c38fed..654fde90f26 100644
--- a/tests/litellm_utils_tests/test_health_check.py
+++ b/tests/litellm_utils_tests/test_health_check.py
@@ -132,7 +132,7 @@ async def test_azure_img_gen_health_check():
retry_delay *= 2 # Exponential backoff
# Should not reach here, but just in case
- assert False, "Health check failed after all retries"
+ pytest.fail("Health check failed after all retries")
@pytest.mark.skip(reason="AWS Suspended Account")
diff --git a/tests/llm_translation/test_bedrock_completion.py b/tests/llm_translation/test_bedrock_completion.py
index 8dcae7cc997..3303fafafb0 100644
--- a/tests/llm_translation/test_bedrock_completion.py
+++ b/tests/llm_translation/test_bedrock_completion.py
@@ -2442,9 +2442,7 @@ class TestBedrockEmbedding(BaseLLMEmbeddingTest):
transformed_request = (
AmazonTitanMultimodalEmbeddingG1Config()._transform_request(**args)
)
- transformed_request[
- "inputImage"
- ] == "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkBAMAAACCzIhnAAAAG1BMVEURAAD///+ln5/h39/Dv79qX18uHx+If39MPz9oMSdmAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABB0lEQVRYhe2SzWrEIBCAh2A0jxEs4j6GLDS9hqWmV5Flt0cJS+lRwv742DXpEjY1kOZW6HwHFZnPmVEBEARBEARB/jd0KYA/bcUYbPrRLh6amXHJ/K+ypMoyUaGthILzw0l+xI0jsO7ZcmCcm4ILd+QuVYgpHOmDmz6jBeJImdcUCmeBqQpuqRIbVmQsLCrAalrGpfoEqEogqbLTWuXCPCo+Ki1XGqgQ+jVVuhB8bOaHkvmYuzm/b0KYLWwoK58oFqi6XfxQ4Uz7d6WeKpna6ytUs5e8betMcqAv5YPC5EZB2Lm9FIn0/VP6R58+/GEY1X1egVoZ/3bt/EqF6malgSAIgiDIH+QL41409QMY0LMAAAAASUVORK5CYII="
+ assert transformed_request["inputImage"] == "iVBORw0KGgoAAAANSUhEUgAAAGQAAABkBAMAAACCzIhnAAAAG1BMVEURAAD///+ln5/h39/Dv79qX18uHx+If39MPz9oMSdmAAAACXBIWXMAAA7EAAAOxAGVKw4bAAABB0lEQVRYhe2SzWrEIBCAh2A0jxEs4j6GLDS9hqWmV5Flt0cJS+lRwv742DXpEjY1kOZW6HwHFZnPmVEBEARBEARB/jd0KYA/bcUYbPrRLh6amXHJ/K+ypMoyUaGthILzw0l+xI0jsO7ZcmCcm4ILd+QuVYgpHOmDmz6jBeJImdcUCmeBqQpuqRIbVmQsLCrAalrGpfoEqEogqbLTWuXCPCo+Ki1XGqgQ+jVVuhB8bOaHkvmYuzm/b0KYLWwoK58oFqi6XfxQ4Uz7d6WeKpna6ytUs5e8betMcqAv5YPC5EZB2Lm9FIn0/VP6R58+/GEY1X1egVoZ/3bt/EqF6malgSAIgiDIH+QL41409QMY0LMAAAAASUVORK5CYII="
@pytest.mark.asyncio
diff --git a/tests/llm_translation/test_bedrock_embedding.py b/tests/llm_translation/test_bedrock_embedding.py
index 2bc4192833b..e343b8856a7 100644
--- a/tests/llm_translation/test_bedrock_embedding.py
+++ b/tests/llm_translation/test_bedrock_embedding.py
@@ -447,9 +447,7 @@ def test_bedrock_embedding_region_bug_reproduction():
print(
"❌ BUG REPRODUCED: Using wrong region from env var instead of explicit parameter"
)
- assert (
- False
- ), f"Bug reproduced: URL contains ap-northeast-1 instead of us-east-1. URL: {url}"
+ pytest.fail(f"Bug reproduced: URL contains ap-northeast-1 instead of us-east-1. URL: {url}")
else:
print(
"✓ Bug NOT reproduced: Using correct region from explicit parameter"
diff --git a/tests/llm_translation/test_containers_api.py b/tests/llm_translation/test_containers_api.py
index 2ae93a3a406..4e26a883fcb 100644
--- a/tests/llm_translation/test_containers_api.py
+++ b/tests/llm_translation/test_containers_api.py
@@ -70,7 +70,7 @@ def test_container_files_api():
custom_llm_provider="openai",
api_key=api_key,
)
- assert False, "Should have raised error for non-existent file"
+ pytest.fail("Should have raised error for non-existent file")
except Exception as e:
assert "not found" in str(e).lower() or "invalid" in str(e).lower()
print(f" Got expected error ✓")
@@ -84,7 +84,7 @@ def test_container_files_api():
custom_llm_provider="openai",
api_key=api_key,
)
- assert False, "Should have raised error for non-existent file content"
+ pytest.fail("Should have raised error for non-existent file content")
except Exception as e:
print(f" Got expected error ✓")
@@ -97,7 +97,7 @@ def test_container_files_api():
custom_llm_provider="openai",
api_key=api_key,
)
- assert False, "Should have raised error for non-existent file"
+ pytest.fail("Should have raised error for non-existent file")
except Exception as e:
# Delete returns 400 for non-existent files
print(f" Got expected error ✓")
diff --git a/tests/llm_translation/test_gemini.py b/tests/llm_translation/test_gemini.py
index 0a5aebdf91b..9326e291b7f 100644
--- a/tests/llm_translation/test_gemini.py
+++ b/tests/llm_translation/test_gemini.py
@@ -1324,7 +1324,7 @@ def test_gemini_exception_message_format():
extra_kwargs={},
)
# Should not reach here - exception should be raised
- assert False, "Expected BadRequestError to be raised"
+ pytest.fail("Expected BadRequestError to be raised")
except BadRequestError as e:
# The test should FAIL initially (before fix) because it will show VertexAIException
# After the fix, it should show GeminiException
@@ -1401,9 +1401,7 @@ def l(status_code, expected_exception):
completion_kwargs={},
extra_kwargs={},
)
- assert (
- False
- ), f"Expected {expected_exception} to be raised for status {status_code}"
+ pytest.fail(f"Expected {expected_exception} to be raised for status {status_code}")
except Exception as e:
# Verify the correct exception type is raised
exception_classes = {
diff --git a/tests/local_testing/test_completion_cost.py b/tests/local_testing/test_completion_cost.py
index 551b3f064bb..e34d5c349c5 100644
--- a/tests/local_testing/test_completion_cost.py
+++ b/tests/local_testing/test_completion_cost.py
@@ -1097,7 +1097,7 @@ def test_completion_cost_databricks(model):
litellm._turn_on_debug()
os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"
litellm.model_cost = litellm.get_model_cost_map(url="")
- model, messages = model, [{"role": "user", "content": "What is 2+2?"}]
+ messages = [{"role": "user", "content": "What is 2+2?"}]
resp = litellm.completion(model=model, messages=messages) # works fine
@@ -1479,7 +1479,6 @@ def test_completion_cost_azure_ai_rerank(model):
},
)
print("response", response)
- model = model
cost = completion_cost(
model=model, completion_response=response, call_type="arerank"
)
@@ -2874,7 +2873,7 @@ def test_json_valid_model_cost_map():
json_str = json.dumps(model_cost)
json.loads(json_str)
except json.JSONDecodeError as e:
- assert False, f"Invalid JSON format: {str(e)}"
+ pytest.fail(f"Invalid JSON format: {str(e)}")
def test_batch_cost_calculator():
diff --git a/tests/local_testing/test_custom_llm.py b/tests/local_testing/test_custom_llm.py
index ea15c3db9d0..64a6c8b2587 100644
--- a/tests/local_testing/test_custom_llm.py
+++ b/tests/local_testing/test_custom_llm.py
@@ -489,9 +489,9 @@ async def test_image_generation_async_additional_params():
mock_client.assert_awaited_once()
- mock_client.call_args.kwargs["api_key"] == "my-api-key"
- mock_client.call_args.kwargs["api_base"] == "my-api-base"
- mock_client.call_args.kwargs["optional_params"] == {
+ assert mock_client.call_args.kwargs["api_key"] == "my-api-key"
+ assert mock_client.call_args.kwargs["api_base"] == "my-api-base"
+ assert mock_client.call_args.kwargs["optional_params"] == {
"my_custom_param": "my-custom-param"
}
diff --git a/tests/local_testing/test_custom_logger.py b/tests/local_testing/test_custom_logger.py
index 6af2ff7e964..02a9eaaa9e6 100644
--- a/tests/local_testing/test_custom_logger.py
+++ b/tests/local_testing/test_custom_logger.py
@@ -279,7 +279,6 @@ def test_azure_completion_stream():
@pytest.mark.asyncio
async def test_async_custom_handler_completion():
try:
- litellm._turn_on_debug
customHandler_success = MyCustomHandler()
customHandler_failure = MyCustomHandler()
# success
diff --git a/tests/local_testing/test_router_pattern_matching.py b/tests/local_testing/test_router_pattern_matching.py
index d09790d43b1..d02582a2a99 100644
--- a/tests/local_testing/test_router_pattern_matching.py
+++ b/tests/local_testing/test_router_pattern_matching.py
@@ -5,6 +5,7 @@ Pattern matching router is used to match patterns like openai/*, vertex_ai/*, an
"""
import sys, os, time
+import json
import traceback, asyncio
import pytest
@@ -233,11 +234,11 @@ def test_router_pattern_match_e2e():
api_key="test",
)
mock_post.assert_called_once()
- print(mock_post.call_args.kwargs["data"])
- mock_post.call_args.kwargs["data"] == {
- "model": "gpt-4o",
- "messages": [{"role": "user", "content": "Hello, how are you?"}],
- }
+ request_body = json.loads(mock_post.call_args.kwargs["data"])
+ assert request_body["model"] == "my-custom-model"
+ assert request_body["messages"] == [
+ {"role": "user", "content": [{"type": "text", "text": "Hello, how are you?"}]}
+ ]
def test_pattern_matching_router_with_default_wildcard():
diff --git a/tests/local_testing/test_secret_detect_hook.py b/tests/local_testing/test_secret_detect_hook.py
index 57b55bd2689..ad2e248da1b 100644
--- a/tests/local_testing/test_secret_detect_hook.py
+++ b/tests/local_testing/test_secret_detect_hook.py
@@ -137,7 +137,7 @@ async def test_basic_secret_detection_text_completion():
call_type="completion",
)
- test_data == {
+ assert test_data == {
"prompt": "Hey, how's it going, API_KEY = '[REDACTED]', my OPENAI_API_KEY = '[REDACTED]' and i want to know what is the weather",
"model": "gpt-3.5-turbo",
}
diff --git a/tests/logging_callback_tests/test_gcs_pub_sub.py b/tests/logging_callback_tests/test_gcs_pub_sub.py
index c37a2e3f65d..3c242a5fe1d 100644
--- a/tests/logging_callback_tests/test_gcs_pub_sub.py
+++ b/tests/logging_callback_tests/test_gcs_pub_sub.py
@@ -133,7 +133,7 @@ def assert_gcs_pubsub_request_matches_expected(
actual_request_body, expected_request_body, ignore_keys=ignored_keys
)
if differences:
- assert False, f"Dictionary mismatch: {differences}"
+ pytest.fail(f"Dictionary mismatch: {differences}")
def assert_gcs_pubsub_request_matches_expected_standard_logging_payload(
diff --git a/tests/mcp_tests/test_aresponses_api_with_mcp.py b/tests/mcp_tests/test_aresponses_api_with_mcp.py
index 32295310005..6da8ce598a9 100644
--- a/tests/mcp_tests/test_aresponses_api_with_mcp.py
+++ b/tests/mcp_tests/test_aresponses_api_with_mcp.py
@@ -1441,9 +1441,7 @@ async def test_no_duplicate_mcp_tools_in_streaming_e2e():
print(
f"ERROR: Duplicate MCP fetching detected! Called {mock_get_tools.call_count} times"
)
- assert (
- False
- ), f"MCP tools should be fetched exactly once, but were fetched {mock_get_tools.call_count} times"
+ pytest.fail(f"MCP tools should be fetched exactly once, but were fetched {mock_get_tools.call_count} times")
# Additional validation: ensure no duplicate tools in any LLM call
total_duplicates_found = 0
@@ -1466,9 +1464,7 @@ async def test_no_duplicate_mcp_tools_in_streaming_e2e():
)
if total_duplicates_found > 0:
- assert (
- False
- ), f"Found {total_duplicates_found} duplicate tools across all LLM calls"
+ pytest.fail(f"Found {total_duplicates_found} duplicate tools across all LLM calls")
print("No duplicate MCP tools E2E test passed!")
print(f"Summary:")
diff --git a/tests/test_litellm/integrations/gitlab/test_gitlab_integration.py b/tests/test_litellm/integrations/gitlab/test_gitlab_integration.py
index 8a0ae030fff..8118af56b0e 100644
--- a/tests/test_litellm/integrations/gitlab/test_gitlab_integration.py
+++ b/tests/test_litellm/integrations/gitlab/test_gitlab_integration.py
@@ -92,7 +92,7 @@ def test_gitlab_prompt_manager_error_handling_load(mock_client_class):
with pytest.raises(
Exception, match="Failed to load prompt 'gitlab::oops' from GitLab"
):
- GitLabPromptManager(config, prompt_id="oops").prompt_manager
+ _ = GitLabPromptManager(config, prompt_id="oops").prompt_manager
def test_gitlab_prompt_manager_config_validation_via_client_ctor():
@@ -105,7 +105,7 @@ def test_gitlab_prompt_manager_config_validation_via_client_ctor():
side_effect=ValueError("project and access_token are required"),
):
with pytest.raises(ValueError, match="project and access_token are required"):
- GitLabPromptManager({}).prompt_manager
+ _ = GitLabPromptManager({}).prompt_manager
# -----------------------------
diff --git a/tests/test_litellm/litellm_core_utils/test_token_counter.py b/tests/test_litellm/litellm_core_utils/test_token_counter.py
index 71e686563a5..74aa5fa823a 100644
--- a/tests/test_litellm/litellm_core_utils/test_token_counter.py
+++ b/tests/test_litellm/litellm_core_utils/test_token_counter.py
@@ -974,7 +974,7 @@ def test_token_counter_with_image_url():
try:
token_counter(model="gpt-3.5-turbo", messages=messages_invalid)
- assert False, "Expected ValueError for invalid detail value"
+ pytest.fail("Expected ValueError for invalid detail value")
except ValueError as e:
assert "Invalid detail value" in str(
e
diff --git a/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py b/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py
index a3be3ebcfc7..ebc482a44ba 100644
--- a/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py
+++ b/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py
@@ -3011,7 +3011,7 @@ def test_request_metadata_validation():
litellm_params={},
headers={},
)
- assert False, "Should have raised validation error for too many items"
+ pytest.fail("Should have raised validation error for too many items")
except Exception as e:
assert "maximum of 16 items" in str(e).lower()
@@ -3034,7 +3034,7 @@ def test_request_metadata_key_constraints():
litellm_params={},
headers={},
)
- assert False, "Should have raised validation error for key too long"
+ pytest.fail("Should have raised validation error for key too long")
except Exception as e:
assert "key length" in str(e).lower() or "256 characters" in str(e).lower()
@@ -3049,7 +3049,7 @@ def test_request_metadata_key_constraints():
litellm_params={},
headers={},
)
- assert False, "Should have raised validation error for empty key"
+ pytest.fail("Should have raised validation error for empty key")
except Exception as e:
assert "key length" in str(e).lower() or "empty" in str(e).lower()
@@ -3072,7 +3072,7 @@ def test_request_metadata_value_constraints():
litellm_params={},
headers={},
)
- assert False, "Should have raised validation error for value too long"
+ pytest.fail("Should have raised validation error for value too long")
except Exception as e:
assert "value length" in str(e).lower() or "256 characters" in str(e).lower()
diff --git a/tests/test_litellm/llms/openai/responses/test_openai_count_tokens_transformation.py b/tests/test_litellm/llms/openai/responses/test_openai_count_tokens_transformation.py
index a87aaa7435f..bcca35886fe 100644
--- a/tests/test_litellm/llms/openai/responses/test_openai_count_tokens_transformation.py
+++ b/tests/test_litellm/llms/openai/responses/test_openai_count_tokens_transformation.py
@@ -1,6 +1,8 @@
import os
import sys
+import pytest
+
sys.path.insert(
0, os.path.abspath("../../../../..")
) # Adds the parent directory to the system path
@@ -177,7 +179,7 @@ def test_validate_request_missing_model():
config = OpenAICountTokensConfig()
try:
config.validate_request(model="", input="Hello")
- assert False, "Should have raised ValueError"
+ pytest.fail("Should have raised ValueError")
except ValueError as e:
assert "model" in str(e)
@@ -187,7 +189,7 @@ def test_validate_request_missing_input():
config = OpenAICountTokensConfig()
try:
config.validate_request(model="gpt-4o", input="")
- assert False, "Should have raised ValueError"
+ pytest.fail("Should have raised ValueError")
except ValueError as e:
assert "input" in str(e)
diff --git a/tests/test_litellm/llms/openrouter/responses/test_openrouter_responses_transformation.py b/tests/test_litellm/llms/openrouter/responses/test_openrouter_responses_transformation.py
index 62c372a3d93..d279eaeec01 100644
--- a/tests/test_litellm/llms/openrouter/responses/test_openrouter_responses_transformation.py
+++ b/tests/test_litellm/llms/openrouter/responses/test_openrouter_responses_transformation.py
@@ -9,6 +9,8 @@ reasoning.encrypted_content for multi-turn stateless workflows.
Related issue: https://github.com/BerriAI/litellm/issues/22189
"""
+import pytest
+
import litellm
from litellm.llms.openrouter.responses.transformation import (
OpenRouterResponsesAPIConfig,
@@ -76,7 +78,7 @@ class TestOpenRouterResponsesAPIConfig:
model="openai/o4-mini",
litellm_params=GenericLiteLLMParams(),
)
- assert False, "Should have raised ValueError"
+ pytest.fail("Should have raised ValueError")
except ValueError as e:
assert "OpenRouter API key is required" in str(e)
diff --git a/tests/test_litellm/llms/perplexity/embedding/test_perplexity_embedding_transformation.py b/tests/test_litellm/llms/perplexity/embedding/test_perplexity_embedding_transformation.py
index 15ebecdcb1d..89c0ec1988f 100644
--- a/tests/test_litellm/llms/perplexity/embedding/test_perplexity_embedding_transformation.py
+++ b/tests/test_litellm/llms/perplexity/embedding/test_perplexity_embedding_transformation.py
@@ -8,6 +8,7 @@ import struct
from unittest.mock import MagicMock
import httpx
+import pytest
from litellm.llms.perplexity.embedding.transformation import (
PerplexityEmbeddingConfig,
@@ -245,7 +246,7 @@ class TestPerplexityEmbeddingConfig:
model_response=model_response,
logging_obj=self.logging_obj,
)
- assert False, "Should have raised PerplexityEmbeddingError"
+ pytest.fail("Should have raised PerplexityEmbeddingError")
except PerplexityEmbeddingError as e:
assert e.status_code == 500
assert "Server error" in e.message
diff --git a/tests/test_litellm/llms/sagemaker/test_sagemaker_common_utils.py b/tests/test_litellm/llms/sagemaker/test_sagemaker_common_utils.py
index 7e13459bca1..f928964dab8 100644
--- a/tests/test_litellm/llms/sagemaker/test_sagemaker_common_utils.py
+++ b/tests/test_litellm/llms/sagemaker/test_sagemaker_common_utils.py
@@ -87,7 +87,6 @@ def test_sagemaker_response_stream_shape_is_structure_shape():
assert (
shape is not None
), "get_sagemaker_response_stream_shape() is None — botocore may not be installed"
- shape: StructureShape = shape # remove Optional
assert isinstance(shape, StructureShape)
assert shape.name == "InvokeEndpointWithResponseStreamOutput"
diff --git a/tests/test_litellm/passthrough/test_passthrough_main.py b/tests/test_litellm/passthrough/test_passthrough_main.py
index 0b5bfac87bb..58a0185ea8c 100644
--- a/tests/test_litellm/passthrough/test_passthrough_main.py
+++ b/tests/test_litellm/passthrough/test_passthrough_main.py
@@ -43,9 +43,10 @@ def test_llm_passthrough_route():
client=client,
)
- mock_post.call_args.kwargs[
- "request"
- ].url == "http://localhost:8090/v1/chat/completions"
+ assert (
+ mock_post.call_args.kwargs["request"].url
+ == "http://localhost:8090/v1/chat/completions"
+ )
assert response.status_code == 200
assert response.json == {"message": "Hello, world!"}
diff --git a/tests/test_litellm/proxy/db/mcp_server/test_db.py b/tests/test_litellm/proxy/db/mcp_server/test_db.py
index ff6400ac5b7..481d1a864c0 100644
--- a/tests/test_litellm/proxy/db/mcp_server/test_db.py
+++ b/tests/test_litellm/proxy/db/mcp_server/test_db.py
@@ -1,6 +1,7 @@
-import json
import os
import sys
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -11,5 +12,34 @@ sys.path.insert(
from litellm.proxy._experimental.mcp_server.db import get_mcp_servers_by_team
-def test_fetch_mcp_servers_by_team():
- assert True == True
+def _prisma_client_returning(team_record: object) -> MagicMock:
+ prisma_client = MagicMock()
+ prisma_client.db.litellm_teamtable.find_unique = AsyncMock(return_value=team_record)
+ return prisma_client
+
+
+ "team_record, expected",
+ [
+ (None, []),
+ (SimpleNamespace(object_permission=None), []),
+ (SimpleNamespace(object_permission=SimpleNamespace(mcp_servers=None)), []),
+ (SimpleNamespace(object_permission=SimpleNamespace(mcp_servers=[])), []),
+ (
+ SimpleNamespace(
+ object_permission=SimpleNamespace(mcp_servers=["server_a", "server_b"])
+ ),
+ ["server_a", "server_b"],
+ ),
+ ],
+)
+async def test_fetch_mcp_servers_by_team(team_record, expected):
+ prisma_client = _prisma_client_returning(team_record)
+
+ assert await get_mcp_servers_by_team(prisma_client, "team-123") == expected
+
+ prisma_client.db.litellm_teamtable.find_unique.assert_awaited_once_with(
+ where={"team_id": "team-123"},
+ include={"object_permission": True},
+ )
diff --git a/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py b/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py
index c4a0a62ef97..291ce732fc6 100644
--- a/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py
+++ b/tests/test_litellm/proxy/guardrails/test_deferred_guardrail_logging.py
@@ -625,7 +625,7 @@ class TestDeferredStreamingClosure:
"""If a guardrail raises HTTPException, the production
_run_deferred_stream_guardrails must still fire logging
and set guardrail_blocked in metadata."""
- from fastapi import HTTPException # noqa: local import for test isolation
+ from fastapi import HTTPException # local import for test isolation
logging_called = False
diff --git a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
index 2d54a391cf0..0767288d0bc 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_team_endpoints.py
@@ -8454,9 +8454,7 @@ async def test_get_team_daily_activity_member_with_permission_sees_all_spend(
hasattr(mock_db_client.db.litellm_verificationtoken, "find_many")
and mock_db_client.db.litellm_verificationtoken.find_many.called
):
- assert (
- False
- ), "API keys should not be fetched for members with /team/daily/activity permission"
+ pytest.fail("API keys should not be fetched for members with /team/daily/activity permission")
@pytest.mark.asyncio
@@ -8808,7 +8806,7 @@ async def test_get_team_daily_activity_team_admin_sees_all_spend(mock_db_client)
and mock_db_client.db.litellm_verificationtoken.find_many.called
):
# If it was called, that's unexpected for admin users
- assert False, "API keys should not be fetched for team admin users"
+ pytest.fail("API keys should not be fetched for team admin users")
@pytest.mark.asyncio
diff --git a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
index 80b7e25e07d..74f89242f7f 100644
--- a/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
+++ b/tests/test_litellm/proxy/management_endpoints/test_ui_sso.py
@@ -1664,7 +1664,7 @@ class TestAuthCallbackRouting:
key_id = cli_state.split(":", 1)[1]
assert key_id == "cli-test1234567890"
else:
- assert False, "CLI state should have been detected"
+ pytest.fail("CLI state should have been detected")
def test_non_cli_state_routing(self):
"""Test that non-CLI states don't trigger CLI routing"""
diff --git a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
index 7052e050806..15a3e6609f0 100644
--- a/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
+++ b/tests/test_litellm/proxy/spend_tracking/test_spend_management_endpoints.py
@@ -2659,7 +2659,7 @@ class TestSpendLogsPayload:
payload, expected_payload, ignore_keys=ignored_keys
)
if differences:
- assert False, f"Dictionary mismatch: {differences}"
+ pytest.fail(f"Dictionary mismatch: {differences}")
def mock_anthropic_response(*args, **kwargs):
mock_response = MagicMock()
@@ -2755,7 +2755,7 @@ class TestSpendLogsPayload:
payload, expected_payload, ignore_keys=ignored_keys
)
if differences:
- assert False, f"Dictionary mismatch: {differences}"
+ pytest.fail(f"Dictionary mismatch: {differences}")
@pytest.mark.asyncio
async def test_spend_logs_payload_success_log_with_router(self, monkeypatch):
@@ -2849,7 +2849,7 @@ class TestSpendLogsPayload:
payload, expected_payload, ignore_keys=ignored_keys
)
if differences:
- assert False, f"Dictionary mismatch: {differences}"
+ pytest.fail(f"Dictionary mismatch: {differences}")
def _compare_nested_dicts(
diff --git a/tests/test_litellm/proxy/test_redis_auth_cache_flag.py b/tests/test_litellm/proxy/test_redis_auth_cache_flag.py
index 849d5494c6e..772b08bc9d0 100644
--- a/tests/test_litellm/proxy/test_redis_auth_cache_flag.py
+++ b/tests/test_litellm/proxy/test_redis_auth_cache_flag.py
@@ -29,7 +29,7 @@ class _FakeRedisCache(RedisCache):
network calls are made.
"""
- def __init__(self): # noqa: super().__init__ skipped intentionally
+ def __init__(self): # super().__init__ skipped intentionally
self._store = {}
def set_cache(self, key, value, **kwargs): # type: ignore[override]
diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py
index cb58038e081..6db65bc8a99 100644
--- a/tests/test_litellm/test_utils.py
+++ b/tests/test_litellm/test_utils.py
@@ -3721,7 +3721,7 @@ class TestMetadataNoneHandling:
# Attempting 'in' on None raises TypeError
with pytest.raises(TypeError):
- "model_group" in kwargs.get("metadata", {})
+ _ = "model_group" in kwargs.get("metadata", {})
def test_litellm_params_metadata_none(self):
"""litellm_params.get("metadata") or {} should handle None value."""
diff --git a/tests/test_litellm/vector_stores/test_vector_store_create_provider_logic.py b/tests/test_litellm/vector_stores/test_vector_store_create_provider_logic.py
index 5c279554c4e..bfb084e7dd2 100644
--- a/tests/test_litellm/vector_stores/test_vector_store_create_provider_logic.py
+++ b/tests/test_litellm/vector_stores/test_vector_store_create_provider_logic.py
@@ -36,7 +36,6 @@ def test_vector_store_create_with_simple_provider_name():
pytest.fail("Should not enter this branch for simple provider name")
else:
api_type = None
- custom_llm_provider = custom_llm_provider # Keep as-is
# Verify api_type is None
assert api_type is None, "api_type should be None for simple provider names"
@@ -132,7 +131,6 @@ def test_vector_store_create_with_ragflow_provider():
pytest.fail("Should not enter this branch for RAGFlow provider")
else:
api_type = None
- custom_llm_provider = custom_llm_provider # Keep as-is
# Verify api_type is None
assert api_type is None, "api_type should be None for RAGFlow provider"
diff --git a/tests/test_team.py b/tests/test_team.py
index b1aba5c1311..62651beb6ec 100644
--- a/tests/test_team.py
+++ b/tests/test_team.py
@@ -511,10 +511,10 @@ async def test_team_update_sc_2():
print(f"team_data: {team_data}")
## assert rest of object is the same
for k, v in new_team_data["data"].items():
- if (
- k == "members_with_roles"
- ): # assert 1 more member (role: "user", user_email: $user_email)
- len(new_team_data["data"][k]) == len(team_data[k]) + 1
+ if k == "members_with_roles":
+ assert len(new_team_data["data"][k]) == len(
+ team_info["team_info"]["members_with_roles"]
+ )
elif (
k == "created_at"
or k == "updated_at"