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: reject assertions on a caught error inside except (ruff PT017)

ryan-crabbe-berri243ed4393dd6
diff --git a/ruff-tests.toml b/ruff-tests.toml
index c6522d6b335..ff29bcff313 100644
--- a/ruff-tests.toml
+++ b/ruff-tests.toml
@@ -29,6 +29,9 @@
# F811 a name bound twice where the first binding was never used. Mostly a repeated
# import, but the same rule is what catches a second `def test_x` silently
# replacing the first, and a local that shadows an import the module still calls
+# PT017 an `assert` on the caught error inside `except`. Nothing runs the handler when
+# the call stops raising, so the test goes green on the exact regression it was
+# written to catch. `pytest.raises` fails when the call succeeds
#
# 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
@@ -36,4 +39,18 @@
line-length = 120
-lint.select = ["F811", "F821", "B011", "B015", "B017", "B018", "PT011", "PT012", "PT014", "PT015", "PLR0133", "PLW0127"]
+lint.select = [
+ "F811",
+ "F821",
+ "B011",
+ "B015",
+ "B017",
+ "B018",
+ "PT011",
+ "PT012",
+ "PT014",
+ "PT015",
+ "PT017",
+ "PLR0133",
+ "PLW0127",
+]
diff --git a/tests/litellm_utils_tests/test_utils.py b/tests/litellm_utils_tests/test_utils.py
index 3c73224d7a1..0a5327d2662 100644
--- a/tests/litellm_utils_tests/test_utils.py
+++ b/tests/litellm_utils_tests/test_utils.py
@@ -1022,17 +1022,14 @@ def test_convert_model_response_object():
"hidden_params": None,
}
- try:
+ with pytest.raises(Exception) as exc_info: # noqa: PT011 # bare Exception() with attributes, so str(e) is empty
litellm.convert_to_model_response_object(**args)
- pytest.fail("Expected this to fail")
- except Exception as e:
- assert hasattr(e, "status_code")
- assert e.status_code == 400
- assert hasattr(e, "message")
- assert (
- e.message
- == '{"type":"error","error":{"type":"invalid_request_error","message":"Output blocked by content filtering policy"}}'
- )
+ e = exc_info.value
+ assert e.status_code == 400
+ assert (
+ e.message
+ == '{"type":"error","error":{"type":"invalid_request_error","message":"Output blocked by content filtering policy"}}'
+ )
@pytest.mark.parametrize(
diff --git a/tests/llm_translation/test_containers_api.py b/tests/llm_translation/test_containers_api.py
index 4e26a883fcb..6c7303e7b4d 100644
--- a/tests/llm_translation/test_containers_api.py
+++ b/tests/llm_translation/test_containers_api.py
@@ -63,17 +63,13 @@ def test_container_files_api():
# 3. Try retrieve non-existent file metadata (should raise error)
print("3. Testing retrieve_container_file (expect error)...")
- try:
+ with pytest.raises(Exception, match="(?i)not found|invalid"):
retrieve_container_file(
container_id=container.id,
file_id="cfile_nonexistent",
custom_llm_provider="openai",
api_key=api_key,
)
- 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 ✓")
# 3b. Try retrieve non-existent file content (should raise error)
print("3b. Testing retrieve_container_file_content (expect error)...")
diff --git a/tests/llm_translation/test_gemini.py b/tests/llm_translation/test_gemini.py
index 9326e291b7f..310a2e2c20c 100644
--- a/tests/llm_translation/test_gemini.py
+++ b/tests/llm_translation/test_gemini.py
@@ -1315,7 +1315,7 @@ def test_gemini_exception_message_format():
mock_exception.status_code = 400
# Test the exception mapping for Gemini provider
- try:
+ with pytest.raises(BadRequestError) as exc_info:
exception_type(
model="gemini-pro",
original_exception=mock_exception,
@@ -1323,22 +1323,18 @@ def test_gemini_exception_message_format():
completion_kwargs={},
extra_kwargs={},
)
- # Should not reach here - exception should 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
- error_message = str(e)
- print(f"Error message: {error_message}") # For debugging
-
- # This assertion will initially FAIL - that's expected for TDD
- assert "GeminiException" in error_message, (
- f"Expected 'GeminiException' in error message, got: {error_message}. "
- f"This test should fail before the fix is implemented."
- )
- assert (
- "VertexAIException" not in error_message
- ), f"Should not contain 'VertexAIException' in error message, got: {error_message}"
+ e = exc_info.value
+ error_message = str(e)
+ print(f"Error message: {error_message}") # For debugging
+
+ # This assertion will initially FAIL - that's expected for TDD
+ assert "GeminiException" in error_message, (
+ f"Expected 'GeminiException' in error message, got: {error_message}. "
+ f"This test should fail before the fix is implemented."
+ )
+ assert (
+ "VertexAIException" not in error_message
+ ), f"Should not contain 'VertexAIException' in error message, got: {error_message}"
@pytest.mark.parametrize(
@@ -1392,8 +1388,21 @@ def l(status_code, expected_exception):
# Set message attribute for compatibility with exception mapping
mock_exception.message = f"HTTP {status_code}"
+ exception_classes = {
+ "BadRequestError": BadRequestError,
+ "AuthenticationError": AuthenticationError,
+ "PermissionDeniedError": PermissionDeniedError,
+ "NotFoundError": NotFoundError,
+ "Timeout": Timeout,
+ "RateLimitError": RateLimitError,
+ "InternalServerError": InternalServerError,
+ "APIConnectionError": APIConnectionError,
+ "ServiceUnavailableError": ServiceUnavailableError,
+ }
+ expected_class = exception_classes[expected_exception]
+
# Test the exception mapping
- try:
+ with pytest.raises(expected_class) as exc_info:
exception_type(
model="gemini-pro",
original_exception=mock_exception,
@@ -1401,33 +1410,16 @@ def l(status_code, expected_exception):
completion_kwargs={},
extra_kwargs={},
)
- 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 = {
- "BadRequestError": BadRequestError,
- "AuthenticationError": AuthenticationError,
- "PermissionDeniedError": PermissionDeniedError,
- "NotFoundError": NotFoundError,
- "Timeout": Timeout,
- "RateLimitError": RateLimitError,
- "InternalServerError": InternalServerError,
- "APIConnectionError": APIConnectionError,
- "ServiceUnavailableError": ServiceUnavailableError,
- }
- expected_class = exception_classes[expected_exception]
- assert isinstance(
- e, expected_class
- ), f"Expected {expected_exception}, got {type(e).__name__}"
+ e = exc_info.value
- # Verify the error message contains GeminiException
- error_message = str(e)
- assert (
- "GeminiException" in error_message
- ), f"Expected 'GeminiException' in error message for status {status_code}, got: {error_message}"
- assert (
- "VertexAIException" not in error_message
- ), f"Should not contain 'VertexAIException' for status {status_code}, got: {error_message}"
+ # Verify the error message contains GeminiException
+ error_message = str(e)
+ assert (
+ "GeminiException" in error_message
+ ), f"Expected 'GeminiException' in error message for status {status_code}, got: {error_message}"
+ assert (
+ "VertexAIException" not in error_message
+ ), f"Should not contain 'VertexAIException' for status {status_code}, got: {error_message}"
def test_gemini_embedding():
diff --git a/tests/llm_translation/test_hyperbolic.py b/tests/llm_translation/test_hyperbolic.py
index ce77ddec73b..006d31c88e6 100644
--- a/tests/llm_translation/test_hyperbolic.py
+++ b/tests/llm_translation/test_hyperbolic.py
@@ -23,17 +23,13 @@ def test_get_llm_provider_hyperbolic():
def test_hyperbolic_completion_call():
"""Test basic completion call structure for Hyperbolic"""
# This is primarily a structure test since we don't have actual API keys
- try:
- litellm.set_verbose = True
- response = litellm.completion(
- model="hyperbolic/qwen-2.5-72b",
- messages=[{"role": "user", "content": "Hello!"}],
- mock_response="Hi there!",
- )
- assert response is not None
- except Exception as e:
- # Expected to fail without valid API key, but should recognize the provider
- assert "hyperbolic" in str(e).lower() or "api" in str(e).lower()
+ litellm.set_verbose = True
+ response = litellm.completion(
+ model="hyperbolic/qwen-2.5-72b",
+ messages=[{"role": "user", "content": "Hello!"}],
+ mock_response="Hi there!",
+ )
+ assert response is not None
def test_hyperbolic_config_initialization():
diff --git a/tests/llm_translation/test_litellm_proxy_provider.py b/tests/llm_translation/test_litellm_proxy_provider.py
index 8b6f37bfbc9..cea0167472e 100644
--- a/tests/llm_translation/test_litellm_proxy_provider.py
+++ b/tests/llm_translation/test_litellm_proxy_provider.py
@@ -578,7 +578,7 @@ def test_litellm_gateway_from_sdk_with_response_cost_in_additional_headers():
def test_litellm_gateway_from_sdk_with_thinking_param():
- try:
+ with pytest.raises(Exception, match="Connection error.") as exc_info:
response = litellm.completion(
model="litellm_proxy/anthropic.claude-sonnet-4-5-20250929-v1:0",
messages=[{"role": "user", "content": "Hello world"}],
@@ -587,6 +587,5 @@ def test_litellm_gateway_from_sdk_with_thinking_param():
# client=openai_client,
thinking={"type": "enabled", "max_budget": 100},
)
- pytest.fail("Expected an error to be raised")
- except Exception as e:
- assert "Connection error." in str(e)
+ e = exc_info.value
+ assert "Connection error." in str(e)
diff --git a/tests/local_testing/test_acompletion_fallbacks.py b/tests/local_testing/test_acompletion_fallbacks.py
index 2d282f4f4f6..7cf97eb9b5e 100644
--- a/tests/local_testing/test_acompletion_fallbacks.py
+++ b/tests/local_testing/test_acompletion_fallbacks.py
@@ -68,14 +68,14 @@ async def test_acompletion_fallbacks_empty_list():
"""
Test behavior when fallbacks list is empty
"""
- try:
+ with pytest.raises(litellm.NotFoundError) as exc_info:
response = await litellm.acompletion(
model="openai/unknown-model",
messages=[{"role": "user", "content": "Hello, world!"}],
fallbacks=[],
)
- except Exception as e:
- assert isinstance(e, litellm.NotFoundError)
+ e = exc_info.value
+ assert isinstance(e, litellm.NotFoundError)
@pytest.mark.asyncio
diff --git a/tests/local_testing/test_completion.py b/tests/local_testing/test_completion.py
index c7cd5a1a2d4..3b890273ce7 100644
--- a/tests/local_testing/test_completion.py
+++ b/tests/local_testing/test_completion.py
@@ -512,7 +512,8 @@ async def test_anthropic_no_content_error():
except litellm.InternalServerError:
pass
except litellm.APIError as e:
- assert e.status_code == 500
+ if e.status_code != 500:
+ raise
except Exception as e:
pytest.fail(f"An unexpected error occurred - {str(e)}")
@@ -4049,7 +4050,7 @@ def test_completion_novita_ai_dynamic_params(api_key):
"create",
side_effect=Exception("Invalid API key"),
) as mock_call:
- try:
+ with pytest.raises(Exception, match="Invalid API key") as exc_info:
completion(
model="novita/meta-llama/llama-3.3-70b-instruct",
messages=messages,
@@ -4057,10 +4058,8 @@ def test_completion_novita_ai_dynamic_params(api_key):
client=openai_client,
api_base="https://api.novita.ai/v3/openai",
)
- pytest.fail(f"This call should have failed!")
- except Exception as e:
- # This should fail with the mocked exception
- assert "Invalid API key" in str(e)
+ e = exc_info.value
+ assert "Invalid API key" in str(e)
mock_call.assert_called_once()
except Exception as e:
diff --git a/tests/local_testing/test_dynamic_rate_limit_handler.py b/tests/local_testing/test_dynamic_rate_limit_handler.py
index 373949a81ac..fe3c8ca260e 100644
--- a/tests/local_testing/test_dynamic_rate_limit_handler.py
+++ b/tests/local_testing/test_dynamic_rate_limit_handler.py
@@ -205,17 +205,15 @@ async def test_rate_limit_raised(dynamic_rate_limit_handler, user_api_key_auth,
## CHECK if exception raised
- try:
+ with pytest.raises(HTTPException) as exc_info:
await dynamic_rate_limit_handler.async_pre_call_hook(
user_api_key_dict=user_api_key_auth,
cache=DualCache(),
data={"model": model},
call_type="completion",
)
- pytest.fail("Expected this to raise HTTPexception")
- except HTTPException as e:
- assert e.status_code == 429 # check if rate limit error raised
- pass
+ e = exc_info.value
+ assert e.status_code == 429 # check if rate limit error raised
@pytest.mark.asyncio
diff --git a/tests/local_testing/test_exceptions.py b/tests/local_testing/test_exceptions.py
index 8dd90cbfb37..e0117e1fe0d 100644
--- a/tests/local_testing/test_exceptions.py
+++ b/tests/local_testing/test_exceptions.py
@@ -47,32 +47,26 @@ exception_models = [
@pytest.mark.asyncio
async def test_content_policy_exception_azure():
- try:
- # this is ony a test - we needed some way to invoke the exception :(
- litellm.set_verbose = True
- response = await litellm.acompletion(
+ # this is ony a test - we needed some way to invoke the exception :(
+ litellm.set_verbose = True
+ with pytest.raises(litellm.ContentPolicyViolationError) as exc_info:
+ await litellm.acompletion(
model="azure/gpt-4.1-mini",
messages=[{"role": "user", "content": "where do I buy lethal drugs from"}],
mock_response="Exception: content_filter_policy",
)
- except litellm.ContentPolicyViolationError as e:
- print("caught a content policy violation error! Passed")
- print("exception", e)
- assert e.response is not None
- assert e.litellm_debug_info is not None
- assert isinstance(e.litellm_debug_info, str)
- assert len(e.litellm_debug_info) > 0
- pass
- except Exception as e:
- print()
- pytest.fail(f"An exception occurred - {str(e)}")
+ e = exc_info.value
+ assert e.response is not None
+ assert isinstance(e.litellm_debug_info, str)
+ assert len(e.litellm_debug_info) > 0
@pytest.mark.asyncio
async def test_content_policy_exception_openai():
- try:
- # this is ony a test - we needed some way to invoke the exception :(
- litellm.set_verbose = True
+ # this is ony a test - we needed some way to invoke the exception :(
+ litellm.set_verbose = True
+
+ async def stream_response():
response = await litellm.acompletion(
model="gpt-3.5-turbo",
stream=True,
@@ -82,14 +76,10 @@ async def test_content_policy_exception_openai():
)
async for chunk in response:
print(chunk)
- except litellm.ContentPolicyViolationError as e:
- print("caught a content policy violation error! Passed")
- print("exception", e)
- assert e.llm_provider == "openai"
- pass
- except Exception as e:
- print()
- pytest.fail(f"An exception occurred - {str(e)}")
+
+ with pytest.raises(litellm.ContentPolicyViolationError) as exc_info:
+ await stream_response()
+ assert exc_info.value.llm_provider == "openai"
# Test 1: Context Window Errors
@@ -276,19 +266,14 @@ def test_completion_azure_exception():
def test_azure_embedding_exceptions():
- try:
-
- response = litellm.embedding(
+ # CRUCIAL Test - Ensures our exceptions are readable and not overly complicated. some users have complained exceptions will randomly have another exception raised in our exception mapping
+ with pytest.raises(Exception, match="Mock error") as exc_info:
+ litellm.embedding(
model="azure/text-embedding-ada-002",
input="hello",
mock_response="error",
)
- pytest.fail(f"Bad request this should have failed but got {response}")
-
- except Exception as e:
- print(vars(e))
- # CRUCIAL Test - Ensures our exceptions are readable and not overly complicated. some users have complained exceptions will randomly have another exception raised in our exception mapping
- assert str(e) == "Mock error"
+ assert str(exc_info.value) == "Mock error"
async def asynctest_completion_azure_exception():
@@ -348,7 +333,6 @@ def asynctest_completion_openai_exception_bad_model():
print("Passed")
except Exception as e:
print("Raised wrong type of exception", type(e))
- assert isinstance(e, openai.BadRequestError)
pytest.fail(f"Error occurred: {e}")
@@ -411,31 +395,19 @@ def test_completion_openai_exception():
# test_completion_openai_exception()
-def test_anthropic_openai_exception():
+def test_anthropic_openai_exception(monkeypatch):
# test if anthropic raises litellm.AuthenticationError
- try:
- litellm.set_verbose = True
- ## Test azure call
- old_azure_key = os.environ["ANTHROPIC_API_KEY"]
- os.environ.pop("ANTHROPIC_API_KEY")
- response = completion(
+ litellm.set_verbose = True
+ monkeypatch.delenv("ANTHROPIC_API_KEY")
+ with pytest.raises(litellm.AuthenticationError) as exc_info:
+ completion(
model="anthropic/claude-3-sonnet-20240229",
messages=[{"role": "user", "content": "hello"}],
)
- print(f"response: {response}")
- print(response)
- except litellm.AuthenticationError as e:
- os.environ["ANTHROPIC_API_KEY"] = old_azure_key
- print("Exception vars=", vars(e))
- assert (
- "Missing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via params"
- in e.message
- )
- print(
- "ANTHROPIC_API_KEY: good job got the correct error for ANTHROPIC_API_KEY when key not set"
- )
- except Exception as e:
- pytest.fail(f"Error occurred: {e}")
+ assert (
+ "Missing Anthropic API Key - A call is being made to anthropic but no key is set either in the environment variables or via params"
+ in exc_info.value.message
+ )
def test_completion_mistral_exception():
@@ -468,29 +440,29 @@ def test_completion_bedrock_invalid_role_exception():
"""
Test if litellm raises a BadRequestError for an invalid role on Bedrock
"""
- try:
- litellm.set_verbose = True
- response = completion(
- model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
- messages=[{"role": "very-bad-role", "content": "hello"}],
- )
- print(f"response: {response}")
- print(response)
-
- except Exception as e:
- assert isinstance(
- e, litellm.BadRequestError
- ), "Expected BadRequestError but got {}".format(type(e))
- print("str(e) = {}".format(str(e)))
-
- # This is important - We we previously returning a poorly formatted error string. Which was
- # litellm.BadRequestError: litellm.BadRequestError: Invalid Message passed in {'role': 'very-bad-role', 'content': 'hello'}
+ litellm.set_verbose = True
+ response = completion(
+ model="bedrock/anthropic.claude-3-sonnet-20240229-v1:0",
+ messages=[{"role": "very-bad-role", "content": "hello"}],
+ )
+ print(f"response: {response}")
- # IMPORTANT ASSERTION
- assert (
- (str(e))
- == "litellm.BadRequestError: Invalid Message passed in {'role': 'very-bad-role', 'content': 'hello'}"
- )
+ with pytest.raises(litellm.BadRequestError) as exc_info:
+ print(response)
+ e = exc_info.value
+ assert isinstance(
+ e, litellm.BadRequestError
+ ), "Expected BadRequestError but got {}".format(type(e))
+ print("str(e) = {}".format(str(e)))
+
+ # This is important - We we previously returning a poorly formatted error string. Which was
+ # litellm.BadRequestError: litellm.BadRequestError: Invalid Message passed in {'role': 'very-bad-role', 'content': 'hello'}
+
+ # IMPORTANT ASSERTION
+ assert (
+ (str(e))
+ == "litellm.BadRequestError: Invalid Message passed in {'role': 'very-bad-role', 'content': 'hello'}"
+ )
@pytest.mark.skip(reason="OpenAI exception changed to a generic error")
@@ -580,88 +552,54 @@ def test_content_policy_violation_error_streaming():
asyncio.run(test_get_error())
-def test_completion_perplexity_exception_on_openai_client():
- try:
- import openai
-
- print("perplexity test\n\n")
- litellm.set_verbose = False
- ## Test azure call
- old_azure_key = os.environ["PERPLEXITYAI_API_KEY"]
+def test_completion_perplexity_exception_on_openai_client(monkeypatch):
+ import openai
- # delete perplexityai api key to simulate bad api key
- del os.environ["PERPLEXITYAI_API_KEY"]
+ print("perplexity test\n\n")
+ litellm.set_verbose = False
- # temporaily delete openai api key
- original_openai_key = os.environ["OPENAI_API_KEY"]
- del os.environ["OPENAI_API_KEY"]
+ # delete both api keys to simulate a bad api key
+ monkeypatch.delenv("PERPLEXITYAI_API_KEY")
+ monkeypatch.delenv("OPENAI_API_KEY")
- response = completion(
+ with pytest.raises(openai.AuthenticationError) as exc_info:
+ completion(
model="perplexity/mistral-7b-instruct",
messages=[{"role": "user", "content": "hello"}],
)
- os.environ["PERPLEXITYAI_API_KEY"] = old_azure_key
- os.environ["OPENAI_API_KEY"] = original_openai_key
- pytest.fail("Request should have failed - bad api key")
- except openai.AuthenticationError as e:
- os.environ["PERPLEXITYAI_API_KEY"] = old_azure_key
- os.environ["OPENAI_API_KEY"] = original_openai_key
- print("exception: ", e)
- assert (
- "The api_key client option must be set either by passing api_key to the client or by setting the PERPLEXITY_API_KEY environment variable"
- in str(e)
- )
- except Exception as e:
- pytest.fail(f"Error occurred: {e}")
+ assert (
+ "The api_key client option must be set either by passing api_key to the client or by setting the PERPLEXITY_API_KEY environment variable"
+ in str(exc_info.value)
+ )
# test_completion_perplexity_exception_on_openai_client()
-def test_completion_perplexity_exception():
- try:
- import openai
+def test_completion_perplexity_exception(monkeypatch):
+ import openai
- print("perplexity test\n\n")
- litellm.set_verbose = True
- ## Test azure call
- old_azure_key = os.environ["PERPLEXITYAI_API_KEY"]
- os.environ["PERPLEXITYAI_API_KEY"] = "good morning"
- response = completion(
+ print("perplexity test\n\n")
+ litellm.set_verbose = True
+ monkeypatch.setenv("PERPLEXITYAI_API_KEY", "good morning")
+ with pytest.raises(openai.AuthenticationError, match="PerplexityException"):
+ completion(
model="perplexity/mistral-7b-instruct",
messages=[{"role": "user", "content": "hello"}],
)
- os.environ["PERPLEXITYAI_API_KEY"] = old_azure_key
- pytest.fail("Request should have failed - bad api key")
- except openai.AuthenticationError as e:
- os.environ["PERPLEXITYAI_API_KEY"] = old_azure_key
- print("exception: ", e)
- assert "PerplexityException" in str(e)
- except Exception as e:
- pytest.fail(f"Error occurred: {e}")
-def test_completion_openai_api_key_exception():
- try:
- import openai
+def test_completion_openai_api_key_exception(monkeypatch):
+ import openai
- print("gpt-3.5 test\n\n")
- litellm.set_verbose = True
- ## Test azure call
- old_azure_key = os.environ["OPENAI_API_KEY"]
- os.environ["OPENAI_API_KEY"] = "good morning"
- response = completion(
+ print("gpt-3.5 test\n\n")
+ litellm.set_verbose = True
+ monkeypatch.setenv("OPENAI_API_KEY", "good morning")
+ with pytest.raises(openai.AuthenticationError, match="OpenAIException"):
+ completion(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "hello"}],
)
- os.environ["OPENAI_API_KEY"] = old_azure_key
- pytest.fail("Request should have failed - bad api key")
- except openai.AuthenticationError as e:
- os.environ["OPENAI_API_KEY"] = old_azure_key
- print("exception: ", e)
- assert "OpenAIException" in str(e)
- except Exception as e:
- pytest.fail(f"Error occurred: {e}")
# tesy_async_acompletion()
@@ -725,7 +663,8 @@ def test_litellm_predibase_exception():
)
pytest.fail("Request should have failed - bad api key")
except Exception as e:
- assert "hf-rawapikey" not in str(e)
+ if "hf-rawapikey" in str(e):
+ pytest.fail("predibase error leaked the raw api key")
print("exception: ", e)
@@ -868,22 +807,15 @@ def test_fireworks_ai_exception_mapping():
status_code=scenario["status_code"], message=scenario["message"], headers={}
)
- try:
- response = litellm.completion(
+ with pytest.raises(scenario["expected_exception"]) as exc_info:
+ litellm.completion(
model="fireworks_ai/llama-v3p1-70b-instruct",
messages=[{"role": "user", "content": "Hello"}],
mock_response=mock_exception,
)
- pytest.fail(
- f"Expected {scenario['expected_exception'].__name__} to be raised"
- )
- except scenario["expected_exception"] as e:
- if scenario["expected_exception"] == litellm.RateLimitError:
- assert "rate limit" in str(e).lower() or "429" in str(e)
- except Exception as e:
- pytest.fail(
- f"Expected {scenario['expected_exception'].__name__} but got {type(e).__name__}: {e}"
- )
+ if scenario["expected_exception"] == litellm.RateLimitError:
+ error_str = str(exc_info.value)
+ assert "rate limit" in error_str.lower() or "429" in error_str
# Test ExceptionCheckers.is_error_str_rate_limit() method directly
@@ -1124,8 +1056,7 @@ async def test_exception_with_headers(sync_mode, provider, model, call_type, str
new_retry_after_mock_client
)
- exception_raised = False
- try:
+ async def call_and_drain():
if sync_mode:
resp = original_function(**data, client=openai_client)
if streaming:
@@ -1138,14 +1069,11 @@ async def test_exception_with_headers(sync_mode, provider, model, call_type, str
async for chunk in resp:
continue
- except litellm.RateLimitError as e:
- exception_raised = True
- assert e.litellm_response_headers is not None
- assert int(e.litellm_response_headers["retry-after"]) == cooldown_time
+ with pytest.raises(litellm.RateLimitError) as exc_info:
+ await call_and_drain()
- if exception_raised is False:
- print(resp)
- assert exception_raised
+ assert exc_info.value.litellm_response_headers is not None
+ assert int(exc_info.value.litellm_response_headers["retry-after"]) == cooldown_time
def test_openai_gateway_timeout_error():
@@ -1188,7 +1116,7 @@ def test_openai_gateway_timeout_error():
setattr(exception, k, v)
raise exception
- try:
+ with pytest.raises(litellm.Timeout) as exc_info:
with patch.object(
mapped_target,
"create",
@@ -1199,9 +1127,8 @@ def test_openai_gateway_timeout_error():
messages=[{"role": "user", "content": "Hello world"}],
client=openai_client,
)
- pytest.fail("Expected to raise Timeout")
- except litellm.Timeout as e:
- assert e.status_code == 504
+ e = exc_info.value
+ assert e.status_code == 504
@pytest.mark.parametrize(
@@ -1287,8 +1214,7 @@ async def test_exception_with_headers_httpx(
new_retry_after_mock_client
)
- exception_raised = False
- try:
+ async def call_and_drain():
if sync_mode:
resp = original_function(**data, client=client)
if streaming:
@@ -1301,17 +1227,14 @@ async def test_exception_with_headers_httpx(
async for chunk in resp:
continue
- except litellm.RateLimitError as e:
- exception_raised = True
- assert (
- e.litellm_response_headers is not None
- ), "litellm_response_headers is None"
- print("e.litellm_response_headers", e.litellm_response_headers)
- assert int(e.litellm_response_headers["retry-after"]) == cooldown_time
+ with pytest.raises(litellm.RateLimitError) as exc_info:
+ await call_and_drain()
- if exception_raised is False:
- print(resp)
- assert exception_raised
+ assert (
+ exc_info.value.litellm_response_headers is not None
+ ), "litellm_response_headers is None"
+ print("e.litellm_response_headers", exc_info.value.litellm_response_headers)
+ assert int(exc_info.value.litellm_response_headers["retry-after"]) == cooldown_time
@pytest.mark.asyncio
@@ -1322,30 +1245,29 @@ async def test_bad_request_error_contains_httpx_response(model):
Relevant issue: https://github.com/BerriAI/litellm/issues/6732
"""
- try:
+ with pytest.raises(litellm.BadRequestError) as exc_info:
await litellm.acompletion(
model=model,
messages=[{"role": "user", "content": "Hello world"}],
bad_arg="bad_arg",
)
- pytest.fail("Expected to raise BadRequestError")
- except litellm.BadRequestError as e:
- print("e.response", e.response)
- print("vars(e.response)", vars(e.response))
- assert e.response is not None
+ e = exc_info.value
+ print("e.response", e.response)
+ print("vars(e.response)", vars(e.response))
+ assert e.response is not None
def test_exceptions_base_class():
- try:
+ with pytest.raises(litellm.RateLimitError) as exc_info:
raise litellm.RateLimitError(
message="BedrockException: Rate Limit Error",
model="model",
llm_provider="bedrock",
)
- except litellm.RateLimitError as e:
- assert isinstance(e, litellm.RateLimitError)
- assert e.code == "429"
- assert e.type == "throttling_error"
+ e = exc_info.value
+ assert isinstance(e, litellm.RateLimitError)
+ assert e.code == "429"
+ assert e.type == "throttling_error"
def test_context_window_exceeded_error_from_litellm_proxy():
diff --git a/tests/local_testing/test_openai_moderations_hook.py b/tests/local_testing/test_openai_moderations_hook.py
index 2e24740c929..944ac047e55 100644
--- a/tests/local_testing/test_openai_moderations_hook.py
+++ b/tests/local_testing/test_openai_moderations_hook.py
@@ -64,7 +64,7 @@ async def test_openai_moderation_error_raising(monkeypatch):
setattr(litellm.proxy.proxy_server, "llm_router", llm_router)
- try:
+ with pytest.raises(Exception, match="Violated content safety policy") as exc_info:
await openai_mod.async_moderation_hook(
data={
"messages": [
@@ -77,11 +77,9 @@ async def test_openai_moderation_error_raising(monkeypatch):
user_api_key_dict=user_api_key_dict,
call_type="completion",
)
- pytest.fail(f"Should have failed")
- except Exception as e:
- print("Got exception: ", e)
- assert "Violated content safety policy" in str(e)
- pass
+ e = exc_info.value
+ print("Got exception: ", e)
+ assert "Violated content safety policy" in str(e)
@pytest.mark.asyncio
@@ -127,25 +125,26 @@ async def test_openai_moderation_responses_api_input_field():
openai_mod, "async_make_request", return_value=mock_moderation_response
):
# Test 1: Responses API / Embeddings with texts (string input)
- try:
- inputs = GenericGuardrailAPIInputs(texts=["I want to hurt people"])
+ inputs = GenericGuardrailAPIInputs(texts=["I want to hurt people"])
+
+ with pytest.raises(Exception, match="Violated OpenAI moderation policy") as exc_info:
await openai_mod.apply_guardrail(
inputs=inputs,
request_data={"model": "gpt-4o", "input": "I want to hurt people"},
input_type="request",
)
- pytest.fail("Should have raised HTTPException for flagged content")
- except Exception as e:
- print("Got exception for texts input: ", e)
- assert "Violated OpenAI moderation policy" in str(e)
+ e = exc_info.value
+ print("Got exception for texts input: ", e)
+ assert "Violated OpenAI moderation policy" in str(e)
# Test 2: Responses API with structured_messages (list of message objects)
- try:
- inputs = GenericGuardrailAPIInputs(
- structured_messages=[
- {"role": "user", "content": "I want to hurt people"}
- ]
- )
+ inputs = GenericGuardrailAPIInputs(
+ structured_messages=[
+ {"role": "user", "content": "I want to hurt people"}
+ ]
+ )
+
+ with pytest.raises(Exception, match="Violated OpenAI moderation policy") as exc_info:
await openai_mod.apply_guardrail(
inputs=inputs,
request_data={
@@ -154,18 +153,18 @@ async def test_openai_moderation_responses_api_input_field():
},
input_type="request",
)
- pytest.fail("Should have raised HTTPException for flagged content")
- except Exception as e:
- print("Got exception for structured_messages input: ", e)
- assert "Violated OpenAI moderation policy" in str(e)
+ e = exc_info.value
+ print("Got exception for structured_messages input: ", e)
+ assert "Violated OpenAI moderation policy" in str(e)
# Test 3: Chat Completions with structured_messages
- try:
- inputs = GenericGuardrailAPIInputs(
- structured_messages=[
- {"role": "user", "content": "I want to hurt people"}
- ]
- )
+ inputs = GenericGuardrailAPIInputs(
+ structured_messages=[
+ {"role": "user", "content": "I want to hurt people"}
+ ]
+ )
+
+ with pytest.raises(Exception, match="Violated OpenAI moderation policy") as exc_info:
await openai_mod.apply_guardrail(
inputs=inputs,
request_data={
@@ -174,9 +173,8 @@ async def test_openai_moderation_responses_api_input_field():
},
input_type="request",
)
- pytest.fail("Should have raised HTTPException for flagged content")
- except Exception as e:
- print("Got exception for chat completions input: ", e)
- assert "Violated OpenAI moderation policy" in str(e)
+ e = exc_info.value
+ print("Got exception for chat completions input: ", e)
+ assert "Violated OpenAI moderation policy" in str(e)
print("✓ All Responses API moderation tests passed!")
diff --git a/tests/local_testing/test_router.py b/tests/local_testing/test_router.py
index 7bc29517f8c..f648b31901a 100644
--- a/tests/local_testing/test_router.py
+++ b/tests/local_testing/test_router.py
@@ -278,7 +278,8 @@ def test_router_sensitive_keys():
)
except Exception as e:
print(f"error msg - {str(e)}")
- assert "special-key" not in str(e)
+ if "special-key" in str(e):
+ pytest.fail("router error leaked the api key")
def test_router_order():
@@ -1916,21 +1917,21 @@ def test_router_context_window_pre_call_check(model, base_model, llm_provider):
def test_router_cooldown_api_connection_error():
from litellm.router_utils.cooldown_handlers import _is_cooldown_required
- try:
+ with pytest.raises(litellm.APIConnectionError) as exc_info:
_ = litellm.completion(
model="vertex_ai/gemini-1.5-pro",
messages=[{"role": "admin", "content": "Fail on this!"}],
)
- except litellm.APIConnectionError as e:
- assert (
- _is_cooldown_required(
- litellm_router_instance=Router(),
- model_id="",
- exception_status=e.code,
- exception_str=str(e),
- )
- is False
+ e = exc_info.value
+ assert (
+ _is_cooldown_required(
+ litellm_router_instance=Router(),
+ model_id="",
+ exception_status=e.code,
+ exception_str=str(e),
)
+ is False
+ )
router = Router(
model_list=[
@@ -2141,25 +2142,22 @@ async def test_aaarouter_dynamic_cooldown_message_retry_time(sync_mode):
assert len(cooldown_deployments) > 0
# Verify that a subsequent call raises RouterRateLimitError with correct cooldown_time
- exception_raised = False
- try:
- if sync_mode:
+ if sync_mode:
+ with pytest.raises(litellm.types.router.RouterRateLimitError) as exc_info:
router.embedding(
model="text-embedding-ada-002",
input="Hello world!",
mock_response=[0.1, 0.2, 0.3],
)
- else:
+ else:
+ with pytest.raises(litellm.types.router.RouterRateLimitError) as exc_info:
await router.aembedding(
model="text-embedding-ada-002",
input="Hello world!",
mock_response=[0.1, 0.2, 0.3],
)
- except litellm.types.router.RouterRateLimitError as e:
- exception_raised = True
- assert e.cooldown_time == cooldown_time
- assert exception_raised
+ assert exc_info.value.cooldown_time == cooldown_time
@pytest.mark.parametrize("sync_mode", [True, False])
diff --git a/tests/local_testing/test_router_fallbacks.py b/tests/local_testing/test_router_fallbacks.py
index 86dec406332..f9ec69c1a57 100644
--- a/tests/local_testing/test_router_fallbacks.py
+++ b/tests/local_testing/test_router_fallbacks.py
@@ -1197,22 +1197,22 @@ async def test_using_default_fallback(sync_mode):
},
],
)
- try:
- if sync_mode:
- response = router.completion(
- model="openai/foo",
- messages=[{"role": "user", "content": "Hey, how's it going?"}],
- )
- else:
- response = await router.acompletion(
- model="openai/foo",
- messages=[{"role": "user", "content": "Hey, how's it going?"}],
- )
+ if sync_mode:
+ response = router.completion(
+ model="openai/foo",
+ messages=[{"role": "user", "content": "Hey, how's it going?"}],
+ )
+ else:
+ response = await router.acompletion(
+ model="openai/foo",
+ messages=[{"role": "user", "content": "Hey, how's it going?"}],
+ )
+
+ with pytest.raises(Exception, match="BadRequestError") as exc_info:
print("got response=", response)
- pytest.fail(f"Expected call to fail we passed model=openai/foo")
- except Exception as e:
- print("got exception = ", e)
- assert "BadRequestError" in str(e)
+ e = exc_info.value
+ print("got exception = ", e)
+ assert "BadRequestError" in str(e)
@pytest.mark.parametrize("sync_mode", [False])
diff --git a/tests/local_testing/test_router_get_deployments.py b/tests/local_testing/test_router_get_deployments.py
index 8df04b4f1d3..78503b36c74 100644
--- a/tests/local_testing/test_router_get_deployments.py
+++ b/tests/local_testing/test_router_get_deployments.py
@@ -671,13 +671,10 @@ def test_get_available_deployment_for_pass_through_no_deployments():
)
# Test that BadRequestError is raised when no pass-through deployments exist
- try:
+ with pytest.raises(litellm.BadRequestError) as exc_info:
router.get_available_deployment_for_pass_through("gpt-3.5-turbo")
- pytest.fail(
- "Expected BadRequestError when no pass-through deployments exist"
- )
- except litellm.BadRequestError as e:
- assert "use_in_pass_through=True" in str(e)
+ e = exc_info.value
+ assert "use_in_pass_through=True" in str(e)
router.reset()
except Exception as e:
diff --git a/tests/local_testing/test_router_retries.py b/tests/local_testing/test_router_retries.py
index cb9b26b0a4e..7d1ad012745 100644
--- a/tests/local_testing/test_router_retries.py
+++ b/tests/local_testing/test_router_retries.py
@@ -927,35 +927,33 @@ async def test_router_retry_num_retries_tracking():
with patch.object(
router, "_time_to_sleep_before_retry", return_value=0.01
): # Fast retries for testing
- try:
+ with pytest.raises(litellm.RateLimitError) as exc_info:
await router.acompletion(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello"}],
)
- pytest.fail("Expected exception to be raised")
- except litellm.RateLimitError as e:
- # Verify num_retries is correctly set to 3 (not 2, which would be current_attempt)
- assert hasattr(
- e, "num_retries"
- ), "Exception should have num_retries attribute"
- assert hasattr(
- e, "max_retries"
- ), "Exception should have max_retries attribute"
- assert (
- e.num_retries == 3
- ), f"Expected num_retries to be 3, got {e.num_retries}"
- assert (
- e.max_retries == 3
- ), f"Expected max_retries to be 3, got {e.max_retries}"
-
- # Verify the error message includes correct retry information
- error_str = str(e)
- assert (
- "LiteLLM Retried: 3 times" in error_str
- ), f"Error message should indicate 3 retries: {error_str}"
- assert (
- "LiteLLM Max Retries: 3" in error_str
- ), f"Error message should show max retries: {error_str}"
+ e = exc_info.value
+ assert hasattr(
+ e, "num_retries"
+ ), "Exception should have num_retries attribute"
+ assert hasattr(
+ e, "max_retries"
+ ), "Exception should have max_retries attribute"
+ assert (
+ e.num_retries == 3
+ ), f"Expected num_retries to be 3, got {e.num_retries}"
+ assert (
+ e.max_retries == 3
+ ), f"Expected max_retries to be 3, got {e.max_retries}"
+
+ # Verify the error message includes correct retry information
+ error_str = str(e)
+ assert (
+ "LiteLLM Retried: 3 times" in error_str
+ ), f"Error message should indicate 3 retries: {error_str}"
+ assert (
+ "LiteLLM Max Retries: 3" in error_str
+ ), f"Error message should show max retries: {error_str}"
@pytest.mark.asyncio
@@ -996,17 +994,15 @@ async def test_router_retry_num_retries_single_retry():
),
):
with patch.object(router, "_time_to_sleep_before_retry", return_value=0.01):
- try:
+ with pytest.raises(litellm.Timeout) as exc_info:
await router.acompletion(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Hello"}],
)
- pytest.fail("Expected exception to be raised")
- except litellm.Timeout as e:
- # With num_retries=1, we should attempt 1 retry
- assert (
- e.num_retries == 1
- ), f"Expected num_retries to be 1, got {e.num_retries}"
- assert (
- e.max_retries == 1
- ), f"Expected max_retries to be 1, got {e.max_retries}"
+ e = exc_info.value
+ assert (
+ e.num_retries == 1
+ ), f"Expected num_retries to be 1, got {e.num_retries}"
+ assert (
+ e.max_retries == 1
+ ), f"Expected max_retries to be 1, got {e.max_retries}"
diff --git a/tests/local_testing/test_rules.py b/tests/local_testing/test_rules.py
index 1af12c079fc..b075821e205 100644
--- a/tests/local_testing/test_rules.py
+++ b/tests/local_testing/test_rules.py
@@ -78,22 +78,17 @@ def my_post_call_rule_2(input: str):
# Test 2: Post-call rule
# commenting out of ci/cd since llm's have variable output which was causing our pipeline to fail erratically.
def test_post_call_rule():
- try:
- litellm.pre_call_rules = []
- litellm.post_call_rules = [my_post_call_rule]
- ### completion
- response = completion(
+ litellm.pre_call_rules = []
+ litellm.post_call_rules = [my_post_call_rule]
+
+ ### completion
+ with pytest.raises(Exception, match="This violates LiteLLM Proxy Rules. Response too short") as exc_info:
+ completion(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "say sorry"}],
max_tokens=2,
)
- pytest.fail(f"Completion call should have been failed. ")
- except Exception as e:
- print("Got exception", e)
- print(type(e))
- print(vars(e))
- assert e.message == "This violates LiteLLM Proxy Rules. Response too short"
- pass
+ assert exc_info.value.message == "This violates LiteLLM Proxy Rules. Response too short"
# print(f"MAKING ACOMPLETION CALL")
# litellm.set_verbose = True
### async completion
@@ -113,24 +108,19 @@ def test_post_call_rule():
def test_post_call_rule_streaming():
- try:
- litellm.pre_call_rules = []
- litellm.post_call_rules = [my_post_call_rule_2]
- ### completion
- response = completion(
- model="gpt-3.5-turbo",
- messages=[{"role": "user", "content": "say sorry"}],
- max_tokens=2,
- stream=True,
- )
- for chunk in response:
- print(f"chunk: {chunk}")
- pytest.fail(f"Completion call should have been failed. ")
- except Exception as e:
- print("Got exception", e)
- print(type(e))
- print(vars(e))
- assert "This violates LiteLLM Proxy Rules. Response too short" in e.message
+ litellm.pre_call_rules = []
+ litellm.post_call_rules = [my_post_call_rule_2]
+ ### completion
+ response = completion(
+ model="gpt-3.5-turbo",
+ messages=[{"role": "user", "content": "say sorry"}],
+ max_tokens=2,
+ stream=True,
+ )
+
+ with pytest.raises(Exception, match="This violates LiteLLM Proxy Rules. Response too short") as exc_info:
+ list(response)
+ assert "This violates LiteLLM Proxy Rules. Response too short" in exc_info.value.message
@pytest.mark.asyncio
diff --git a/tests/otel_tests/test_guardrails.py b/tests/otel_tests/test_guardrails.py
index ecc5d2eda5b..758b244d259 100644
--- a/tests/otel_tests/test_guardrails.py
+++ b/tests/otel_tests/test_guardrails.py
@@ -109,7 +109,7 @@ async def test_llm_guard_triggered():
- Assert that the guardrails applied are returned in the response headers
"""
async with aiohttp.ClientSession() as session:
- try:
+ with pytest.raises(Exception, match="Aporia detected and blocked PII") as exc_info:
response, headers = await chat_completion(
session,
"sk-1234",
@@ -122,10 +122,9 @@ async def test_llm_guard_triggered():
"aporia-pre-guard",
],
)
- pytest.fail("Should have thrown an exception")
- except Exception as e:
- print(e)
- assert "Aporia detected and blocked PII" in str(e)
+ e = exc_info.value
+ print(e)
+ assert "Aporia detected and blocked PII" in str(e)
@pytest.mark.asyncio
@@ -203,7 +202,7 @@ async def test_bedrock_guardrail_triggered():
- Assert that the guardrails applied are returned in the response headers
"""
async with aiohttp.ClientSession() as session:
- try:
+ with pytest.raises(Exception, match="Violated guardrail policy") as exc_info:
response, headers = await chat_completion(
session,
"sk-1234",
@@ -211,10 +210,9 @@ async def test_bedrock_guardrail_triggered():
messages=[{"role": "user", "content": "Hello do you like coffee?"}],
guardrails=["bedrock-pre-guard"],
)
- pytest.fail("Should have thrown an exception")
- except Exception as e:
- print(e)
- assert "Violated guardrail policy" in str(e)
+ e = exc_info.value
+ print(e)
+ assert "Violated guardrail policy" in str(e)
@pytest.mark.asyncio
@@ -224,7 +222,7 @@ async def test_custom_guardrail_during_call_triggered():
- Assert that the guardrails applied are returned in the response headers
"""
async with aiohttp.ClientSession() as session:
- try:
+ with pytest.raises(Exception, match="Guardrail failed words - `litellm` detected") as exc_info:
response, headers = await chat_completion(
session,
"sk-1234",
@@ -232,10 +230,9 @@ async def test_custom_guardrail_during_call_triggered():
messages=[{"role": "user", "content": f"Hello do you like litellm?"}],
guardrails=["custom-during-guard"],
)
- pytest.fail("Should have thrown an exception")
- except Exception as e:
- print(e)
- assert "Guardrail failed words - `litellm` detected" in str(e)
+ e = exc_info.value
+ print(e)
+ assert "Guardrail failed words - `litellm` detected" in str(e)
async def create_team(session, guardrails: Optional[List] = None):
diff --git a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
index 8ea95060953..439cdbdc777 100644
--- a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
+++ b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py
@@ -151,10 +151,8 @@ async def test_anthropic_messages_streaming_with_bad_request():
except Exception as e:
print("got exception", e)
print("vars", vars(e))
- if hasattr(e, "status_code"):
- assert getattr(e, "status_code") == 400
- else:
- assert isinstance(e, Exception)
+ if getattr(e, "status_code", 400) != 400:
+ raise
@pytest.mark.asyncio
@@ -188,10 +186,8 @@ async def test_anthropic_messages_router_streaming_with_bad_request():
except Exception as e:
print("got exception", e)
print("vars", vars(e))
- if hasattr(e, "status_code"):
- assert getattr(e, "status_code") == 400
- else:
- assert isinstance(e, Exception)
+ if getattr(e, "status_code", 400) != 400:
+ raise
@pytest.mark.asyncio
diff --git a/tests/proxy_admin_ui_tests/test_key_management.py b/tests/proxy_admin_ui_tests/test_key_management.py
index dec7404b3cf..d7bba09e6a1 100644
--- a/tests/proxy_admin_ui_tests/test_key_management.py
+++ b/tests/proxy_admin_ui_tests/test_key_management.py
@@ -197,15 +197,15 @@ async def test_regenerate_api_key(prisma_client):
return return_string.encode()
request.body = return_body_3
- try:
- result = await user_api_key_auth(
- request=request, api_key=f"Bearer {generated_key}"
- )
+ result = await user_api_key_auth(
+ request=request, api_key=f"Bearer {generated_key}"
+ )
+
+ with pytest.raises(Exception, match="Invalid proxy server token passed") as exc_info:
print(result)
- pytest.fail(f"This should have failed!. the key has been regenerated")
- except Exception as e:
- print("got expected exception", e)
- assert "Invalid proxy server token passed" in e.message
+ e = exc_info.value
+ print("got expected exception", e)
+ assert "Invalid proxy server token passed" in e.message
# Check that the regenerated key has the same spend, max_budget, models and key_alias
assert new_key.spend == spend, f"Expected spend {spend} but got {new_key.spend}"
diff --git a/tests/proxy_admin_ui_tests/test_role_based_access.py b/tests/proxy_admin_ui_tests/test_role_based_access.py
index 587a1048595..b5a076d0185 100644
--- a/tests/proxy_admin_ui_tests/test_role_based_access.py
+++ b/tests/proxy_admin_ui_tests/test_role_based_access.py
@@ -410,18 +410,17 @@ async def test_org_admin_create_user_team_wrong_org_permissions(prisma_client):
request.body = return_body
- try:
+ with pytest.raises(
+ Exception, match="You do not have a role within the selected organization. Passed organization_id"
+ ) as exc_info:
response = await user_api_key_auth(request=request, api_key="Bearer " + new_key)
- pytest.fail(
- f"This should have failed!. creating a user in an org without admins"
- )
- except Exception as e:
- print("got exception", e)
- print("exception.message", e.message)
- assert (
- "You do not have a role within the selected organization. Passed organization_id"
- in e.message
- )
+ e = exc_info.value
+ print("got exception", e)
+ print("exception.message", e.message)
+ assert (
+ "You do not have a role within the selected organization. Passed organization_id"
+ in e.message
+ )
# Create /team/new request in organization=org_without_admins -> expect fail
request = Request(scope={"type": "http"})
@@ -433,18 +432,9 @@ async def test_org_admin_create_user_team_wrong_org_permissions(prisma_client):
request.body = return_body
- try:
- response = await user_api_key_auth(request=request, api_key="Bearer " + new_key)
- pytest.fail(
- f"This should have failed!. Org Admin creating a team in an org where they are not an admin"
- )
- except Exception as e:
- print("got exception", e)
- print("exception.message", e.message)
- assert (
- "You do not have the required role to call" in e.message
- and org2_id in e.message
- )
+ with pytest.raises(Exception, match="You do not have the required role to call") as exc_info:
+ await user_api_key_auth(request=request, api_key="Bearer " + new_key)
+ assert org2_id in exc_info.value.message
@pytest.mark.asyncio
diff --git a/tests/proxy_unit_tests/test_auth_checks.py b/tests/proxy_unit_tests/test_auth_checks.py
index 947117bd882..3dc39969024 100644
--- a/tests/proxy_unit_tests/test_auth_checks.py
+++ b/tests/proxy_unit_tests/test_auth_checks.py
@@ -96,27 +96,21 @@ async def test_check_end_user_budget(customer_spend, customer_budget):
should_exceed = customer_spend > customer_budget
- try:
+ if not should_exceed:
await _check_end_user_budget(
end_user_obj=end_user_obj,
route="/v1/chat/completions",
)
- if should_exceed:
- pytest.fail(
- "Expected BudgetExceededError. Customer Spend={}, Customer Budget={}".format(
- customer_spend, customer_budget
- )
- )
- except litellm.BudgetExceededError as e:
- if not should_exceed:
- pytest.fail(
- "Unexpected BudgetExceededError. Customer Spend={}, Customer Budget={}, Error={}".format(
- customer_spend, customer_budget, str(e)
- )
- )
- # Verify the error has correct info
- assert e.current_cost == customer_spend
- assert e.max_budget == customer_budget
+ return
+
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _check_end_user_budget(
+ end_user_obj=end_user_obj,
+ route="/v1/chat/completions",
+ )
+ # Verify the error has correct info
+ assert exc_info.value.current_cost == customer_spend
+ assert exc_info.value.max_budget == customer_budget
@pytest.mark.parametrize(
@@ -450,13 +444,12 @@ async def test_is_valid_fallback_model():
except Exception as e:
pytest.fail(f"Expected is_valid_fallback_model to work, got exception: {e}")
- try:
+ with pytest.raises(Exception, match="Invalid") as exc_info:
await is_valid_fallback_model(
model="gpt-4o", llm_router=router, user_model=None
)
- pytest.fail("Expected is_valid_fallback_model to fail")
- except Exception as e:
- assert "Invalid" in str(e)
+ e = exc_info.value
+ assert "Invalid" in str(e)
@pytest.mark.parametrize(
@@ -506,23 +499,21 @@ async def test_virtual_key_max_budget_check(
proxy_logging_obj.budget_alerts = mock_budget_alert
- try:
+ if expect_budget_error:
+ with pytest.raises(litellm.BudgetExceededError) as exc_info:
+ await _virtual_key_max_budget_check(
+ valid_token=valid_token,
+ proxy_logging_obj=proxy_logging_obj,
+ user_obj=user_obj,
+ )
+ assert exc_info.value.current_cost == token_spend
+ assert exc_info.value.max_budget == max_budget
+ else:
await _virtual_key_max_budget_check(
valid_token=valid_token,
proxy_logging_obj=proxy_logging_obj,
user_obj=user_obj,
)
- if expect_budget_error:
- pytest.fail(
- f"Expected BudgetExceededError for spend={token_spend}, max_budget={max_budget}"
- )
- except litellm.BudgetExceededError as e:
- if not expect_budget_error:
- pytest.fail(
- f"Unexpected BudgetExceededError for spend={token_spend}, max_budget={max_budget}"
- )
- assert e.current_cost == token_spend
- assert e.max_budget == max_budget
await asyncio.sleep(1)
diff --git a/tests/proxy_unit_tests/test_key_generate_prisma.py b/tests/proxy_unit_tests/test_key_generate_prisma.py
index c845fb35774..e10d6be4427 100644
--- a/tests/proxy_unit_tests/test_key_generate_prisma.py
+++ b/tests/proxy_unit_tests/test_key_generate_prisma.py
@@ -305,27 +305,26 @@ def test_call_with_invalid_key(prisma_client):
# 2. Make a call with invalid key, expect it to fail
setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- generated_key = "sk-126666"
- bearer_token = "Bearer " + generated_key
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ generated_key = "sk-126666"
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"}, receive=None)
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"}, receive=None)
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("got result", result)
- pytest.fail(f"This should have failed!. IT's an invalid key")
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("got result", result)
+ pytest.fail(f"This should have failed!. IT's an invalid key")
+ with pytest.raises(Exception, match="Authentication Error, Invalid proxy server token passed") as exc_info:
asyncio.run(test())
- except Exception as e:
- print("Got Exception", e)
- print(e.message)
- assert "Authentication Error, Invalid proxy server token passed" in e.message
- pass
+ e = exc_info.value
+ print("Got Exception", e)
+ print(e.message)
+ assert "Authentication Error, Invalid proxy server token passed" in e.message
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -334,46 +333,46 @@ def test_call_with_invalid_model(prisma_client):
# 3. Make a call to a key with an invalid model - expect to fail
setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = NewUserRequest(models=["mistral"])
- key = await new_user(
- data=request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = NewUserRequest(models=["mistral"])
+ key = await new_user(
+ data=request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- bearer_token = "Bearer " + generated_key
+ generated_key = key.key
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- async def return_body():
- return b'{"model": "gemini-pro-vision"}'
+ async def return_body():
+ return b'{"model": "gemini-pro-vision"}'
- request.body = return_body
+ request.body = return_body
- # use generated key to auth in
- print(
- "Bearer token being sent to user_api_key_auth() - {}".format(
- bearer_token
- )
+ # use generated key to auth in
+ print(
+ "Bearer token being sent to user_api_key_auth() - {}".format(
+ bearer_token
)
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- pytest.fail(f"This should have failed!. IT's an invalid model")
+ )
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ pytest.fail(f"This should have failed!. IT's an invalid model")
+ with pytest.raises(ProxyException) as exc_info:
asyncio.run(test())
- except Exception as e:
- assert isinstance(e, ProxyException)
- assert e.type == ProxyErrorTypes.key_model_access_denied
- assert e.param == "model"
+ e = exc_info.value
+ assert isinstance(e, ProxyException)
+ assert e.type == ProxyErrorTypes.key_model_access_denied
+ assert e.param == "model"
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -491,82 +490,82 @@ def test_call_with_user_over_budget(prisma_client):
# 5. Make a call with a key over budget, expect to fail
setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = NewUserRequest(max_budget=0.00001)
- key = await new_user(
- data=request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = NewUserRequest(max_budget=0.00001)
+ key = await new_user(
+ data=request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- user_id = key.user_id
- bearer_token = "Bearer " + generated_key
+ generated_key = key.key
+ user_id = key.user_id
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
- # update spend using track_cost callback, make 2nd request, it should fail
- from litellm import Choices, Message, ModelResponse, Usage
- from litellm.proxy.proxy_server import _ProxyDBLogger
-
- proxy_db_logger = _ProxyDBLogger()
-
- resp = ModelResponse(
- id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
- choices=[
- Choices(
- finish_reason=None,
- index=0,
- message=Message(
- content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
- role="assistant",
- ),
- )
- ],
- model="gpt-35-turbo", # azure always has model written like this
- usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
- )
- await proxy_db_logger._PROXY_track_cost_callback(
- kwargs={
- "stream": False,
- "litellm_params": {
- "metadata": {
- "user_api_key": generated_key,
- "user_api_key_user_id": user_id,
- }
- },
- "response_cost": 0.00002,
+ # update spend using track_cost callback, make 2nd request, it should fail
+ from litellm import Choices, Message, ModelResponse, Usage
+ from litellm.proxy.proxy_server import _ProxyDBLogger
+
+ proxy_db_logger = _ProxyDBLogger()
+
+ resp = ModelResponse(
+ id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
+ choices=[
+ Choices(
+ finish_reason=None,
+ index=0,
+ message=Message(
+ content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
+ role="assistant",
+ ),
+ )
+ ],
+ model="gpt-35-turbo", # azure always has model written like this
+ usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
+ )
+ await proxy_db_logger._PROXY_track_cost_callback(
+ kwargs={
+ "stream": False,
+ "litellm_params": {
+ "metadata": {
+ "user_api_key": generated_key,
+ "user_api_key_user_id": user_id,
+ }
},
- completion_response=resp,
- start_time=datetime.now(),
- end_time=datetime.now(),
- )
- await asyncio.sleep(5)
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail("This should have failed!. They key crossed it's budget")
+ "response_cost": 0.00002,
+ },
+ completion_response=resp,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+ await asyncio.sleep(5)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
+ pytest.fail("This should have failed!. They key crossed it's budget")
+ with pytest.raises(ProxyException) as exc_info:
asyncio.run(test())
- except Exception as e:
- print("got an errror=", e)
- error_detail = e.message
- assert "ExceededBudget:" in error_detail
- assert isinstance(e, ProxyException)
- assert e.type == ProxyErrorTypes.budget_exceeded
- print(vars(e))
+ e = exc_info.value
+ print("got an errror=", e)
+ error_detail = e.message
+ assert "ExceededBudget:" in error_detail
+ assert isinstance(e, ProxyException)
+ assert e.type == ProxyErrorTypes.budget_exceeded
+ print(vars(e))
def test_end_user_cache_write_unit_test():
@@ -585,100 +584,100 @@ def test_call_with_end_user_over_budget(prisma_client):
setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
setattr(litellm, "max_end_user_budget", 0.00001)
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- user = f"ishaan {uuid.uuid4().hex}"
- request = NewCustomerRequest(
- user_id=user, max_budget=0.000001
- ) # create a key with no budget
- await new_end_user(
- request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ user = f"ishaan {uuid.uuid4().hex}"
+ request = NewCustomerRequest(
+ user_id=user, max_budget=0.000001
+ ) # create a key with no budget
+ await new_end_user(
+ request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
- bearer_token = "Bearer sk-1234"
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
+ bearer_token = "Bearer sk-1234"
- async def return_body():
- return_string = f'{{"model": "gemini-pro-vision", "user": "{user}"}}'
- # return string as bytes
- return return_string.encode()
+ async def return_body():
+ return_string = f'{{"model": "gemini-pro-vision", "user": "{user}"}}'
+ # return string as bytes
+ return return_string.encode()
- request.body = return_body
+ request.body = return_body
- result = await user_api_key_auth(request=request, api_key=bearer_token)
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
- # update spend using track_cost callback, make 2nd request, it should fail
- from litellm import Choices, Message, ModelResponse, Usage
- from litellm.proxy.proxy_server import _ProxyDBLogger
-
- proxy_db_logger = _ProxyDBLogger()
-
- resp = ModelResponse(
- id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
- choices=[
- Choices(
- finish_reason=None,
- index=0,
- message=Message(
- content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
- role="assistant",
- ),
- )
- ],
- model="gpt-35-turbo", # azure always has model written like this
- usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
- )
- await proxy_db_logger._PROXY_track_cost_callback(
- kwargs={
- "stream": False,
- "litellm_params": {
- "metadata": {
- "user_api_key": "sk-1234",
- "user_api_key_end_user_id": user,
- },
- "proxy_server_request": {
- "body": {
- "user": user,
- }
- },
+ # update spend using track_cost callback, make 2nd request, it should fail
+ from litellm import Choices, Message, ModelResponse, Usage
+ from litellm.proxy.proxy_server import _ProxyDBLogger
+
+ proxy_db_logger = _ProxyDBLogger()
+
+ resp = ModelResponse(
+ id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
+ choices=[
+ Choices(
+ finish_reason=None,
+ index=0,
+ message=Message(
+ content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
+ role="assistant",
+ ),
+ )
+ ],
+ model="gpt-35-turbo", # azure always has model written like this
+ usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
+ )
+ await proxy_db_logger._PROXY_track_cost_callback(
+ kwargs={
+ "stream": False,
+ "litellm_params": {
+ "metadata": {
+ "user_api_key": "sk-1234",
+ "user_api_key_end_user_id": user,
+ },
+ "proxy_server_request": {
+ "body": {
+ "user": user,
+ }
},
- "response_cost": 10,
},
- completion_response=resp,
- start_time=datetime.now(),
- end_time=datetime.now(),
- )
+ "response_cost": 10,
+ },
+ completion_response=resp,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
- await asyncio.sleep(10)
- await update_spend(
- prisma_client=prisma_client,
- db_writer_client=None,
- proxy_logging_obj=proxy_logging_obj,
- )
+ await asyncio.sleep(10)
+ await update_spend(
+ prisma_client=prisma_client,
+ db_writer_client=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail("This should have failed!. They key crossed it's budget")
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
+ pytest.fail("This should have failed!. They key crossed it's budget")
+ with pytest.raises(ProxyException) as exc_info:
asyncio.run(test())
- except Exception as e:
- print(f"raised error: {e}, traceback: {traceback.format_exc()}")
- # Handle DataError and other exceptions that don't have .message attribute
- error_detail = getattr(e, "message", str(e))
- assert "ExceededBudget: End User=" in error_detail
- assert "over budget" in error_detail
- assert isinstance(e, ProxyException)
- assert e.type == ProxyErrorTypes.budget_exceeded
- print(vars(e))
+ e = exc_info.value
+ print(f"raised error: {e}, traceback: {traceback.format_exc()}")
+ # Handle DataError and other exceptions that don't have .message attribute
+ error_detail = getattr(e, "message", str(e))
+ assert "ExceededBudget: End User=" in error_detail
+ assert "over budget" in error_detail
+ assert isinstance(e, ProxyException)
+ assert e.type == ProxyErrorTypes.budget_exceeded
+ print(vars(e))
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -699,85 +698,85 @@ def test_call_with_proxy_over_budget(prisma_client):
key="{}:spend".format(litellm_proxy_budget_name), value=0
)
setattr(litellm.proxy.proxy_server, "user_api_key_cache", user_api_key_cache)
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = NewUserRequest()
- key = await new_user(
- data=request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = NewUserRequest()
+ key = await new_user(
+ data=request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- user_id = key.user_id
- bearer_token = "Bearer " + generated_key
+ generated_key = key.key
+ user_id = key.user_id
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
- # update spend using track_cost callback, make 2nd request, it should fail
- from litellm import Choices, Message, ModelResponse, Usage
- from litellm.proxy.proxy_server import _ProxyDBLogger
-
- proxy_db_logger = _ProxyDBLogger()
-
- resp = ModelResponse(
- id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
- choices=[
- Choices(
- finish_reason=None,
- index=0,
- message=Message(
- content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
- role="assistant",
- ),
- )
- ],
- model="gpt-35-turbo", # azure always has model written like this
- usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
- )
- await proxy_db_logger._PROXY_track_cost_callback(
- kwargs={
- "stream": False,
- "litellm_params": {
- "metadata": {
- "user_api_key": generated_key,
- "user_api_key_user_id": user_id,
- }
- },
- "response_cost": 0.00002,
+ # update spend using track_cost callback, make 2nd request, it should fail
+ from litellm import Choices, Message, ModelResponse, Usage
+ from litellm.proxy.proxy_server import _ProxyDBLogger
+
+ proxy_db_logger = _ProxyDBLogger()
+
+ resp = ModelResponse(
+ id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
+ choices=[
+ Choices(
+ finish_reason=None,
+ index=0,
+ message=Message(
+ content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
+ role="assistant",
+ ),
+ )
+ ],
+ model="gpt-35-turbo", # azure always has model written like this
+ usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
+ )
+ await proxy_db_logger._PROXY_track_cost_callback(
+ kwargs={
+ "stream": False,
+ "litellm_params": {
+ "metadata": {
+ "user_api_key": generated_key,
+ "user_api_key_user_id": user_id,
+ }
},
- completion_response=resp,
- start_time=datetime.now(),
- end_time=datetime.now(),
- )
+ "response_cost": 0.00002,
+ },
+ completion_response=resp,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
- await asyncio.sleep(5)
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail(f"This should have failed!. They key crossed it's budget")
+ await asyncio.sleep(5)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
+ pytest.fail(f"This should have failed!. They key crossed it's budget")
+ with pytest.raises(ProxyException) as exc_info:
asyncio.run(test())
- except Exception as e:
- if hasattr(e, "message"):
- error_detail = e.message
- else:
- error_detail = traceback.format_exc()
- assert "Budget has been exceeded" in error_detail
- assert isinstance(e, ProxyException)
- assert e.type == ProxyErrorTypes.budget_exceeded
- print(vars(e))
+ e = exc_info.value
+ if hasattr(e, "message"):
+ error_detail = e.message
+ else:
+ error_detail = traceback.format_exc()
+ assert "Budget has been exceeded" in error_detail
+ assert isinstance(e, ProxyException)
+ assert e.type == ProxyErrorTypes.budget_exceeded
+ print(vars(e))
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -791,82 +790,82 @@ def test_call_with_user_over_budget_stream(prisma_client):
litellm.set_verbose = True
verbose_proxy_logger.setLevel(logging.DEBUG)
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = NewUserRequest(max_budget=0.00001)
- key = await new_user(
- data=request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = NewUserRequest(max_budget=0.00001)
+ key = await new_user(
+ data=request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- user_id = key.user_id
- bearer_token = "Bearer " + generated_key
+ generated_key = key.key
+ user_id = key.user_id
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
- # update spend using track_cost callback, make 2nd request, it should fail
- from litellm import Choices, Message, ModelResponse, Usage
- from litellm.proxy.proxy_server import _ProxyDBLogger
-
- proxy_db_logger = _ProxyDBLogger()
-
- resp = ModelResponse(
- id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
- choices=[
- Choices(
- finish_reason=None,
- index=0,
- message=Message(
- content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
- role="assistant",
- ),
- )
- ],
- model="gpt-35-turbo", # azure always has model written like this
- usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
- )
- await proxy_db_logger._PROXY_track_cost_callback(
- kwargs={
- "stream": True,
- "complete_streaming_response": resp,
- "litellm_params": {
- "metadata": {
- "user_api_key": generated_key,
- "user_api_key_user_id": user_id,
- }
- },
- "response_cost": 0.00002,
+ # update spend using track_cost callback, make 2nd request, it should fail
+ from litellm import Choices, Message, ModelResponse, Usage
+ from litellm.proxy.proxy_server import _ProxyDBLogger
+
+ proxy_db_logger = _ProxyDBLogger()
+
+ resp = ModelResponse(
+ id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
+ choices=[
+ Choices(
+ finish_reason=None,
+ index=0,
+ message=Message(
+ content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
+ role="assistant",
+ ),
+ )
+ ],
+ model="gpt-35-turbo", # azure always has model written like this
+ usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
+ )
+ await proxy_db_logger._PROXY_track_cost_callback(
+ kwargs={
+ "stream": True,
+ "complete_streaming_response": resp,
+ "litellm_params": {
+ "metadata": {
+ "user_api_key": generated_key,
+ "user_api_key_user_id": user_id,
+ }
},
- completion_response=ModelResponse(),
- start_time=datetime.now(),
- end_time=datetime.now(),
- )
- await asyncio.sleep(5)
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail("This should have failed!. They key crossed it's budget")
+ "response_cost": 0.00002,
+ },
+ completion_response=ModelResponse(),
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+ await asyncio.sleep(5)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
+ pytest.fail("This should have failed!. They key crossed it's budget")
+ with pytest.raises(ProxyException) as exc_info:
asyncio.run(test())
- except Exception as e:
- error_detail = e.message
- assert "ExceededBudget:" in error_detail
- assert isinstance(e, ProxyException)
- assert e.type == ProxyErrorTypes.budget_exceeded
- print(vars(e))
+ e = exc_info.value
+ error_detail = e.message
+ assert "ExceededBudget:" in error_detail
+ assert isinstance(e, ProxyException)
+ assert e.type == ProxyErrorTypes.budget_exceeded
+ print(vars(e))
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -894,84 +893,84 @@ def test_call_with_proxy_over_budget_stream(prisma_client):
litellm.set_verbose = True
verbose_proxy_logger.setLevel(logging.DEBUG)
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- ## CREATE PROXY + USER BUDGET ##
- # request = NewUserRequest(
- # max_budget=0.00001, user_id=litellm_proxy_budget_name
- # )
- request = NewUserRequest()
- key = await new_user(
- data=request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ ## CREATE PROXY + USER BUDGET ##
+ # request = NewUserRequest(
+ # max_budget=0.00001, user_id=litellm_proxy_budget_name
+ # )
+ request = NewUserRequest()
+ key = await new_user(
+ data=request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- user_id = key.user_id
- bearer_token = "Bearer " + generated_key
+ generated_key = key.key
+ user_id = key.user_id
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
- # update spend using track_cost callback, make 2nd request, it should fail
- from litellm import Choices, Message, ModelResponse, Usage
- from litellm.proxy.proxy_server import _ProxyDBLogger
-
- proxy_db_logger = _ProxyDBLogger()
-
- resp = ModelResponse(
- id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
- choices=[
- Choices(
- finish_reason=None,
- index=0,
- message=Message(
- content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
- role="assistant",
- ),
- )
- ],
- model="gpt-35-turbo", # azure always has model written like this
- usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
- )
- await proxy_db_logger._PROXY_track_cost_callback(
- kwargs={
- "stream": True,
- "complete_streaming_response": resp,
- "litellm_params": {
- "metadata": {
- "user_api_key": generated_key,
- "user_api_key_user_id": user_id,
- }
- },
- "response_cost": 0.00002,
+ # update spend using track_cost callback, make 2nd request, it should fail
+ from litellm import Choices, Message, ModelResponse, Usage
+ from litellm.proxy.proxy_server import _ProxyDBLogger
+
+ proxy_db_logger = _ProxyDBLogger()
+
+ resp = ModelResponse(
+ id="chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac",
+ choices=[
+ Choices(
+ finish_reason=None,
+ index=0,
+ message=Message(
+ content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
+ role="assistant",
+ ),
+ )
+ ],
+ model="gpt-35-turbo", # azure always has model written like this
+ usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
+ )
+ await proxy_db_logger._PROXY_track_cost_callback(
+ kwargs={
+ "stream": True,
+ "complete_streaming_response": resp,
+ "litellm_params": {
+ "metadata": {
+ "user_api_key": generated_key,
+ "user_api_key_user_id": user_id,
+ }
},
- completion_response=ModelResponse(),
- start_time=datetime.now(),
- end_time=datetime.now(),
- )
- await asyncio.sleep(5)
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail(f"This should have failed!. They key crossed it's budget")
+ "response_cost": 0.00002,
+ },
+ completion_response=ModelResponse(),
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+ await asyncio.sleep(5)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
+ pytest.fail(f"This should have failed!. They key crossed it's budget")
+ with pytest.raises(Exception, match="Budget has been exceeded") as exc_info:
asyncio.run(test())
- except Exception as e:
- error_detail = e.message
- assert "Budget has been exceeded" in error_detail
- print(vars(e))
+ e = exc_info.value
+ error_detail = e.message
+ assert "Budget has been exceeded" in error_detail
+ print(vars(e))
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -1020,40 +1019,38 @@ def test_generate_and_call_with_expired_key(prisma_client):
setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = NewUserRequest(duration="0s")
- key = await new_user(
- data=request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = NewUserRequest(duration="0s")
+ key = await new_user(
+ data=request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- bearer_token = "Bearer " + generated_key
+ generated_key = key.key
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail("This should have failed!. It's an expired key")
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
+ pytest.fail("This should have failed!. It's an expired key")
+ with pytest.raises(Exception, match="Authentication Error") as exc_info:
asyncio.run(test())
- except Exception as e:
- print("Got Exception", e)
- print(e.message)
- assert "Authentication Error" in e.message
- assert e.type == ProxyErrorTypes.expired_key
-
- pass
+ e = exc_info.value
+ print("Got Exception", e)
+ print(e.message)
+ assert "Authentication Error" in e.message
+ assert e.type == ProxyErrorTypes.expired_key
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -1498,9 +1495,10 @@ def test_key_generate_with_custom_auth(prisma_client):
try:
async def test():
- try:
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = GenerateKeyRequest()
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = GenerateKeyRequest()
+
+ with pytest.raises(Exception, match="This violates LiteLLM Proxy Rules. No team id provided.") as exc_info:
key = await generate_key_fn(
request,
user_api_key_dict=UserAPIKeyAuth(
@@ -1509,16 +1507,14 @@ def test_key_generate_with_custom_auth(prisma_client):
user_id="1234",
),
)
- pytest.fail(f"Expected an exception. Got {key}")
- except Exception as e:
- # this should fail
- print("Got Exception", e)
- print(e.message)
- print("First request failed!. This is expected")
- assert (
- "This violates LiteLLM Proxy Rules. No team id provided."
- in e.message
- )
+ e = exc_info.value
+ print("Got Exception", e)
+ print(e.message)
+ print("First request failed!. This is expected")
+ assert (
+ "This violates LiteLLM Proxy Rules. No team id provided."
+ in e.message
+ )
request_2 = GenerateKeyRequest(
team_id="[email protected]",
@@ -1550,117 +1546,116 @@ def test_call_with_key_over_budget(prisma_client):
# 12. Make a call with a key over budget, expect to fail
setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = GenerateKeyRequest(max_budget=0.00001)
- key = await generate_key_fn(
- request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = GenerateKeyRequest(max_budget=0.00001)
+ key = await generate_key_fn(
+ request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- user_id = key.user_id
- bearer_token = "Bearer " + generated_key
+ generated_key = key.key
+ user_id = key.user_id
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
- # update spend using track_cost callback, make 2nd request, it should fail
- from litellm import Choices, Message, ModelResponse, Usage
- from litellm.caching.caching import Cache
- from litellm.proxy.proxy_server import _ProxyDBLogger
-
- proxy_db_logger = _ProxyDBLogger()
-
- litellm.cache = Cache()
- import time
- from litellm._uuid import uuid
-
- request_id = f"chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac{uuid.uuid4()}"
-
- resp = ModelResponse(
- id=request_id,
- choices=[
- Choices(
- finish_reason=None,
- index=0,
- message=Message(
- content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
- role="assistant",
- ),
- )
- ],
- model="gpt-35-turbo", # azure always has model written like this
- usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
- )
- await proxy_db_logger._PROXY_track_cost_callback(
- kwargs={
- "model": "chatgpt-v-3",
- "stream": False,
- "litellm_params": {
- "metadata": {
- "user_api_key": hash_token(generated_key),
- "user_api_key_user_id": user_id,
- }
- },
- "response_cost": 0.00002,
+ # update spend using track_cost callback, make 2nd request, it should fail
+ from litellm import Choices, Message, ModelResponse, Usage
+ from litellm.caching.caching import Cache
+ from litellm.proxy.proxy_server import _ProxyDBLogger
+
+ proxy_db_logger = _ProxyDBLogger()
+
+ litellm.cache = Cache()
+ import time
+ from litellm._uuid import uuid
+
+ request_id = f"chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac{uuid.uuid4()}"
+
+ resp = ModelResponse(
+ id=request_id,
+ choices=[
+ Choices(
+ finish_reason=None,
+ index=0,
+ message=Message(
+ content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
+ role="assistant",
+ ),
+ )
+ ],
+ model="gpt-35-turbo", # azure always has model written like this
+ usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
+ )
+ await proxy_db_logger._PROXY_track_cost_callback(
+ kwargs={
+ "model": "chatgpt-v-3",
+ "stream": False,
+ "litellm_params": {
+ "metadata": {
+ "user_api_key": hash_token(generated_key),
+ "user_api_key_user_id": user_id,
+ }
},
- completion_response=resp,
- start_time=datetime.now(),
- end_time=datetime.now(),
- )
- await update_spend(
- prisma_client=prisma_client,
- db_writer_client=None,
- proxy_logging_obj=proxy_logging_obj,
- )
- # test spend_log was written and we can read it
- spend_logs = await view_spend_logs(
- request_id=request_id,
- user_api_key_dict=UserAPIKeyAuth(api_key=generated_key),
- )
+ "response_cost": 0.00002,
+ },
+ completion_response=resp,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+ await update_spend(
+ prisma_client=prisma_client,
+ db_writer_client=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ # test spend_log was written and we can read it
+ spend_logs = await view_spend_logs(
+ request_id=request_id,
+ user_api_key_dict=UserAPIKeyAuth(api_key=generated_key),
+ )
- print("read spend logs", spend_logs)
- assert len(spend_logs) == 1
+ print("read spend logs", spend_logs)
+ assert len(spend_logs) == 1
- spend_log = spend_logs[0]
+ spend_log = spend_logs[0]
- assert spend_log.request_id == request_id
- assert spend_log.spend == float("2e-05")
- assert spend_log.model == "chatgpt-v-3"
- assert (
- spend_log.cache_key
- == "509ba0554a7129ae4f4fd13d11c141acce5549bb6aaf1f629ed543101615658e"
- )
+ assert spend_log.request_id == request_id
+ assert spend_log.spend == float("2e-05")
+ assert spend_log.model == "chatgpt-v-3"
+ assert (
+ spend_log.cache_key
+ == "509ba0554a7129ae4f4fd13d11c141acce5549bb6aaf1f629ed543101615658e"
+ )
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail("This should have failed!. They key crossed it's budget")
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
+ pytest.fail("This should have failed!. They key crossed it's budget")
+ with pytest.raises(ProxyException) as exc_info:
asyncio.run(test())
- except Exception as e:
- # print(f"Error - {str(e)}")
- traceback.print_exc()
- if hasattr(e, "message"):
- error_detail = e.message
- else:
- error_detail = str(e)
- assert "Budget has been exceeded" in error_detail
- assert isinstance(e, ProxyException)
- assert e.type == ProxyErrorTypes.budget_exceeded
- print(vars(e))
+ e = exc_info.value
+ traceback.print_exc()
+ if hasattr(e, "message"):
+ error_detail = e.message
+ else:
+ error_detail = str(e)
+ assert "Budget has been exceeded" in error_detail
+ assert isinstance(e, ProxyException)
+ assert e.type == ProxyErrorTypes.budget_exceeded
+ print(vars(e))
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -1670,122 +1665,121 @@ def test_call_with_key_over_budget_no_cache(prisma_client):
# Related to this: https://github.com/BerriAI/litellm/issues/3920
setattr(litellm.proxy.proxy_server, "prisma_client", prisma_client)
setattr(litellm.proxy.proxy_server, "master_key", "sk-1234")
- try:
- async def test():
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = GenerateKeyRequest(max_budget=0.00001)
- key = await generate_key_fn(
- request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ async def test():
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = GenerateKeyRequest(max_budget=0.00001)
+ key = await generate_key_fn(
+ request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- user_id = key.user_id
- bearer_token = "Bearer " + generated_key
+ generated_key = key.key
+ user_id = key.user_id
+ bearer_token = "Bearer " + generated_key
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
- # update spend using track_cost callback, make 2nd request, it should fail
- from litellm.proxy.proxy_server import _ProxyDBLogger
- from litellm.proxy.proxy_server import user_api_key_cache
+ # update spend using track_cost callback, make 2nd request, it should fail
+ from litellm.proxy.proxy_server import _ProxyDBLogger
+ from litellm.proxy.proxy_server import user_api_key_cache
- user_api_key_cache.in_memory_cache.cache_dict = {}
- setattr(litellm.proxy.proxy_server, "proxy_batch_write_at", 1)
-
- from litellm import Choices, Message, ModelResponse, Usage
- from litellm.caching.caching import Cache
-
- litellm.cache = Cache()
- import time
- from litellm._uuid import uuid
-
- request_id = f"chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac{uuid.uuid4()}"
-
- resp = ModelResponse(
- id=request_id,
- choices=[
- Choices(
- finish_reason=None,
- index=0,
- message=Message(
- content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
- role="assistant",
- ),
- )
- ],
- model="gpt-35-turbo", # azure always has model written like this
- usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
- )
- proxy_db_logger = _ProxyDBLogger()
- await proxy_db_logger._PROXY_track_cost_callback(
- kwargs={
- "model": "chatgpt-v-3",
- "stream": False,
- "litellm_params": {
- "metadata": {
- "user_api_key": hash_token(generated_key),
- "user_api_key_user_id": user_id,
- }
- },
- "response_cost": 0.00002,
+ user_api_key_cache.in_memory_cache.cache_dict = {}
+ setattr(litellm.proxy.proxy_server, "proxy_batch_write_at", 1)
+
+ from litellm import Choices, Message, ModelResponse, Usage
+ from litellm.caching.caching import Cache
+
+ litellm.cache = Cache()
+ import time
+ from litellm._uuid import uuid
+
+ request_id = f"chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac{uuid.uuid4()}"
+
+ resp = ModelResponse(
+ id=request_id,
+ choices=[
+ Choices(
+ finish_reason=None,
+ index=0,
+ message=Message(
+ content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
+ role="assistant",
+ ),
+ )
+ ],
+ model="gpt-35-turbo", # azure always has model written like this
+ usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
+ )
+ proxy_db_logger = _ProxyDBLogger()
+ await proxy_db_logger._PROXY_track_cost_callback(
+ kwargs={
+ "model": "chatgpt-v-3",
+ "stream": False,
+ "litellm_params": {
+ "metadata": {
+ "user_api_key": hash_token(generated_key),
+ "user_api_key_user_id": user_id,
+ }
},
- completion_response=resp,
- start_time=datetime.now(),
- end_time=datetime.now(),
- )
- await asyncio.sleep(10)
- await update_spend(
- prisma_client=prisma_client,
- db_writer_client=None,
- proxy_logging_obj=proxy_logging_obj,
- )
- # test spend_log was written and we can read it
- spend_logs = await view_spend_logs(
- request_id=request_id,
- user_api_key_dict=UserAPIKeyAuth(api_key=generated_key),
- )
+ "response_cost": 0.00002,
+ },
+ completion_response=resp,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+ await asyncio.sleep(10)
+ await update_spend(
+ prisma_client=prisma_client,
+ db_writer_client=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ # test spend_log was written and we can read it
+ spend_logs = await view_spend_logs(
+ request_id=request_id,
+ user_api_key_dict=UserAPIKeyAuth(api_key=generated_key),
+ )
- print("read spend logs", spend_logs)
- assert len(spend_logs) == 1
+ print("read spend logs", spend_logs)
+ assert len(spend_logs) == 1
- spend_log = spend_logs[0]
+ spend_log = spend_logs[0]
- assert spend_log.request_id == request_id
- assert spend_log.spend == float("2e-05")
- assert spend_log.model == "chatgpt-v-3"
- assert (
- spend_log.cache_key
- == "509ba0554a7129ae4f4fd13d11c141acce5549bb6aaf1f629ed543101615658e"
- )
+ assert spend_log.request_id == request_id
+ assert spend_log.spend == float("2e-05")
+ assert spend_log.model == "chatgpt-v-3"
+ assert (
+ spend_log.cache_key
+ == "509ba0554a7129ae4f4fd13d11c141acce5549bb6aaf1f629ed543101615658e"
+ )
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail(f"This should have failed!. They key crossed it's budget")
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
+ pytest.fail(f"This should have failed!. They key crossed it's budget")
+ with pytest.raises(ProxyException) as exc_info:
asyncio.run(test())
- except Exception as e:
- # print(f"Error - {str(e)}")
- traceback.print_exc()
- if hasattr(e, "message"):
- error_detail = e.message
- else:
- error_detail = str(e)
- assert "Budget has been exceeded" in error_detail
- assert isinstance(e, ProxyException)
- assert e.type == ProxyErrorTypes.budget_exceeded
- print(vars(e))
+ e = exc_info.value
+ traceback.print_exc()
+ if hasattr(e, "message"):
+ error_detail = e.message
+ else:
+ error_detail = str(e)
+ assert "Budget has been exceeded" in error_detail
+ assert isinstance(e, ProxyException)
+ assert e.type == ProxyErrorTypes.budget_exceeded
+ print(vars(e))
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -1813,132 +1807,106 @@ async def test_aasync_call_with_key_over_model_budget(
# This ensures the budget limiter's cache is shared between the callback and auth checks
from litellm.proxy.proxy_server import model_max_budget_limiter
- try:
- # set budget for chatgpt-v-3 to 0.000001, expect the next request to fail
- model_max_budget = {
- "gpt-4o-mini": {
- "budget_limit": "0.000001",
- "time_period": "1d",
- },
- "gpt-4o": {
- "budget_limit": "200",
- "time_period": "30d",
- },
- }
+ # set budget for chatgpt-v-3 to 0.000001, expect the next request to fail
+ model_max_budget = {
+ "gpt-4o-mini": {
+ "budget_limit": "0.000001",
+ "time_period": "1d",
+ },
+ "gpt-4o": {
+ "budget_limit": "200",
+ "time_period": "30d",
+ },
+ }
+
+ request = GenerateKeyRequest(
+ max_budget=100000, # the key itself has a very high budget
+ model_max_budget=model_max_budget,
+ )
+ key = await generate_key_fn(
+ request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
+
+ generated_key = key.key
+ user_id = key.user_id
+ bearer_token = "Bearer " + generated_key
- request = GenerateKeyRequest(
- max_budget=100000, # the key itself has a very high budget
- model_max_budget=model_max_budget,
- )
- key = await generate_key_fn(
- request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- generated_key = key.key
- user_id = key.user_id
- bearer_token = "Bearer " + generated_key
+ async def return_body():
+ request_str = f'{{"model": "{request_model}"}}' # Added extra curly braces to escape JSON
+ return request_str.encode()
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ request.body = return_body
- async def return_body():
- request_str = f'{{"model": "{request_model}"}}' # Added extra curly braces to escape JSON
- return request_str.encode()
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
- request.body = return_body
+ # update spend using track_cost callback, make 2nd request, it should fail
+ response = await litellm.acompletion(
+ model=request_model,
+ messages=[{"role": "user", "content": "Hello, how are you?"}],
+ metadata={
+ "user_api_key": hash_token(generated_key),
+ "user_api_key_model_max_budget": model_max_budget,
+ },
+ )
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
+ # Manually trigger the budget limiter callback to avoid event loop issues with logging worker
+ # This ensures the spend is tracked immediately without relying on async background tasks
+ import time
- # update spend using track_cost callback, make 2nd request, it should fail
- response = await litellm.acompletion(
- model=request_model,
- messages=[{"role": "user", "content": "Hello, how are you?"}],
- metadata={
+ # Create a mock kwargs object that the callback expects (StandardLoggingPayload is a TypedDict, so use dict)
+ mock_kwargs = {
+ "standard_logging_object": {
+ "response_cost": getattr(response, "_hidden_params", {}).get(
+ "response_cost", 0.0001
+ ), # Use actual cost or small fallback
+ "model": request_model,
+ "metadata": {
+ "user_api_key_hash": hash_token(generated_key),
+ },
+ },
+ "litellm_params": {
+ "metadata": {
"user_api_key": hash_token(generated_key),
"user_api_key_model_max_budget": model_max_budget,
- },
- )
-
- # Manually trigger the budget limiter callback to avoid event loop issues with logging worker
- # This ensures the spend is tracked immediately without relying on async background tasks
- import time
-
- # Create a mock kwargs object that the callback expects (StandardLoggingPayload is a TypedDict, so use dict)
- mock_kwargs = {
- "standard_logging_object": {
- "response_cost": getattr(response, "_hidden_params", {}).get(
- "response_cost", 0.0001
- ), # Use actual cost or small fallback
- "model": request_model,
- "metadata": {
- "user_api_key_hash": hash_token(generated_key),
- },
- },
- "litellm_params": {
- "metadata": {
- "user_api_key": hash_token(generated_key),
- "user_api_key_model_max_budget": model_max_budget,
- }
- },
- }
+ }
+ },
+ }
- # Call the budget limiter callback directly to ensure spend is recorded
- await model_max_budget_limiter.async_log_success_event(
- kwargs=mock_kwargs,
- response_obj=response,
- start_time=time.time(),
- end_time=time.time(),
- )
+ # Call the budget limiter callback directly to ensure spend is recorded
+ await model_max_budget_limiter.async_log_success_event(
+ kwargs=mock_kwargs,
+ response_obj=response,
+ start_time=time.time(),
+ end_time=time.time(),
+ )
- # Small delay to ensure cache write completes
- await asyncio.sleep(0.5)
+ # Small delay to ensure cache write completes
+ await asyncio.sleep(0.5)
- # use generated key to auth in
+ # use generated key to auth in
+ if should_pass:
result = await user_api_key_auth(request=request, api_key=bearer_token)
- if should_pass is True:
- print(
- f"Passed request for model={request_model}, model_max_budget={model_max_budget}"
- )
- return
- print("result from user auth with new key", result)
- pytest.fail("This should have failed!. They key crossed it's budget")
- except Exception as e:
- # print(f"Error - {str(e)}")
print(
- f"Failed request for model={request_model}, model_max_budget={model_max_budget}"
+ f"Passed request for model={request_model}, model_max_budget={model_max_budget}"
)
- assert (
- should_pass is False
- ), f"This should have failed!. They key crossed it's budget for model={request_model}. {e}"
- traceback.print_exc()
-
- # Handle both ProxyException and other exceptions (like RuntimeError from event loop)
- if isinstance(e, ProxyException):
- error_detail = e.message
- assert f"exceeded budget for model={request_model}" in error_detail
- assert e.type == ProxyErrorTypes.budget_exceeded
- print(vars(e))
- else:
- # For RuntimeError or other exceptions, check the string representation
- error_detail = str(e)
- # If it's an event loop error, the test should still be considered as passing
- # since the budget check likely happened before the event loop issue
- if (
- "event loop" in error_detail.lower()
- or "RuntimeError" in type(e).__name__
- ):
- print(f"Test passed with event loop cleanup error: {error_detail}")
- else:
- # Re-raise if it's an unexpected exception
- raise
+ print("result from user auth with new key", result)
+ return
+
+ with pytest.raises(ProxyException) as exc_info:
+ await user_api_key_auth(request=request, api_key=bearer_token)
+ assert f"exceeded budget for model={request_model}" in exc_info.value.message
+ assert exc_info.value.type == ProxyErrorTypes.budget_exceeded
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -2039,90 +2007,89 @@ async def test_call_with_key_over_budget_stream(prisma_client):
litellm.set_verbose = True
verbose_proxy_logger.setLevel(logging.DEBUG)
- try:
- await litellm.proxy.proxy_server.prisma_client.connect()
- request = GenerateKeyRequest(max_budget=0.00001)
- key = await generate_key_fn(
- request,
- user_api_key_dict=UserAPIKeyAuth(
- user_role=LitellmUserRoles.PROXY_ADMIN,
- api_key="sk-1234",
- user_id="1234",
- ),
- )
- print(key)
+ await litellm.proxy.proxy_server.prisma_client.connect()
+ request = GenerateKeyRequest(max_budget=0.00001)
+ key = await generate_key_fn(
+ request,
+ user_api_key_dict=UserAPIKeyAuth(
+ user_role=LitellmUserRoles.PROXY_ADMIN,
+ api_key="sk-1234",
+ user_id="1234",
+ ),
+ )
+ print(key)
- generated_key = key.key
- user_id = key.user_id
- bearer_token = "Bearer " + generated_key
- print(f"generated_key: {generated_key}")
- request = Request(scope={"type": "http"})
- request._url = URL(url="/chat/completions")
+ generated_key = key.key
+ user_id = key.user_id
+ bearer_token = "Bearer " + generated_key
+ print(f"generated_key: {generated_key}")
+ request = Request(scope={"type": "http"})
+ request._url = URL(url="/chat/completions")
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
+ print("result from user auth with new key", result)
- # update spend using track_cost callback, make 2nd request, it should fail
- import time
- from litellm._uuid import uuid
+ # update spend using track_cost callback, make 2nd request, it should fail
+ import time
+ from litellm._uuid import uuid
- from litellm import Choices, Message, ModelResponse, Usage
- from litellm.proxy.proxy_server import _ProxyDBLogger
+ from litellm import Choices, Message, ModelResponse, Usage
+ from litellm.proxy.proxy_server import _ProxyDBLogger
- proxy_db_logger = _ProxyDBLogger()
+ proxy_db_logger = _ProxyDBLogger()
- request_id = f"chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac{uuid.uuid4()}"
- resp = ModelResponse(
- id=request_id,
- choices=[
- Choices(
- finish_reason=None,
- index=0,
- message=Message(
- content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
- role="assistant",
- ),
- )
- ],
- model="gpt-35-turbo", # azure always has model written like this
- usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
- )
- await proxy_db_logger._PROXY_track_cost_callback(
- kwargs={
- "call_type": "acompletion",
- "model": "sagemaker-chatgpt-v-3",
- "stream": True,
- "complete_streaming_response": resp,
- "litellm_params": {
- "metadata": {
- "user_api_key": hash_token(generated_key),
- "user_api_key_user_id": user_id,
- }
- },
- "response_cost": 0.00005,
+ request_id = f"chatcmpl-e41836bb-bb8b-4df2-8e70-8f3e160155ac{uuid.uuid4()}"
+ resp = ModelResponse(
+ id=request_id,
+ choices=[
+ Choices(
+ finish_reason=None,
+ index=0,
+ message=Message(
+ content=" Sure! Here is a short poem about the sky:\n\nA canvas of blue, a",
+ role="assistant",
+ ),
+ )
+ ],
+ model="gpt-35-turbo", # azure always has model written like this
+ usage=Usage(prompt_tokens=210, completion_tokens=200, total_tokens=410),
+ )
+ await proxy_db_logger._PROXY_track_cost_callback(
+ kwargs={
+ "call_type": "acompletion",
+ "model": "sagemaker-chatgpt-v-3",
+ "stream": True,
+ "complete_streaming_response": resp,
+ "litellm_params": {
+ "metadata": {
+ "user_api_key": hash_token(generated_key),
+ "user_api_key_user_id": user_id,
+ }
},
- completion_response=resp,
- start_time=datetime.now(),
- end_time=datetime.now(),
- )
- await update_spend(
- prisma_client=prisma_client,
- db_writer_client=None,
- proxy_logging_obj=proxy_logging_obj,
- )
- # use generated key to auth in
- result = await user_api_key_auth(request=request, api_key=bearer_token)
- print("result from user auth with new key", result)
- pytest.fail(f"This should have failed!. They key crossed it's budget")
+ "response_cost": 0.00005,
+ },
+ completion_response=resp,
+ start_time=datetime.now(),
+ end_time=datetime.now(),
+ )
+ await update_spend(
+ prisma_client=prisma_client,
+ db_writer_client=None,
+ proxy_logging_obj=proxy_logging_obj,
+ )
+ # use generated key to auth in
+ result = await user_api_key_auth(request=request, api_key=bearer_token)
- except Exception as e:
- print("Got Exception", e)
- # Handle DataError and other exceptions that don't have .message attribute
- error_detail = getattr(e, "message", str(e))
- assert "Budget has been exceeded" in error_detail
+ with pytest.raises(Exception, match="Budget has been exceeded") as exc_info:
+ print("result from user auth with new key", result)
+ e = exc_info.value
+ print("Got Exception", e)
+ # Handle DataError and other exceptions that don't have .message attribute
+ error_detail = getattr(e, "message", str(e))
+ assert "Budget has been exceeded" in error_detail
- print(vars(e))
+ print(vars(e))
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -2309,12 +2276,12 @@ async def test_upperbound_key_param_larger_budget(prisma_client):
max_budget=0.001, budget_duration="1m"
)
await litellm.proxy.proxy_server.prisma_client.connect()
- try:
- request = GenerateKeyRequest(
- max_budget=200000,
- budget_duration="30d",
- )
- key = await generate_key_fn(
+ request = GenerateKeyRequest(
+ max_budget=200000,
+ budget_duration="30d",
+ )
+ with pytest.raises(ProxyException) as exc_info:
+ await generate_key_fn(
request,
user_api_key_dict=UserAPIKeyAuth(
user_role=LitellmUserRoles.PROXY_ADMIN,
@@ -2322,9 +2289,7 @@ async def test_upperbound_key_param_larger_budget(prisma_client):
user_id="1234",
),
)
- # print(result)
- except Exception as e:
- assert e.code == str(400)
+ assert exc_info.value.code == str(400)
@pytest.mark.asyncio()
@@ -2336,12 +2301,12 @@ async def test_upperbound_key_param_larger_duration(prisma_client):
max_budget=100, duration="14d"
)
await litellm.proxy.proxy_server.prisma_client.connect()
- try:
- request = GenerateKeyRequest(
- max_budget=10,
- duration="30d",
- )
- key = await generate_key_fn(
+ request = GenerateKeyRequest(
+ max_budget=10,
+ duration="30d",
+ )
+ with pytest.raises(ProxyException) as exc_info:
+ await generate_key_fn(
request,
user_api_key_dict=UserAPIKeyAuth(
user_role=LitellmUserRoles.PROXY_ADMIN,
@@ -2349,10 +2314,7 @@ async def test_upperbound_key_param_larger_duration(prisma_client):
user_id="1234",
),
)
- pytest.fail("Expected this to fail but it passed")
- # print(result)
- except Exception as e:
- assert e.code == str(400)
+ assert exc_info.value.code == str(400)
@pytest.mark.asyncio()
@@ -2461,34 +2423,31 @@ async def test_user_api_key_auth(prisma_client):
request = Request(scope={"type": "http"})
request._url = URL(url="/chat/completions")
# Test case: No API Key passed in
- try:
+ with pytest.raises(ProxyException) as exc_info:
await user_api_key_auth(request, api_key=None)
- pytest.fail(f"This should have failed!. IT's an invalid key")
- except ProxyException as exc:
- print(exc.message)
- assert exc.message == "Authentication Error, No api key passed in."
+ exc = exc_info.value
+ print(exc.message)
+ assert exc.message == "Authentication Error, No api key passed in."
# Test case: Malformed API Key (missing 'Bearer ' prefix)
- try:
+ with pytest.raises(ProxyException) as exc_info:
await user_api_key_auth(request, api_key="my_token")
- pytest.fail(f"This should have failed!. IT's an invalid key")
- except ProxyException as exc:
- print(exc.message)
- assert (
- exc.message
- == "Authentication Error, Malformed API Key passed in. Ensure Key has `Bearer ` prefix."
- )
+ exc = exc_info.value
+ print(exc.message)
+ assert (
+ exc.message
+ == "Authentication Error, Malformed API Key passed in. Ensure Key has `Bearer ` prefix."
+ )
# Test case: User passes empty string API Key
- try:
+ with pytest.raises(ProxyException) as exc_info:
await user_api_key_auth(request, api_key="")
- pytest.fail(f"This should have failed!. IT's an invalid key")
- except ProxyException as exc:
- print(exc.message)
- assert (
- "Authentication Error, Malformed API Key passed in. Ensure Key has `Bearer ` prefix."
- in exc.message
- )
+ exc = exc_info.value
+ print(exc.message)
+ assert (
+ "Authentication Error, Malformed API Key passed in. Ensure Key has `Bearer ` prefix."
+ in exc.message
+ )
@pytest.mark.asyncio
@@ -2772,15 +2731,16 @@ async def test_reset_spend_authentication(prisma_client):
generate_key = "Bearer " + _response.key
- try:
+ with pytest.raises(
+ Exception, match="Tried to access route=/global/spend/reset, which is only for MASTER KEY"
+ ) as exc_info:
await user_api_key_auth(request=request, api_key=generate_key)
- pytest.fail(f"This should have failed!. IT's an expired key")
- except Exception as e:
- print("Got Exception", e)
- assert (
- "Tried to access route=/global/spend/reset, which is only for MASTER KEY"
- in e.message
- )
+ e = exc_info.value
+ print("Got Exception", e)
+ assert (
+ "Tried to access route=/global/spend/reset, which is only for MASTER KEY"
+ in e.message
+ )
# Test 3 - Non-Master Key with role == LitellmUserRoles.PROXY_ADMIN or admin
_response = await new_user(
@@ -2797,15 +2757,16 @@ async def test_reset_spend_authentication(prisma_client):
generate_key = "Bearer " + _response.key
- try:
+ with pytest.raises(
+ Exception, match="Tried to access route=/global/spend/reset, which is only for MASTER KEY"
+ ) as exc_info:
await user_api_key_auth(request=request, api_key=generate_key)
- pytest.fail(f"This should have failed!. IT's an expired key")
- except Exception as e:
- print("Got Exception", e)
- assert (
- "Tried to access route=/global/spend/reset, which is only for MASTER KEY"
- in e.message
- )
+ e = exc_info.value
+ print("Got Exception", e)
+ assert (
+ "Tried to access route=/global/spend/reset, which is only for MASTER KEY"
+ in e.message
+ )
@pytest.mark.skip(reason="Requires reliable external DB connection (prisma).")
@@ -3091,15 +3052,13 @@ async def test_custom_api_key_header_name(prisma_client):
"headers": [],
}
)
- try:
+ with pytest.raises(Exception, match="Malformed API Key passed in. Ensure Key has `Bearer ` prefix") as exc_info:
result = await user_api_key_auth(request=request, api_key="Bearer sk-1234")
- pytest.fail(f"This should have failed!. invalid Auth on this request")
- except Exception as e:
- print("failed with error", e)
- assert (
- "Malformed API Key passed in. Ensure Key has `Bearer ` prefix" in e.message
- )
- pass
+ e = exc_info.value
+ print("failed with error", e)
+ assert (
+ "Malformed API Key passed in. Ensure Key has `Bearer ` prefix" in e.message
+ )
# this should pass because X-Litellm-Key is valid
@@ -3402,14 +3361,13 @@ async def test_team_access_groups(prisma_client):
print(
"Bearer token being sent to user_api_key_auth() - {}".format(bearer_token)
)
- try:
+ with pytest.raises(ProxyException) as exc_info:
result = await user_api_key_auth(request=request, api_key=bearer_token)
- pytest.fail(f"This should have failed!. IT's an invalid model")
- except Exception as e:
- print("got exception", e)
- assert isinstance(e, ProxyException)
- assert e.type == ProxyErrorTypes.team_model_access_denied
- assert e.param == "model"
+ e = exc_info.value
+ print("got exception", e)
+ assert isinstance(e, ProxyException)
+ assert e.type == ProxyErrorTypes.team_model_access_denied
+ assert e.param == "model"
@pytest.mark.asyncio()
@@ -3758,17 +3716,14 @@ async def test_auth_vertex_ai_route(prisma_client):
request = Request(scope={"type": "http"})
request._url = URL(url=route)
request._headers = {"Authorization": "Bearer sk-12345"}
- try:
+ with pytest.raises(Exception, match="Invalid proxy server token passed") as exc_info:
await user_api_key_auth(request=request, api_key="Bearer " + "sk-12345")
- pytest.fail("Expected this call to fail. User is over limit.")
- except Exception as e:
- print(vars(e))
- print("error str=", str(e.message))
- error_str = str(e.message)
- assert e.code == "401"
- assert "Invalid proxy server token passed" in error_str
-
- pass
+ e = exc_info.value
+ print(vars(e))
+ print("error str=", str(e.message))
+ error_str = str(e.message)
+ assert e.code == "401"
+ assert "Invalid proxy server token passed" in error_str
@pytest.mark.asyncio
@@ -4028,7 +3983,7 @@ async def test_key_alias_uniqueness(prisma_client):
)
# Try to create second key with same alias - should fail
- try:
+ with pytest.raises(Exception, match="Unique key aliases across all keys are required") as exc_info:
key2 = await generate_key_fn(
data=GenerateKeyRequest(key_alias=unique_alias),
user_api_key_dict=UserAPIKeyAuth(
@@ -4037,10 +3992,9 @@ async def test_key_alias_uniqueness(prisma_client):
user_id="1234",
),
)
- pytest.fail("Should not be able to create a second key with the same alias")
- except Exception as e:
- print("vars(e)=", vars(e))
- assert "Unique key aliases across all keys are required" in str(e.message)
+ e = exc_info.value
+ print("vars(e)=", vars(e))
+ assert "Unique key aliases across all keys are required" in str(e.message)
# Create another key with different alias
another_alias = f"test-alias-{uuid.uuid4()}"
@@ -4054,7 +4008,7 @@ async def test_key_alias_uniqueness(prisma_client):
)
# Try to update key3 to use key1's alias - should fail
- try:
+ with pytest.raises(Exception, match="Unique key aliases across all keys are required") as exc_info:
await update_key_fn(
data=UpdateKeyRequest(key=key3.key, key_alias=unique_alias),
request=Request(scope={"type": "http"}),
@@ -4064,9 +4018,8 @@ async def test_key_alias_uniqueness(prisma_client):
user_id="1234",
),
)
- pytest.fail("Should not be able to update a key to use an existing alias")
- except Exception as e:
- assert "Unique key aliases across all keys are required" in str(e.message)
+ e = exc_info.value
+ assert "Unique key aliases across all keys are required" in str(e.message)
# Update key1 with its own existing alias - should succeed
updated_key = await update_key_fn(
@@ -4122,14 +4075,13 @@ async def test_enforce_unique_key_alias(prisma_client):
)
# Test 2: Block duplicate alias for new key
- try:
+ with pytest.raises(Exception, match="Unique key aliases across all keys are required") as exc_info:
await _enforce_unique_key_alias(
key_alias=unique_alias,
prisma_client=prisma_client,
)
- pytest.fail("Should not allow duplicate alias")
- except Exception as e:
- assert "Unique key aliases across all keys are required" in str(e.message)
+ e = exc_info.value
+ assert "Unique key aliases across all keys are required" in str(e.message)
# Test 3: Allow updating key with its own alias
await _enforce_unique_key_alias(
@@ -4148,15 +4100,14 @@ async def test_enforce_unique_key_alias(prisma_client):
),
)
- try:
+ with pytest.raises(Exception, match="Unique key aliases across all keys are required") as exc_info:
await _enforce_unique_key_alias(
key_alias=unique_alias,
existing_key_token=another_key.key,
prisma_client=prisma_client,
)
- pytest.fail("Should not allow using another key's alias")
- except Exception as e:
- assert "Unique key aliases across all keys are required" in str(e.message)
+ e = exc_info.value
+ assert "Unique key aliases across all keys are required" in str(e.message)
except Exception as e:
print("Unexpected error:", e)
@@ -4410,17 +4361,14 @@ def test_delete_nonexistent_key_returns_404(prisma_client):
request=request, api_key=bearer_token
)
result.user_role = LitellmUserRoles.PROXY_ADMIN
- try:
+ with pytest.raises(ProxyException) as exc_info:
await delete_key_fn(data=delete_key_request, user_api_key_dict=result)
- pytest.fail(
- "Expected ProxyException 404 for non-existent key, but delete_key_fn did not raise."
- )
- except ProxyException as e:
- print("Caught ProxyException:", e)
- assert str(e.code) == "404"
- assert "No keys found" in str(
- e.message
- ) or "No matching keys or aliases found to delete" in str(e.message)
+ e = exc_info.value
+ print("Caught ProxyException:", e)
+ assert str(e.code) == "404"
+ assert "No keys found" in str(
+ e.message
+ ) or "No matching keys or aliases found to delete" in str(e.message)
import asyncio
diff --git a/tests/proxy_unit_tests/test_proxy_custom_auth.py b/tests/proxy_unit_tests/test_proxy_custom_auth.py
index c5b6c1e6209..0582cacb42d 100644
--- a/tests/proxy_unit_tests/test_proxy_custom_auth.py
+++ b/tests/proxy_unit_tests/test_proxy_custom_auth.py
@@ -48,51 +48,40 @@ def client():
def test_custom_auth(client):
- try:
- # Your test data
- test_data = {
- "model": "openai-model",
- "messages": [
- {"role": "user", "content": "hi"},
- ],
- "max_tokens": 10,
- }
- # Your bearer token
- token = os.getenv("PROXY_MASTER_KEY")
- print(f"token: {token}")
- headers = {"Authorization": f"Bearer {token}"}
- response = client.post("/chat/completions", json=test_data, headers=headers)
- pytest.fail("LiteLLM Proxy test failed. This request should have been rejected")
- except Exception as e:
- print(vars(e))
- print("got an exception")
- assert e.code == "401"
- assert e.message == "Authentication Error, Failed custom auth"
- pass
+ # Your test data
+ test_data = {
+ "model": "openai-model",
+ "messages": [
+ {"role": "user", "content": "hi"},
+ ],
+ "max_tokens": 10,
+ }
+ # Your bearer token
+ token = os.getenv("PROXY_MASTER_KEY")
+ print(f"token: {token}")
+ headers = {"Authorization": f"Bearer {token}"}
+ with pytest.raises(Exception, match="Authentication Error, Failed custom auth") as exc_info:
+ client.post("/chat/completions", json=test_data, headers=headers)
+ assert exc_info.value.code == "401"
def test_custom_auth_bearer(client):
- try:
- # Your test data
- test_data = {
- "model": "openai-model",
- "messages": [
- {"role": "user", "content": "hi"},
- ],
- "max_tokens": 10,
- }
- # Your bearer token
- token = os.getenv("PROXY_MASTER_KEY")
-
- headers = {"Authorization": f"WITHOUT BEAR Er {token}"}
- response = client.post("/chat/completions", json=test_data, headers=headers)
- pytest.fail("LiteLLM Proxy test failed. This request should have been rejected")
- except Exception as e:
- print(vars(e))
- print("got an exception")
- assert e.code == "401"
- assert (
- e.message
- == "Authentication Error, CustomAuth - Malformed API Key passed in. Ensure Key has `Bearer` prefix"
- )
- pass
+ # Your test data
+ test_data = {
+ "model": "openai-model",
+ "messages": [
+ {"role": "user", "content": "hi"},
+ ],
+ "max_tokens": 10,
+ }
+ # Your bearer token
+ token = os.getenv("PROXY_MASTER_KEY")
+
+ headers = {"Authorization": f"WITHOUT BEAR Er {token}"}
+ with pytest.raises(Exception, match="CustomAuth - Malformed API Key passed in") as exc_info:
+ client.post("/chat/completions", json=test_data, headers=headers)
+ assert exc_info.value.code == "401"
+ assert (
+ exc_info.value.message
+ == "Authentication Error, CustomAuth - Malformed API Key passed in. Ensure Key has `Bearer` prefix"
+ )
diff --git a/tests/proxy_unit_tests/test_proxy_server.py b/tests/proxy_unit_tests/test_proxy_server.py
index e8f0e6953bc..150b90fc8c4 100644
--- a/tests/proxy_unit_tests/test_proxy_server.py
+++ b/tests/proxy_unit_tests/test_proxy_server.py
@@ -475,11 +475,10 @@ async def test_team_disable_guardrails(mock_acompletion, client_no_auth):
request._body = json_bytes
- try:
+ with pytest.raises(ProxyException) as exc_info:
await user_api_key_auth(request=request, api_key="Bearer " + user_key)
- pytest.fail("Expected to raise 403 forbidden error.")
- except ProxyException as e:
- assert e.code == str(403)
+ e = exc_info.value
+ assert e.code == str(403)
from test_custom_callback_input import CompletionCustomHandler
@@ -1473,11 +1472,11 @@ async def test_create_team_member_add_team_admin(
user_api_key_dict=valid_token,
)
except HTTPException as e:
- if user_role == "user" or new_member_method == "user_id":
- assert e.status_code == 403
+ if (
+ user_role == "user" or new_member_method == "user_id"
+ ) and e.status_code == 403:
return
- else:
- raise e
+ raise
mock_client.assert_called()
diff --git a/tests/proxy_unit_tests/test_user_api_key_auth.py b/tests/proxy_unit_tests/test_user_api_key_auth.py
index 9c9639144cb..49ec29d3ac5 100644
--- a/tests/proxy_unit_tests/test_user_api_key_auth.py
+++ b/tests/proxy_unit_tests/test_user_api_key_auth.py
@@ -295,13 +295,11 @@ async def test_user_api_key_auth_fails_with_prohibited_params(prohibited_param):
return bytes(json.dumps(body), "utf-8")
request.body = return_body
- try:
- response = await user_api_key_auth(request=request, api_key="Bearer " + user_key)
- except Exception as e:
- print("error str=", str(e))
- error_message = str(e.message)
- print("error message=", error_message)
- assert "is not allowed in request body" in error_message
+ with pytest.raises(Exception, match="is not allowed in request body") as exc_info:
+ await user_api_key_auth(request=request, api_key="Bearer " + user_key)
+ error_message = str(exc_info.value.message)
+ print("error message=", error_message)
+ assert "is not allowed in request body" in error_message
@pytest.mark.asyncio()
@@ -1120,12 +1118,9 @@ async def test_jwt_non_admin_team_route_access(monkeypatch):
return_value=mock_jwt_response,
),
):
- try:
+ with pytest.raises(ProxyException) as exc_info:
await user_api_key_auth(request=request, api_key="Bearer fake.jwt.token")
- pytest.fail("Expected this call to fail. Non-admin user should not access team routes.")
- except ProxyException as e:
- print("e", e)
- assert "Only proxy admin can be used to generate" in str(e.message)
+ assert "Only proxy admin can be used to generate" in str(exc_info.value.message)
@pytest.mark.asyncio
diff --git a/tests/router_unit_tests/test_router_helper_utils.py b/tests/router_unit_tests/test_router_helper_utils.py
index f81578dbd99..755405c8b21 100644
--- a/tests/router_unit_tests/test_router_helper_utils.py
+++ b/tests/router_unit_tests/test_router_helper_utils.py
@@ -756,25 +756,19 @@ async def test_routing_strategy_pre_call_checks(model_list, sync_mode):
)
),
):
- try:
+ with pytest.raises(litellm.RateLimitError):
await router.async_routing_strategy_pre_call_checks(
deployment, litellm_logging_obj
)
- pytest.fail("Exception was not raised")
- except Exception as e:
- assert isinstance(e, litellm.RateLimitError)
## WITH EXCEPTION - generic error
with patch.object(
callback, "async_pre_call_check", AsyncMock(side_effect=Exception("Error"))
):
- try:
+ with pytest.raises(Exception, match="Error"):
await router.async_routing_strategy_pre_call_checks(
deployment, litellm_logging_obj
)
- pytest.fail("Exception was not raised")
- except Exception as e:
- assert isinstance(e, Exception)
@pytest.mark.parametrize(
@@ -1866,21 +1860,14 @@ def testgenerate_model_id_with_deployment_model_name(model_list):
pytest.fail(f"Failed with valid model_group: {e}")
# Test case 2: Edge case with None model_group (this should fail as expected - our fix prevents this from happening)
- try:
- result = router.generate_model_id(
- model_group=None, litellm_params=litellm_params
- )
- pytest.fail(
- "Expected TypeError when model_group is None - this confirms our fix is needed"
- )
- except TypeError as e:
- # After optimization, error message changed but still fails appropriately on None
- assert "unsupported operand type(s) for +=" in str(
- e
- ) or "expected str instance, NoneType found" in str(e)
- print(f"✓ Correctly failed with None model_group (as expected): {e}")
- except Exception as e:
- pytest.fail(f"Unexpected error with None model_group: {e}")
+ with pytest.raises(TypeError) as exc_info:
+ router.generate_model_id(model_group=None, litellm_params=litellm_params)
+ # After optimization, error message changed but still fails appropriately on None
+ error_str = str(exc_info.value)
+ assert (
+ "unsupported operand type(s) for +=" in error_str
+ or "expected str instance, NoneType found" in error_str
+ )
# Test case 3: Edge case with None key in litellm_params
litellm_params_with_none_key = {
diff --git a/tests/test_keys.py b/tests/test_keys.py
index 003e2711055..2d8ff2232a1 100644
--- a/tests/test_keys.py
+++ b/tests/test_keys.py
@@ -708,11 +708,10 @@ async def test_key_crossing_budget():
response = await chat_completion(session=session, key=key)
print("response 1: ", response)
await asyncio.sleep(10)
- try:
+ with pytest.raises(Exception, match="Budget has been exceeded!") as exc_info:
response = await chat_completion(session=session, key=key)
- pytest.fail("Should have failed - Key crossed it's budget")
- except Exception as e:
- assert "Budget has been exceeded!" in str(e)
+ e = exc_info.value
+ assert "Budget has been exceeded!" in str(e)
@pytest.mark.skip(reason="AWS Suspended Account")
@@ -884,8 +883,7 @@ async def test_key_over_budget():
## CALL `/models` - expect to work
model_list = await get_key_info(session=session, get_key=key, call_key=key)
## CALL `/chat/completions` - expect to fail
- try:
+ with pytest.raises(Exception, match="Budget has been exceeded!") as exc_info:
await chat_completion(session=session, key=key)
- pytest.fail("Expected this call to fail")
- except Exception as e:
- assert "Budget has been exceeded!" in str(e)
+ e = exc_info.value
+ assert "Budget has been exceeded!" in str(e)
diff --git a/tests/test_litellm/google_genai/test_google_genai_adapter_fixes.py b/tests/test_litellm/google_genai/test_google_genai_adapter_fixes.py
index da56b094d95..d51452aec1b 100644
--- a/tests/test_litellm/google_genai/test_google_genai_adapter_fixes.py
+++ b/tests/test_litellm/google_genai/test_google_genai_adapter_fixes.py
@@ -219,17 +219,14 @@ def test_stream_transformation_error_handling():
# Create a wrapper
mock_wrapper = GoogleGenAIStreamWrapper(completion_stream=iter([]))
- # Try to transform - this should handle errors gracefully
+ # Try to transform - this should either succeed or raise a ValueError, never crash
try:
- streaming_chunk = adapter.translate_streaming_completion_to_generate_content(
+ adapter.translate_streaming_completion_to_generate_content(
mock_response, mock_wrapper
)
- # If no exception is raised, that's fine - we just want to ensure no crash
- assert True
- except Exception as e:
- # If an exception is raised, it should be a ValueError with appropriate message
- assert isinstance(e, ValueError)
+ except ValueError:
# We won't check the exact message as it might vary
+ pass
def test_non_stream_response_when_stream_requested():
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 bd373f87eea..ee3e7719d52 100644
--- a/tests/test_litellm/litellm_core_utils/test_token_counter.py
+++ b/tests/test_litellm/litellm_core_utils/test_token_counter.py
@@ -1024,13 +1024,12 @@ def test_token_counter_with_image_url():
}
]
- try:
+ with pytest.raises(ValueError, match="Invalid detail value") as exc_info:
token_counter(model="gpt-3.5-turbo", messages=messages_invalid)
- pytest.fail("Expected ValueError for invalid detail value")
- except ValueError as e:
- assert "Invalid detail value" in str(
- e
- ), f"Expected detail validation error, got: {e}"
+ e = exc_info.value
+ assert "Invalid detail value" in str(
+ e
+ ), f"Expected detail validation error, got: {e}"
def test_token_counter_with_thinking_content():
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 5e3729fdd92..30843e8160b 100644
--- a/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py
+++ b/tests/test_litellm/llms/bedrock/chat/test_converse_transformation.py
@@ -3003,7 +3003,7 @@ def test_request_metadata_validation():
# Test too many items (max 16)
too_many_items = {f"key_{i}": f"value_{i}" for i in range(17)}
- try:
+ with pytest.raises(Exception, match="maximum of 16 items") as exc_info:
config.transform_request(
model="anthropic.claude-haiku-4-5-20251001-v1:0",
messages=messages,
@@ -3011,9 +3011,8 @@ def test_request_metadata_validation():
litellm_params={},
headers={},
)
- pytest.fail("Should have raised validation error for too many items")
- except Exception as e:
- assert "maximum of 16 items" in str(e).lower()
+ e = exc_info.value
+ assert "maximum of 16 items" in str(e).lower()
def test_request_metadata_key_constraints():
@@ -3026,7 +3025,7 @@ def test_request_metadata_key_constraints():
long_key = "a" * 257
invalid_metadata = {long_key: "value"}
- try:
+ with pytest.raises(Exception, match="(?i)key length|256 characters"):
config.transform_request(
model="anthropic.claude-haiku-4-5-20251001-v1:0",
messages=messages,
@@ -3034,14 +3033,11 @@ def test_request_metadata_key_constraints():
litellm_params={},
headers={},
)
- 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()
# Test empty key
invalid_metadata = {"": "value"}
- try:
+ with pytest.raises(Exception, match="(?i)key length|empty"):
config.transform_request(
model="anthropic.claude-haiku-4-5-20251001-v1:0",
messages=messages,
@@ -3049,9 +3045,6 @@ def test_request_metadata_key_constraints():
litellm_params={},
headers={},
)
- 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()
def test_request_metadata_value_constraints():
@@ -3064,7 +3057,7 @@ def test_request_metadata_value_constraints():
long_value = "a" * 257
invalid_metadata = {"key": long_value}
- try:
+ with pytest.raises(Exception, match="(?i)value length|256 characters"):
config.transform_request(
model="anthropic.claude-haiku-4-5-20251001-v1:0",
messages=messages,
@@ -3072,9 +3065,6 @@ def test_request_metadata_value_constraints():
litellm_params={},
headers={},
)
- 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()
# Test empty value (should be allowed)
valid_metadata = {"key": ""}
diff --git a/tests/test_litellm/llms/deepinfra/test_deepinfra_rerank.py b/tests/test_litellm/llms/deepinfra/test_deepinfra_rerank.py
index f317fb70d41..4633cd5c6b0 100644
--- a/tests/test_litellm/llms/deepinfra/test_deepinfra_rerank.py
+++ b/tests/test_litellm/llms/deepinfra/test_deepinfra_rerank.py
@@ -309,9 +309,8 @@ def test_deepinfra_rerank_models():
except Exception as e:
# We expect this to potentially fail due to missing api_base/key
# but the model format should be recognized
- assert "api_base" in str(e) or "API key" in str(
- e
- ), f"Unexpected error for model {model}: {e}"
+ if "api_base" not in str(e) and "API key" not in str(e):
+ raise
@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post")
diff --git a/tests/test_litellm/llms/deepinfra/test_deepinfra_rerank_integration.py b/tests/test_litellm/llms/deepinfra/test_deepinfra_rerank_integration.py
index 08d8e4ffdd4..e61ba81cf09 100644
--- a/tests/test_litellm/llms/deepinfra/test_deepinfra_rerank_integration.py
+++ b/tests/test_litellm/llms/deepinfra/test_deepinfra_rerank_integration.py
@@ -307,25 +307,26 @@ def test_deepinfra_rerank_error_handling(mock_post):
@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post")
-def test_deepinfra_rerank_missing_api_base_error(mock_post):
- """Test error handling when API base is missing."""
- # Note: The current implementation may have a default API base or the test environment
- # may be providing one, so we'll test the actual behavior
- try:
- response = litellm.rerank(
- model="deepinfra/Qwen/Qwen3-Reranker-0.6B",
- query="hello",
- documents=["hello", "world"],
- custom_llm_provider="deepinfra",
- api_key="test_key",
- # api_base is intentionally missing
- )
- # If no error is raised, it means a default API base is being used
- # This is acceptable behavior
- assert response is not None
- except ValueError as e:
- # If an error is raised, it should match the expected message
- assert "api_base must be provided for Deepinfra rerank" in str(e)
+def test_deepinfra_rerank_defaults_api_base_when_missing(mock_post, monkeypatch):
+ """With no api_base anywhere, the call still goes out against DeepInfra's own base."""
+ monkeypatch.delenv("DEEPINFRA_API_BASE", raising=False)
+
+ mock_response = MagicMock()
+ mock_response.json = lambda: {"scores": [0.9, 0.1], "input_tokens": 20}
+ mock_response.status_code = 200
+ mock_response.headers = {"content-type": "application/json"}
+ mock_post.return_value = mock_response
+
+ litellm.rerank(
+ model="deepinfra/Qwen/Qwen3-Reranker-0.6B",
+ query="hello",
+ documents=["hello", "world"],
+ custom_llm_provider="deepinfra",
+ api_key="test_key",
+ # api_base is intentionally missing
+ )
+
+ assert "api.deepinfra.com" in mock_post.call_args.kwargs["url"]
@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post")
@@ -395,9 +396,8 @@ def test_deepinfra_rerank_models():
except Exception as e:
# We expect this to potentially fail due to missing api_base/key
# but the model format should be recognized
- assert "api_base" in str(e) or "API key" in str(
- e
- ), f"Unexpected error for model {model}: {e}"
+ if "api_base" not in str(e) and "API key" not in str(e):
+ raise
@patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post")
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 bcca35886fe..195fba69010 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
@@ -177,21 +177,19 @@ def test_validate_request_valid():
def test_validate_request_missing_model():
"""Test that missing model raises ValueError."""
config = OpenAICountTokensConfig()
- try:
+ with pytest.raises(ValueError, match="model") as exc_info:
config.validate_request(model="", input="Hello")
- pytest.fail("Should have raised ValueError")
- except ValueError as e:
- assert "model" in str(e)
+ e = exc_info.value
+ assert "model" in str(e)
def test_validate_request_missing_input():
"""Test that missing input raises ValueError."""
config = OpenAICountTokensConfig()
- try:
+ with pytest.raises(ValueError, match="input") as exc_info:
config.validate_request(model="gpt-4o", input="")
- pytest.fail("Should have raised ValueError")
- except ValueError as e:
- assert "input" in str(e)
+ e = exc_info.value
+ assert "input" in str(e)
def test_get_endpoint_default():
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 d279eaeec01..d3ea8d5b907 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
@@ -72,15 +72,14 @@ class TestOpenRouterResponsesAPIConfig:
monkeypatch.delenv("OPENROUTER_API_KEY", raising=False)
monkeypatch.delenv("OR_API_KEY", raising=False)
- try:
+ with pytest.raises(ValueError, match="OpenRouter API key is required") as exc_info:
config.validate_environment(
headers={},
model="openai/o4-mini",
litellm_params=GenericLiteLLMParams(),
)
- pytest.fail("Should have raised ValueError")
- except ValueError as e:
- assert "OpenRouter API key is required" in str(e)
+ e = exc_info.value
+ assert "OpenRouter API key is required" in str(e)
class TestOpenRouterResponsesAPIRegistration:
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 89c0ec1988f..6a6271e95e2 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
@@ -239,17 +239,16 @@ class TestPerplexityEmbeddingConfig:
mock_response.status_code = 500
model_response = EmbeddingResponse()
- try:
+ with pytest.raises(PerplexityEmbeddingError) as exc_info:
self.config.transform_embedding_response(
model=self.model,
raw_response=mock_response,
model_response=model_response,
logging_obj=self.logging_obj,
)
- pytest.fail("Should have raised PerplexityEmbeddingError")
- except PerplexityEmbeddingError as e:
- assert e.status_code == 500
- assert "Server error" in e.message
+ e = exc_info.value
+ assert e.status_code == 500
+ assert "Server error" in e.message
def test_get_error_class(self):
"""Test that get_error_class returns the correct error type."""
diff --git a/tests/test_litellm/llms/vertex_ai/videos/test_vertex_video_transformation.py b/tests/test_litellm/llms/vertex_ai/videos/test_vertex_video_transformation.py
index 55197d3165c..57cd729bc90 100644
--- a/tests/test_litellm/llms/vertex_ai/videos/test_vertex_video_transformation.py
+++ b/tests/test_litellm/llms/vertex_ai/videos/test_vertex_video_transformation.py
@@ -10,6 +10,7 @@ from unittest.mock import MagicMock, Mock, patch
import httpx
import pytest
+import litellm
from litellm.llms.vertex_ai.videos.transformation import (
VertexAIVideoConfig,
_convert_image_to_vertex_format,
@@ -93,22 +94,15 @@ class TestVertexAIVideoConfig:
# Should NOT include endpoint
assert not url.endswith(":predictLongRunning")
- def test_get_complete_url_missing_project(self):
+ def test_get_complete_url_missing_project(self, monkeypatch):
"""Test that missing vertex_project raises error."""
- litellm_params = {}
+ monkeypatch.delenv("VERTEXAI_PROJECT", raising=False)
+ monkeypatch.setattr(litellm, "vertex_project", None)
- # Note: The method might not raise if vertex_project can be fetched from env
- # This test verifies the behavior when completely missing
- try:
- url = self.config.get_complete_url(
- model="veo-002", api_base=None, litellm_params=litellm_params
+ with pytest.raises(ValueError, match="vertex_project is required"):
+ self.config.get_complete_url(
+ model="veo-002", api_base=None, litellm_params={}
)
- # If no error is raised, vertex_project was obtained from environment
- # In that case, just verify a URL was returned
- assert url is not None
- except ValueError as e:
- # Expected behavior when vertex_project is truly missing
- assert "vertex_project is required" in str(e)
def test_get_complete_url_default_location(self):
"""Test URL construction with default location."""
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 da7f43c7118..0b211255218 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
@@ -1896,20 +1896,21 @@ def test_is_context_window_error_detection_variants():
)
assert _is_context_window_error(cwe)
- try:
+ with pytest.raises(ValueError, match="Internal_litellm_router API call failed") as explicitly_chained:
raise ValueError("Internal_litellm_router API call failed") from cwe
- except ValueError as explicitly_chained:
- assert _is_context_window_error(explicitly_chained)
+ assert _is_context_window_error(explicitly_chained.value)
- try:
+ def wrap_without_explicit_chaining():
try:
raise litellm.ContextWindowExceededError(
message="overflow", model="m", llm_provider="openai"
)
except litellm.ContextWindowExceededError:
raise ValueError("wrapper without explicit chaining")
- except ValueError as implicitly_chained:
- assert _is_context_window_error(implicitly_chained)
+
+ with pytest.raises(ValueError, match="wrapper without explicit chaining") as implicitly_chained:
+ wrap_without_explicit_chaining()
+ assert _is_context_window_error(implicitly_chained.value)
assert _is_context_window_error(ValueError("Invalid 'input[0]': maximum input length is 8192 tokens."))
assert not _is_context_window_error(ValueError("A generic API error occurred."))
diff --git a/tests/test_litellm/proxy/db/test_exception_handler.py b/tests/test_litellm/proxy/db/test_exception_handler.py
index a656d5edcbc..4c6315024dd 100644
--- a/tests/test_litellm/proxy/db/test_exception_handler.py
+++ b/tests/test_litellm/proxy/db/test_exception_handler.py
@@ -266,10 +266,10 @@ def test_is_prisma_engine_internal_error_excludes_data_layer_prisma_error():
data_layer_error = UniqueViolationError(
data={"user_facing_error": {"meta": {"table": "t"}}}
)
- try:
+ with pytest.raises(UniqueViolationError) as exc_info:
raise data_layer_error
- except UniqueViolationError as e:
- assert PrismaDBExceptionHandler.is_prisma_engine_internal_error(e) is False
+ e = exc_info.value
+ assert PrismaDBExceptionHandler.is_prisma_engine_internal_error(e) is False
@pytest.mark.parametrize(
diff --git a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
index a72871310c7..fc0088b28d7 100644
--- a/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
+++ b/tests/test_litellm/proxy/hooks/test_parallel_request_limiter_v3.py
@@ -1192,19 +1192,19 @@ async def test_tpm_api_key_rate_limits_v3():
# Test the pre-call hook
error = None
- try:
+ with pytest.raises(HTTPException) as exc_info:
await parallel_request_handler.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=local_cache,
data={"model": model},
call_type="",
)
- except HTTPException as e:
- error = e
- assert e.status_code == 429
- assert "rate_limit_type" in e.headers
- assert e.headers.get("rate_limit_type") == "tokens"
- assert "retry-after" in e.headers
+ e = exc_info.value
+ error = e
+ assert e.status_code == 429
+ assert "rate_limit_type" in e.headers
+ assert e.headers.get("rate_limit_type") == "tokens"
+ assert "retry-after" in e.headers
assert error is not None, "An Exception must be thrown"
assert captured_descriptors is not None, "Rate limit descriptors should be captured"
@@ -1287,19 +1287,19 @@ async def test_rpm_api_key_rate_limits_v3():
# Test the pre-call hook
error = None
- try:
+ with pytest.raises(HTTPException) as exc_info:
await parallel_request_handler.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=local_cache,
data={"model": model},
call_type="",
)
- except HTTPException as e:
- error = e
- assert e.status_code == 429
- assert "rate_limit_type" in e.headers
- assert e.headers.get("rate_limit_type") == "requests"
- assert "retry-after" in e.headers
+ e = exc_info.value
+ error = e
+ assert e.status_code == 429
+ assert "rate_limit_type" in e.headers
+ assert e.headers.get("rate_limit_type") == "requests"
+ assert "retry-after" in e.headers
assert error is not None, "An Exception must be thrown"
assert captured_descriptors is not None, "Rate limit descriptors should be captured"
@@ -1441,19 +1441,19 @@ async def test_team_member_rate_limits_v3_raises_429_when_over_limit():
parallel_request_handler.should_rate_limit = mock_should_rate_limit
error = None
- try:
+ with pytest.raises(HTTPException) as exc_info:
await parallel_request_handler.async_pre_call_hook(
user_api_key_dict=user_api_key_dict,
cache=local_cache,
data={"model": "gpt-3.5-turbo"},
call_type="",
)
- except HTTPException as e:
- error = e
- assert e.status_code == 429
- assert "rate_limit_type" in e.headers
- assert e.headers.get("rate_limit_type") == "requests"
- assert "retry-after" in e.headers
+ e = exc_info.value
+ error = e
+ assert e.status_code == 429
+ assert "rate_limit_type" in e.headers
+ assert e.headers.get("rate_limit_type") == "requests"
+ assert "retry-after" in e.headers
assert error is not None, "An Exception must be thrown"
assert captured_descriptors is not None, "Rate limit descriptors should be captured"
diff --git a/tests/test_litellm/router_strategy/test_router_tag_routing.py b/tests/test_litellm/router_strategy/test_router_tag_routing.py
index 60b1166de73..752136f2b66 100644
--- a/tests/test_litellm/router_strategy/test_router_tag_routing.py
+++ b/tests/test_litellm/router_strategy/test_router_tag_routing.py
@@ -256,7 +256,11 @@ async def test_error_from_tag_routing():
enable_tag_filtering=True,
)
- try:
+ from litellm.types.router import RouterErrors
+
+ with pytest.raises(
+ Exception, match=RouterErrors.no_deployments_with_tag_routing.value
+ ):
await router.acompletion(
model="gpt-4",
messages=[{"role": "user", "content": "Tell me a joke."}],
@@ -264,13 +268,6 @@ async def test_error_from_tag_routing():
mock_response="Tell me a joke.",
)
- pytest.fail("this should have failed - expected it to fail")
- except Exception as e:
- from litellm.types.router import RouterErrors
-
- assert RouterErrors.no_deployments_with_tag_routing.value in str(e)
- pass
-
def test_tag_routing_with_list_of_tags():
"""
diff --git a/tests/test_litellm/test_a2a_registry_lookup.py b/tests/test_litellm/test_a2a_registry_lookup.py
index e248956488d..dd745bfe15b 100644
--- a/tests/test_litellm/test_a2a_registry_lookup.py
+++ b/tests/test_litellm/test_a2a_registry_lookup.py
@@ -65,9 +65,8 @@ def test_a2a_registry_integration():
)
except Exception as e:
# Should use registry URL (connection error expected)
- assert "registry-url.example.com" in str(e) or "APIConnectionError" in str(
- type(e).__name__
- )
+ if "registry-url.example.com" not in str(e) and "APIConnectionError" not in type(e).__name__:
+ raise
finally:
global_agent_registry.agent_list = original_agents
diff --git a/tests/test_team_members.py b/tests/test_team_members.py
index 4cf85af6410..449068cf6e5 100644
--- a/tests/test_team_members.py
+++ b/tests/test_team_members.py
@@ -310,9 +310,8 @@ def test_delete_nonexistent_member(api_client, new_team):
), "Test setup error: nonexistent user somehow exists"
# Attempt to delete nonexistent user
- try:
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
api_client.delete_team_member(new_team, nonexistent_user)
- pytest.fail("Expected HTTPError for deleting nonexistent user")
- except requests.exceptions.HTTPError as e:
- logger.info(f"Expected error received: {str(e)}")
- assert e.response.status_code == 400
+ e = exc_info.value
+ logger.info(f"Expected error received: {str(e)}")
+ assert e.response.status_code == 400