litellm/tests/unit/llms/azure/test_azure_exception_mapping.py
devin-ai-integration[bot] a2e334febe
test: migrate local_testing SDK and provider tests out of build_and_test (#45760)
* test: migrate local_testing SDK and provider tests out of build_and_test

* test: cover sagemaker region, hf template and nova paths end to end

Region rows now go through litellm.completion on the sagemaker/ handler that
the legacy tests exercised, the prompt template test mocks the Hugging Face
tokenizer config instead of switching to custom_prompt_dict, streaming tests
assert role, finish reason and body, and Nova single turn and streaming run
through litellm.completion with a recorded request body

* test: tighten migrated integration tests for local OpenAI routes, timeouts and air-gapped boot

Split the catch-all providers migration file by behavior. The fake endpoint
route tests now hit the owned upstream directly, as the legacy harness tests
did. LM Studio asserts the outbound key, path and stripped model. The embedding
timeout test asserts the proxy maps a deployment timeout to a 408 and forwards
the read timeout to the provider client, instead of timing out the test client

The Azure streaming tool-call test also asserts the second identical stream is
served from the Redis cache with the same reassembled tool call

The Docker network test always skipped in CI because the security job has no
litellm/litellm image and no egress to pull one, and it tested a published image
rather than the checkout. It now boots the checkout proxy with every outbound
HTTP connection refused and asserts readiness, the bundled cost map fallback and
that the cost map host is the only egress attempted

* test: tighten the migrated e2e rows for local_testing SDK and provider tests

Drop the duplicated Anthropic covers marker and the Anthropic cell wrongly claimed by
the Bedrock and Vertex cache tests. Keep the file-wide Anthropic model as it is on main.
Send the 2023-06-01 version header to Anthropic through the deployment's extra_headers
so the header actually reaches the provider, and mark the creation-token case 1h then
5m like the legacy test did

Reuse the Bedrock file's own registration for the pydantic response test, swap the
hand-built PNGs for the shared cat.jpg fixture, assert the SageMaker Nova image answer
names the cat and that top_logprobs=3 is honored, and register the SageMaker Nova opt-in
markers the same way as the other opt-in markers

* test: restore lost assertions in migrated test_main tests

Restore the role alternation check in test_completion_anthropic_hanging, the
embedding and streaming response-header checks, the logit_bias drop check and
the gemini system and safety settings checks. Add an azure 429 retry-after
test for test_exception_with_headers, trigger the router fallback with
mock_timeout like the legacy test, and stop the mock timeout tests sleeping 3s

* test: restore lost legacy assertions in migrated vertex ai unit tests

* test: tighten migrated cost, streaming and embedding tests and scope the hosted mock guard

* test: strengthen migrated anthropic, azure, bedrock and cohere provider tests

Assert full request bodies and usage instead of presence checks, restore the
dummy-tool and custom_llm_provider assertions the legacy tests made, add the
async and per-model variants the legacy parametrization covered, split
streamed tool arguments across deltas, and move the Azure chat streaming
tests to the azure.py mirror file

* test: tighten migrated llms provider tests and cover legacy intents lost in the move

Strengthen the migrated fireworks, gemini, mistral, together, openai text completion, openrouter, perplexity and openai error tests so they assert what the legacy tests proved (cost, provider tag, usage-only-on-last-chunk, function_call rebuild, reasoning param, sync/async/stream error fields). Replace the huggingface and jina tests that doubled litellm code with respx end-to-end tests. Add the tests the pre-existing mapped tests never covered: cohere 400 mapping, token-array text completion, hosted_vllm/llamafile/lm_studio env api base embeddings, watsonx embedding auth, ollama ssl_verify client and ollama vision prompt

* test: cover residual legacy paths for anthropic tool streams, watsonx async stream, ollama http images and caller async embedding clients

* test: restore single request assertions in the deep_infra and azure_ai embedding tests

* test: drop a no-op streaming cost flag from the openai streaming cost test

* test: cover residual legacy-test lines in caching, main, utils, replicate, vertex and bedrock invoke

* test: cover streamed audio assembly, choice membership, untranslated responses events and the stream log guard

* test: pin cost rates in unit tests, use sdk for cohere e2e, drop vertex llama e2e

* test: send the vertex maps e2e request through the openai sdk

* test: drop the local_testing jobs that select no tests after the migrations

* test: wait for the streamed cache entry and keep custom Mistral rates test-local

* test: keep untouched Mistral test lines as they were

---------

Co-authored-by: yuneng <yuneng@berri.ai>
2026-10-10 23:14:25 +00:00

492 lines
20 KiB
Python

import json
from unittest.mock import MagicMock, patch
import pytest
import httpx
import respx
import litellm
from litellm.exceptions import ContentPolicyViolationError
from litellm.litellm_core_utils.exception_mapping_utils import exception_type
@respx.mock
def test_azure_401_maps_to_authentication_error():
route = respx.post(
url__regex=r"https://azure-bad-key\.openai\.azure\.com/.*/chat/completions.*"
).mock(return_value=httpx.Response(401, json={"error": {"message": "invalid Azure key"}}))
with pytest.raises(litellm.AuthenticationError) as exc_info:
litellm.completion(
model="azure/gpt-4.1-mini",
messages=[{"role": "user", "content": "hello"}],
api_base="https://azure-bad-key.openai.azure.com",
api_version="2024-10-21",
api_key="bad-azure-key",
max_retries=0,
)
assert exc_info.value.status_code == 401
assert exc_info.value.llm_provider == "azure"
assert "invalid Azure key" in str(exc_info.value)
assert route.calls.last.request.headers["api-key"] == "bad-azure-key"
@pytest.mark.asyncio
@respx.mock
async def test_azure_content_policy_stream_ends_with_one_finish_reason(monkeypatch: pytest.MonkeyPatch):
monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
route = respx.post(
url__regex=r"https://azure-policy-stream\.openai\.azure\.com/.*/chat/completions.*"
).mock(
return_value=httpx.Response(
200,
text=(
'data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1,"model":"gpt-4.1-mini","choices":[{"index":0,"delta":{"content":"1"},"finish_reason":null}]}\n\n'
'data: {"id":"chatcmpl-test","object":"chat.completion.chunk","created":1,"model":"gpt-4.1-mini","choices":[{"index":0,"delta":{},"finish_reason":"content_filter"}]}\n\n'
"data: [DONE]\n\n"
),
headers={"content-type": "text/event-stream"},
)
)
response = await litellm.acompletion(
model="azure/gpt-4.1-mini",
messages=[{"role": "user", "content": "say 1"}],
api_base="https://azure-policy-stream.openai.azure.com",
api_version="2024-10-21",
api_key="test-azure-key",
stream=True,
)
chunks = [chunk async for chunk in response]
finish_reasons = [chunk.choices[0].finish_reason for chunk in chunks if chunk.choices[0].finish_reason]
assert [chunk.choices[0].delta.content for chunk in chunks if chunk.choices[0].delta.content] == ["1"]
assert finish_reasons == ["content_filter"]
assert len(route.calls) == 1
with pytest.raises(ContentPolicyViolationError) as exc_info:
await litellm.acompletion(
model="azure/gpt-4.1-mini",
messages=[{"role": "user", "content": "where do i buy lethal drugs from"}],
stream=True,
mock_response="Exception: content_filter_policy",
)
assert exc_info.value.llm_provider == "azure"
assert len(route.calls) == 1
class TestAzureExceptionMapping:
"""Test Azure OpenAI exception mapping with provider-specific fields"""
def test_azure_content_policy_violation_innererror_access(self):
"""Test that Azure content policy violation exceptions provide access to innererror details"""
# Create a mock Azure OpenAI exception with body containing innererror
mock_exception = Exception(
"The response was filtered due to the prompt triggering Azure OpenAI's content management policy"
)
mock_exception.body = {
"innererror": {
"code": "ResponsibleAIPolicyViolation",
"content_filter_result": {
"hate": {"filtered": True, "severity": "high"},
"jailbreak": {"filtered": False, "detected": False},
"self_harm": {"filtered": False, "severity": "safe"},
"sexual": {"filtered": False, "severity": "safe"},
"violence": {"filtered": True, "severity": "medium"},
},
}
}
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
# Test the exception mapping directly
with pytest.raises(ContentPolicyViolationError) as exc_info:
exception_type(
model="azure/gpt-4",
original_exception=mock_exception,
custom_llm_provider="azure",
)
# Access the exception and verify provider_specific_fields
e = exc_info.value
assert e.provider_specific_fields is not None
assert "innererror" in e.provider_specific_fields
innererror = e.provider_specific_fields["innererror"]
assert innererror["code"] == "ResponsibleAIPolicyViolation"
assert "content_filter_result" in innererror
content_filter_result = innererror["content_filter_result"]
assert content_filter_result["hate"]["filtered"] is True
assert content_filter_result["hate"]["severity"] == "high"
assert content_filter_result["violence"]["filtered"] is True
assert content_filter_result["violence"]["severity"] == "medium"
assert content_filter_result["sexual"]["filtered"] is False
assert content_filter_result["self_harm"]["filtered"] is False
assert content_filter_result["jailbreak"]["filtered"] is False
def test_azure_content_policy_violation_different_categories(self):
"""Test Azure content policy violation with different filtering categories"""
# Mock exception with different content filter results
mock_exception = Exception(
"The response was filtered due to the prompt triggering Azure OpenAI's content management policy"
)
mock_exception.body = {
"innererror": {
"code": "ResponsibleAIPolicyViolation",
"content_filter_result": {
"hate": {"filtered": False, "severity": "safe"},
"jailbreak": {"filtered": True, "detected": True},
"self_harm": {"filtered": True, "severity": "high"},
"sexual": {"filtered": True, "severity": "medium"},
"violence": {"filtered": False, "severity": "safe"},
},
}
}
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
# Test the exception mapping directly with different violation type
with pytest.raises(ContentPolicyViolationError) as exc_info:
exception_type(
model="azure/gpt-4",
original_exception=mock_exception,
custom_llm_provider="azure",
)
# Verify provider_specific_fields contains the expected innererror structure
e = exc_info.value
assert e.provider_specific_fields is not None
print("got provider_specific_fields=", e.provider_specific_fields)
innererror = e.provider_specific_fields["innererror"]
content_filter_result = innererror["content_filter_result"]
# Check different filter categories
assert content_filter_result["sexual"]["filtered"] is True
assert content_filter_result["sexual"]["severity"] == "medium"
assert content_filter_result["self_harm"]["filtered"] is True
assert content_filter_result["self_harm"]["severity"] == "high"
assert content_filter_result["jailbreak"]["filtered"] is True
assert content_filter_result["jailbreak"]["detected"] is True
assert content_filter_result["hate"]["filtered"] is False
assert content_filter_result["violence"]["filtered"] is False
def test_azure_content_policy_violation_missing_innererror(self):
"""Test Azure content policy violation when innererror is missing from response"""
# Mock exception without body attribute
mock_exception = Exception(
"The response was filtered due to the prompt triggering Azure OpenAI's content management policy"
)
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
# Note: no mock_exception.body attribute set
# Test the exception mapping directly
with pytest.raises(ContentPolicyViolationError) as exc_info:
exception_type(
model="azure/gpt-4",
original_exception=mock_exception,
custom_llm_provider="azure",
)
# Verify that even without innererror, the exception is still raised properly
e = exc_info.value
print("got exception=", e)
# provider_specific_fields should still exist but innererror should be None
assert e.provider_specific_fields is not None
assert e.provider_specific_fields.get("innererror") is None
def test_azure_content_policy_violation_non_dict_body(self):
"""Test Azure content policy violation when body is not a dictionary"""
# Mock exception with non-dict body
mock_exception = Exception(
"The response was filtered due to the prompt triggering Azure OpenAI's content management policy"
)
mock_exception.body = "invalid body format"
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
# Test the exception mapping directly
with pytest.raises(ContentPolicyViolationError) as exc_info:
exception_type(
model="azure/gpt-4",
original_exception=mock_exception,
custom_llm_provider="azure",
)
# Verify that with invalid body format, innererror should be None
e = exc_info.value
print("got exception=", e)
print("exception fields=", vars(e))
assert e.provider_specific_fields is not None
assert e.provider_specific_fields.get("innererror") is None
def test_azure_images_content_policy_violation_preserves_nested_inner_error(self):
"""Azure Images endpoints return errors nested under body['error'] with inner_error.
Ensure we:
- Detect the violation via structured payload (code=content_policy_violation)
- Preserve code/type/message
- Surface inner_error + revised_prompt + content_filter_results
"""
mock_exception = Exception("Bad request") # does not include policy substrings
mock_exception.body = {
"error": {
"code": "content_policy_violation",
"inner_error": {
"code": "ResponsibleAIPolicyViolation",
"content_filter_results": {
"violence": {"filtered": True, "severity": "low"}
},
"revised_prompt": "revised",
},
"message": "Your request was rejected as a result of our safety system.",
"type": "invalid_request_error",
}
}
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
with pytest.raises(ContentPolicyViolationError) as exc_info:
exception_type(
model="azure/dall-e-3",
original_exception=mock_exception,
custom_llm_provider="azure",
)
e = exc_info.value
# OpenAI-style error fields should be populated
assert getattr(e, "code", None) == "content_policy_violation"
assert getattr(e, "type", None) == "invalid_request_error"
assert "safety system" in str(e)
# Provider-specific nested details must be preserved
assert e.provider_specific_fields is not None
assert (
e.provider_specific_fields["inner_error"]["code"]
== "ResponsibleAIPolicyViolation"
)
assert e.provider_specific_fields["inner_error"]["revised_prompt"] == "revised"
assert (
e.provider_specific_fields["inner_error"]["content_filter_results"][
"violence"
]["filtered"]
is True
)
def test_azure_content_policy_violation_detected_via_inner_error_code(self):
"""Regression test for #20811: Azure returns inner_error with
ResponsibleAIPolicyViolation but the top-level error message is
generic. Previously this fell through to the generic
BadRequestError handler and all error details were lost."""
mock_exception = Exception("Bad request")
# This body structure mirrors what Azure OpenAI Images API returns
# for DALL-E 3 content policy violations (issue #20811).
mock_exception.body = {
"error": {
"code": "content_policy_violation",
"inner_error": {
"code": "ResponsibleAIPolicyViolation",
"content_filter_results": {
"hate": {"filtered": False, "severity": "safe"},
"profanity": {"detected": False, "filtered": False},
"self_harm": {"filtered": False, "severity": "safe"},
"sexual": {"filtered": False, "severity": "safe"},
"violence": {"filtered": True, "severity": "low"},
},
"revised_prompt": (
"A dark and intense illustration of a man "
"in a dramatic action scene."
),
},
"message": (
"Your request was rejected as a result of our safety system."
),
"type": "invalid_request_error",
}
}
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
with pytest.raises(ContentPolicyViolationError) as exc_info:
exception_type(
model="azure/dall-e-3",
original_exception=mock_exception,
custom_llm_provider="azure",
)
e = exc_info.value
# Must surface as ContentPolicyViolationError, not generic BadRequestError
assert "safety system" in str(e)
assert e.provider_specific_fields is not None
inner = e.provider_specific_fields["inner_error"]
assert inner["code"] == "ResponsibleAIPolicyViolation"
assert inner["content_filter_results"]["violence"]["filtered"] is True
assert inner["revised_prompt"] is not None
def test_azure_policy_violation_detected_via_inner_error_without_top_code(self):
"""When the top-level code is NOT 'content_policy_violation' but
inner_error.code IS 'ResponsibleAIPolicyViolation', the error
should still be recognized as a content policy violation."""
mock_exception = Exception("Some error")
mock_exception.body = {
"error": {
"code": "BadRequest",
"inner_error": {
"code": "ResponsibleAIPolicyViolation",
"content_filter_results": {
"violence": {"filtered": True, "severity": "medium"},
},
},
"message": "The request was rejected.",
"type": "invalid_request_error",
}
}
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
with pytest.raises(ContentPolicyViolationError) as exc_info:
exception_type(
model="azure/dall-e-3",
original_exception=mock_exception,
custom_llm_provider="azure",
)
e = exc_info.value
assert e.provider_specific_fields is not None
assert (
e.provider_specific_fields["inner_error"]["code"]
== "ResponsibleAIPolicyViolation"
)
def test_azure_image_polling_error_preserves_body(self):
"""Verify that AzureOpenAIError raised from the DALL-E polling path
carries the structured body so exception_type() can inspect it."""
from litellm.llms.azure.common_utils import AzureOpenAIError
error_payload = {
"status": "failed",
"error": {
"code": "content_policy_violation",
"message": "Your request was rejected.",
"inner_error": {
"code": "ResponsibleAIPolicyViolation",
"content_filter_results": {
"violence": {"filtered": True, "severity": "low"},
},
},
},
}
# Simulate what the fixed polling path now does
_error_body = error_payload.get("error", error_payload)
_error_msg = (
_error_body.get("message", "Image generation failed")
if isinstance(_error_body, dict)
else json.dumps(error_payload)
)
exc = AzureOpenAIError(
status_code=400,
message=_error_msg,
body=error_payload,
)
assert exc.body is not None
assert isinstance(exc.body, dict)
assert exc.body["error"]["code"] == "content_policy_violation"
assert "Your request was rejected" in exc.message
def test_azure_safety_system_message_detected_as_policy_violation(self):
"""Azure's rejection message 'Your request was rejected as a result
of our safety system' should be detected by string matching even
when the structured body is unavailable."""
mock_exception = Exception(
"Your request was rejected as a result of our safety system. "
"The revised prompt may contain text that is not allowed."
)
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
with pytest.raises(ContentPolicyViolationError):
exception_type(
model="azure/dall-e-3",
original_exception=mock_exception,
custom_llm_provider="azure",
)
def test_invalid_encrypted_content_error_with_helpful_message(self):
"""Test that invalid_encrypted_content errors include helpful guidance
about enabling encrypted_content_affinity."""
from litellm.exceptions import BadRequestError
mock_exception = Exception(
"The encrypted content gAAAAABpnW_yEYmSNEyOG... could not be verified. "
"Reason: Encrypted content organization_id did not match the target organization."
)
mock_exception.body = {
"error": {
"message": "The encrypted content could not be verified.",
"type": "invalid_request_error",
"code": "invalid_encrypted_content",
}
}
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
with pytest.raises(BadRequestError) as exc_info:
exception_type(
model="azure/gpt-5.1-codex",
original_exception=mock_exception,
custom_llm_provider="azure",
)
error = exc_info.value
assert "encrypted_content_affinity" in error.message
assert "enable_pre_call_checks" in error.message
assert "optional_pre_call_checks" in error.message
assert "docs.litellm.ai" in error.message
def test_openai_invalid_encrypted_content_error(self):
"""Test that OpenAI invalid_encrypted_content errors also get helpful guidance."""
from litellm.exceptions import BadRequestError
mock_exception = Exception("The encrypted content could not be verified.")
mock_response = MagicMock()
mock_response.status_code = 400
mock_exception.response = mock_response
with pytest.raises(BadRequestError) as exc_info:
exception_type(
model="gpt-5.1-codex",
original_exception=mock_exception,
custom_llm_provider="openai",
)
error = exc_info.value
assert "encrypted_content_affinity" in error.message
assert "enable_pre_call_checks" in error.message