litellm/tests/unit/llms/openai/test_openai.py
yuneng-jiang 5e6dc89ba1
test: move tests/test_litellm/llms into tests/unit/llms (#43191)
* ci: run the unit_selection.sh shard files on every event instead of only fork pull requests

Co-Authored-By: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>

* ci: rename fork-flag to unit-flag now that it applies on every event

* test: move tests/test_litellm root and small trees into tests/unit

Pure renames, no content changes. Follow-up commits in this PR fix
references, merge the three files that already existed in tests/unit,
keep live-provider tests in tests/test_litellm and wire CI.

* test: carry tests/test_litellm conftest isolation into tests/unit

Callback lists, routing fallbacks, cached HTTP clients, logger state, AWS,
proxy-URL and keychain env, and session-end client cleanup now reset for
unit tests too. The environment isolation owns its MonkeyPatch so a test's
own monkeypatch is undone before the model-cost teardown runs.

* test: merge, split and prune the moved root and small-tree tests

Merge batches/test_batch_utils.py and the chat_completions and messages
dispatch tests into the files that already existed in tests/unit. Keep
the live Gemini interactions tests, the async image-fetch format test and
the OpenAI embedding scorer test in tests/test_litellm since they need
real network or keys. Put test_router.py under tests/unit/test_router so
the existing package no longer shadows it. Delete eight tests the audit
found superseded by stronger ones kept in this move.

* ci: run the moved root and small-tree tests under their legacy flags

Add the misc and responses-caching-types flags to unit_selection.sh and
CircleCI, extend enterprise-routing and mcp-integration, and point the
legacy GHA shards, Makefile, redis-compat workflow, merge smoke manifest
and change classifier at the new paths.

* test: make the new tests/unit directories packages

tests/unit/test_package_layout.py requires every directory to carry an
__init__.py, and without one the moved and retained
test_litellm_responses_bridge.py modules collide on import.

* test: scope the unit socket block to tests/unit in shared sessions

The GHA shards collect the legacy test-path and the unit selection in one
pytest session. The unit conftest's loopback-only block leaked into legacy
modules that reach the network at import. The legacy conftest now lifts the
restriction at collect and setup time, and the unit conftest re-applies it
when collecting its own modules.

* test: move tests/test_litellm/llms into tests/unit/llms

Rename-only. Moves the provider tests and the fine-tuning fixtures they
load, mirroring the old paths. Follow-up commits merge, split and wire them.

* test: merge, split and prune the moved llms tests

Merges the Databricks chat transformation tests into the existing unit
file, keeps the tests that need real keys or the network in
tests/test_litellm, deletes the audited tests a stronger unit test
already covers, and points imports at tests.unit.llms.

* ci: run the moved llms tests under their legacy flags

The Vertex AI and All Other Providers shards keep their legacy test-path
for the retained files and add the llm-vertex-ai and llm-other-providers
unit selections. CircleCI gets matching unit jobs.

* test: make the tests/unit/llms directories packages

Adds __init__.py to the moved dirs and drops the legacy ones whose
directories no longer hold tests.

* test: drop script runners and path hacks the llms split left dangling

The __main__ runners in the split openai_like files and the Databricks e2e
runner called tests that now live in the other half of the split or were
deleted. The retained legacy halves also no longer need sys.path edits.

* test: give the shard-script tests their own GITHUB_OUTPUT

They only passed where the runner set it. The CircleCI unit job's env
allowlist drops it, so the script's redirect failed there.

* test: point the router and module-deletion checks at tests/unit

router_code_coverage and code_qa_check_tests only searched tests/test_litellm,
so the moved router tests no longer counted. The two silent-experiment tests
the audit deleted were the only direct callers of those methods; they are
replaced with tests that assert the forwarded shadow request and the
recursion guard.

* test: keep the Databricks manual e2e runner and fix the SageMaker Nova run path

The Databricks e2e file is a manual script whose main() calls the tests
that were pruned, so pruning them broke the documented run. It is back to
its main version. The SageMaker Nova docstring now points at the file's
real location in tests/local_testing.

* test: keep the job's UNIT_FLAG out of the shard-script tests

---------

Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
2026-09-25 12:43:23 -07:00

352 lines
13 KiB
Python

import asyncio
import json
from typing import Final
from unittest.mock import Mock
import httpx
import pytest
from openai import AsyncOpenAI, OpenAI
import litellm
from litellm.llms.openai.openai import OpenAIChatCompletion
from litellm.types.utils import ImageResponse
@pytest.mark.parametrize(
"api_base",
[
None,
"https://api.openai.com/v1",
"https://api.openai.com:443/v1",
"https://southcentralus.privatelink.api.openai.com/v1",
"https://eu.api.openai.com/v1",
"https://us.api.openai.com/v1",
"HTTPS://API.OPENAI.COM/v1/",
],
)
def test_get_stream_options_defaults_include_usage_on_every_openai_backed_host(api_base):
"""
PrivateLink and regional hostnames reach the real OpenAI backend, so a stream with no caller
stream_options must ask for the usage chunk exactly as the default base does. Regression guard
for LIT-6875: spend for those deployments fell back to local token counting.
"""
assert OpenAIChatCompletion().get_stream_options(stream_options=None, api_base=api_base) == {
"stream_options": {"include_usage": True}
}
@pytest.mark.parametrize(
"api_base",
[
"https://my-gateway.example/v1",
"https://api.openai.com.evil.example/v1",
"https://notapi.openai.com/v1",
"https://gateway.example/v1?upstream=api.openai.com",
"https://openai.internal.example/api.openai.com/v1",
],
)
def test_get_stream_options_leaves_foreign_hosts_without_a_usage_default(api_base):
"""Only the host decides: an OpenAI-compatible backend elsewhere may not support stream_options at all."""
assert OpenAIChatCompletion().get_stream_options(stream_options=None, api_base=api_base) == {}
@pytest.mark.parametrize(
"api_base",
["https://southcentralus.privatelink.api.openai.com/v1", "https://my-gateway.example/v1"],
)
def test_get_stream_options_passes_caller_stream_options_through_on_any_host(api_base):
caller_options = {"include_usage": False}
assert OpenAIChatCompletion().get_stream_options(stream_options=caller_options, api_base=api_base) == {
"stream_options": caller_options
}
@pytest.mark.asyncio
async def test_acompletion_returns_json_reply_over_injected_transport():
outbound: Final = asyncio.Queue()
def respond(request: httpx.Request) -> httpx.Response:
outbound.put_nowait(json.loads(request.content))
return httpx.Response(
200,
json={
"id": "chatcmpl-smoke",
"object": "chat.completion",
"created": 0,
"model": "gpt-5.6",
"choices": [
{
"index": 0,
"message": {"role": "assistant", "content": "smoke-json-reply"},
"finish_reason": "stop",
}
],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
},
)
async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client:
client: Final = AsyncOpenAI(api_key="transport-only", http_client=http_client)
response: Final = await asyncio.wait_for(
litellm.acompletion(
model="openai/gpt-5.6",
api_key="transport-only",
client=client,
messages=[{"role": "user", "content": "smoke-json-request"}],
num_retries=0,
max_retries=0,
),
timeout=10,
)
request: Final = await asyncio.wait_for(outbound.get(), timeout=10)
assert request["model"] == "gpt-5.6"
assert request["messages"] == [{"role": "user", "content": "smoke-json-request"}]
assert not request.get("stream")
assert outbound.empty()
assert response.choices[0].message.content == "smoke-json-reply"
assert response.choices[0].finish_reason == "stop"
assert response.usage.total_tokens == 15
@pytest.mark.asyncio
async def test_acompletion_streams_text_deltas_over_injected_transport():
outbound: Final = asyncio.Queue()
def chunk(delta: dict, finish: str | None) -> bytes:
body: Final = {
"id": "chatcmpl-smoke",
"object": "chat.completion.chunk",
"created": 0,
"model": "gpt-5.6",
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
}
return f"data: {json.dumps(body)}\n\n".encode()
def respond(request: httpx.Request) -> httpx.Response:
outbound.put_nowait(json.loads(request.content))
usage: Final = {
"id": "chatcmpl-smoke",
"object": "chat.completion.chunk",
"created": 0,
"model": "gpt-5.6",
"choices": [],
"usage": {"prompt_tokens": 10, "completion_tokens": 5, "total_tokens": 15},
}
content: Final = b"".join(
(
chunk({"role": "assistant", "content": "Hel"}, None),
chunk({"content": "lo"}, "stop"),
f"data: {json.dumps(usage)}\n\n".encode(),
b"data: [DONE]\n\n",
)
)
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=content)
async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client:
client: Final = AsyncOpenAI(api_key="transport-only", http_client=http_client)
stream: Final = await litellm.acompletion(
model="openai/gpt-5.6",
api_key="transport-only",
client=client,
messages=[{"role": "user", "content": "smoke-stream-request"}],
stream=True,
num_retries=0,
max_retries=0,
)
chunks: Final = []
async def drain() -> None:
async for part in stream:
chunks.append(part)
await asyncio.wait_for(drain(), timeout=10)
request: Final = await asyncio.wait_for(outbound.get(), timeout=10)
assert request["stream"] is True
assert outbound.empty()
assert (
"".join(part.choices[0].delta.content or "" for part in chunks if part.choices and part.choices[0].delta)
== "Hello"
)
last_finish: Final = next(
part.choices[0].finish_reason for part in reversed(chunks) if part.choices and part.choices[0].finish_reason
)
assert last_finish == "stop"
@pytest.mark.asyncio
async def test_acompletion_streams_tool_call_arguments_over_injected_transport():
outbound: Final = asyncio.Queue()
tools: Final = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Look up weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
},
}
]
def chunk(delta: dict, finish: str | None) -> bytes:
body: Final = {
"id": "chatcmpl-smoke",
"object": "chat.completion.chunk",
"created": 0,
"model": "gpt-5.6",
"choices": [{"index": 0, "delta": delta, "finish_reason": finish}],
}
return f"data: {json.dumps(body)}\n\n".encode()
def respond(request: httpx.Request) -> httpx.Response:
outbound.put_nowait(json.loads(request.content))
content: Final = b"".join(
(
chunk(
{
"tool_calls": [
{
"index": 0,
"id": "call-1",
"type": "function",
"function": {"name": "get_weather", "arguments": ""},
}
]
},
None,
),
chunk({"tool_calls": [{"index": 0, "function": {"arguments": '{"city":'}}]}, None),
chunk({"tool_calls": [{"index": 0, "function": {"arguments": '"Paris"}'}}]}, "tool_calls"),
b"data: [DONE]\n\n",
)
)
return httpx.Response(200, headers={"content-type": "text/event-stream"}, content=content)
async with httpx.AsyncClient(transport=httpx.MockTransport(respond)) as http_client:
client: Final = AsyncOpenAI(api_key="transport-only", http_client=http_client)
messages: Final = [{"role": "user", "content": "weather in Paris"}]
stream: Final = await litellm.acompletion(
model="openai/gpt-4o",
api_key="transport-only",
client=client,
messages=messages,
tools=tools,
stream=True,
num_retries=0,
max_retries=0,
)
chunks: Final = []
async def drain() -> None:
async for part in stream:
chunks.append(part)
await asyncio.wait_for(drain(), timeout=10)
request: Final = await asyncio.wait_for(outbound.get(), timeout=10)
assert request["stream"] is True
assert request["tools"][0]["function"]["name"] == "get_weather"
assert outbound.empty()
rebuilt: Final = litellm.stream_chunk_builder(chunks, messages=messages)
tool_call: Final = rebuilt.choices[0].message.tool_calls[0]
assert tool_call.id == "call-1"
assert tool_call.function.name == "get_weather"
assert json.loads(tool_call.function.arguments) == {"city": "Paris"}
assert rebuilt.choices[0].finish_reason == "tool_calls"
_PROVIDER_HEADERS: Final = {"x-request-id": "req_openai", "x-ratelimit-remaining-requests": "41"}
def _image_generation_transport() -> httpx.MockTransport:
return httpx.MockTransport(
lambda request: httpx.Response(
200, json={"created": 1, "data": [{"b64_json": "abc"}]}, headers=_PROVIDER_HEADERS
)
)
def _speech_transport() -> httpx.MockTransport:
return httpx.MockTransport(
lambda request: httpx.Response(
200, content=b"audio-bytes", headers={**_PROVIDER_HEADERS, "content-type": "audio/mpeg"}
)
)
def _assert_provider_headers_recorded(response) -> None:
assert response._hidden_params["headers"]["x-request-id"] == "req_openai"
assert response._hidden_params["additional_headers"]["llm_provider-x-request-id"] == "req_openai"
assert response._hidden_params["additional_headers"]["x-ratelimit-remaining-requests"] == "41"
def _image_generation_kwargs() -> dict:
return {
"model": "gpt-image-2",
"prompt": "a cat",
"timeout": 10,
"optional_params": {},
"logging_obj": Mock(),
"api_key": "transport-only",
"model_response": ImageResponse(),
}
def test_image_generation_records_provider_response_headers():
with httpx.Client(transport=_image_generation_transport()) as http_client:
response = OpenAIChatCompletion().image_generation(
client=OpenAI(api_key="transport-only", http_client=http_client), **_image_generation_kwargs()
)
_assert_provider_headers_recorded(response)
@pytest.mark.asyncio
async def test_aimage_generation_records_provider_response_headers():
async with httpx.AsyncClient(transport=_image_generation_transport()) as http_client:
response = await OpenAIChatCompletion().image_generation(
client=AsyncOpenAI(api_key="transport-only", http_client=http_client),
aimg_generation=True,
**_image_generation_kwargs(),
)
_assert_provider_headers_recorded(response)
def _audio_speech_kwargs() -> dict:
return {
"model": "gpt-4o-mini-tts",
"input": "hello",
"voice": "alloy",
"optional_params": {},
"api_key": "transport-only",
"api_base": None,
"organization": None,
"project": None,
"max_retries": 0,
"timeout": 10,
"logging_obj": Mock(),
}
def test_audio_speech_records_provider_response_headers():
with httpx.Client(transport=_speech_transport()) as http_client:
response = OpenAIChatCompletion().audio_speech(
client=OpenAI(api_key="transport-only", http_client=http_client), **_audio_speech_kwargs()
)
_assert_provider_headers_recorded(response)
@pytest.mark.asyncio
async def test_async_audio_speech_records_provider_response_headers():
async with httpx.AsyncClient(transport=_speech_transport()) as http_client:
response = await OpenAIChatCompletion().audio_speech(
client=AsyncOpenAI(api_key="transport-only", http_client=http_client),
aspeech=True,
**_audio_speech_kwargs(),
)
_assert_provider_headers_recorded(response)