litellm/tests/unit/llms/custom_httpx/test_aiohttp_handler.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

453 lines
16 KiB
Python

from unittest.mock import AsyncMock, Mock, patch
import aiohttp
import pytest
import litellm
from litellm.llms.custom_httpx.aiohttp_handler import BaseLLMAIOHTTPHandler
from litellm.llms.custom_httpx.aiohttp_transport import LiteLLMAiohttpTransport
class TestBaseLLMAIOHTTPHandler:
"""Test cases for BaseLLMAIOHTTPHandler dependency injection functionality"""
def test_init_with_no_client_session(self):
"""Test handler initialization with no client session"""
handler = BaseLLMAIOHTTPHandler()
assert handler.client_session is None
assert handler._owns_session is True
def test_init_with_provided_client_session(self):
"""Test handler initialization with provided client session"""
# Create a mock client session
mock_session = Mock()
handler = BaseLLMAIOHTTPHandler(client_session=mock_session)
assert handler.client_session is mock_session
assert handler._owns_session is False
def test_get_async_client_session_with_dynamic_session(self):
"""Test _get_async_client_session with dynamic session parameter"""
handler = BaseLLMAIOHTTPHandler()
dynamic_session = Mock()
result = handler._get_async_client_session(
dynamic_client_session=dynamic_session
)
assert result is dynamic_session
def test_get_async_client_session_with_instance_session(self):
"""Test _get_async_client_session with instance session"""
instance_session = Mock()
handler = BaseLLMAIOHTTPHandler(client_session=instance_session)
result = handler._get_async_client_session()
assert result is instance_session
@patch("aiohttp.ClientSession")
def test_get_async_client_session_create_new(self, mock_client_session):
"""Test _get_async_client_session creates new session when none provided"""
handler = BaseLLMAIOHTTPHandler()
mock_session_instance = Mock()
mock_client_session.return_value = mock_session_instance
result = handler._get_async_client_session()
# Verify new session was created
mock_client_session.assert_called_once()
assert handler.client_session is mock_session_instance
assert handler._owns_session is True
assert result is mock_session_instance
@pytest.mark.asyncio
async def test_close_with_owned_session(self):
"""Test close() method with owned session"""
# Create a mock session that we own
mock_session = Mock()
mock_session.closed = False
mock_session.close = AsyncMock()
# Create handler that owns the session
handler = BaseLLMAIOHTTPHandler()
handler.client_session = mock_session
handler._owns_session = True
await handler.close()
# Verify close was called
mock_session.close.assert_called_once()
@pytest.mark.asyncio
async def test_close_with_non_owned_session(self):
"""Test close() method with non-owned session (should not close)"""
# Create a mock session that we don't own
mock_session = Mock()
mock_session.closed = False
mock_session.close = AsyncMock()
handler = BaseLLMAIOHTTPHandler(client_session=mock_session)
await handler.close()
# Verify close was NOT called since we don't own this session
mock_session.close.assert_not_called()
@pytest.mark.asyncio
async def test_close_with_already_closed_session(self):
"""Test close() method with already closed session"""
mock_session = Mock()
mock_session.closed = True
mock_session.close = AsyncMock()
handler = BaseLLMAIOHTTPHandler()
handler.client_session = mock_session
handler._owns_session = True
await handler.close()
# Verify close was NOT called since session is already closed
mock_session.close.assert_not_called()
@pytest.mark.asyncio
async def test_close_with_no_session(self):
"""Test close() method with no session"""
handler = BaseLLMAIOHTTPHandler()
# Should not raise any exceptions
await handler.close()
def test_session_priority_dynamic_over_instance(self):
"""Test that dynamic session takes priority over instance session"""
instance_session = Mock()
dynamic_session = Mock()
handler = BaseLLMAIOHTTPHandler(client_session=instance_session)
result = handler._get_async_client_session(
dynamic_client_session=dynamic_session
)
assert result is dynamic_session
assert result is not instance_session
def test_session_ownership_tracking(self):
"""Test proper session ownership tracking in various scenarios"""
# Scenario 1: Provided session - not owned
provided_session = Mock()
handler1 = BaseLLMAIOHTTPHandler(client_session=provided_session)
assert not handler1._owns_session
# Scenario 2: No session initially - becomes owned when created
handler2 = BaseLLMAIOHTTPHandler()
assert handler2._owns_session
with patch("aiohttp.ClientSession") as mock_client_session:
mock_session_instance = Mock()
mock_client_session.return_value = mock_session_instance
handler2._get_async_client_session()
assert handler2._owns_session
@pytest.mark.asyncio
async def test_context_manager_pattern_compatibility(self):
"""Test that the handler works well with context manager pattern"""
mock_session = Mock()
mock_session.closed = False
mock_session.close = AsyncMock()
# Test as context manager style usage
handler = BaseLLMAIOHTTPHandler()
handler.client_session = mock_session
handler._owns_session = True
try:
# Simulate some work
session = handler._get_async_client_session()
assert session is mock_session
finally:
await handler.close()
# Verify cleanup happened
mock_session.close.assert_called_once()
@patch("litellm.llms.custom_httpx.aiohttp_handler.aiohttp.ClientSession")
def test_lazy_session_creation(self, mock_client_session):
"""Test that session is created lazily only when needed"""
handler = BaseLLMAIOHTTPHandler()
# Session should not be created on init
mock_client_session.assert_not_called()
assert handler.client_session is None
# Session should be created when requested
mock_session_instance = Mock()
mock_client_session.return_value = mock_session_instance
session = handler._get_async_client_session()
mock_client_session.assert_called_once()
assert session is mock_session_instance
assert handler.client_session is mock_session_instance
def test_session_reuse(self):
"""Test that the same session is reused across multiple calls"""
instance_session = Mock()
handler = BaseLLMAIOHTTPHandler(client_session=instance_session)
# Multiple calls should return the same session
session1 = handler._get_async_client_session()
session2 = handler._get_async_client_session()
session3 = handler._get_async_client_session()
assert session1 is session2 is session3 is instance_session
# ===============================
# TRANSPORT INJECTION TESTS
# ===============================
def test_init_with_transport(self):
"""Test handler initialization with provided transport"""
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
handler = BaseLLMAIOHTTPHandler(transport=mock_transport)
assert handler.transport is mock_transport
assert handler._owns_transport is False
def test_init_with_connector(self):
"""Test handler initialization with provided connector"""
mock_connector = Mock(spec=aiohttp.BaseConnector)
handler = BaseLLMAIOHTTPHandler(connector=mock_connector)
assert handler.connector is mock_connector
assert handler._owns_connector is False
def test_init_with_transport_and_session(self):
"""Test handler initialization with both transport and session"""
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
mock_session = Mock()
handler = BaseLLMAIOHTTPHandler(
client_session=mock_session, transport=mock_transport
)
assert handler.transport is mock_transport
assert handler._owns_transport is False
assert handler.client_session is mock_session
assert handler._owns_session is False
def test_get_connector_from_provided_connector(self):
"""Test _get_connector returns provided connector"""
mock_connector = Mock(spec=aiohttp.BaseConnector)
handler = BaseLLMAIOHTTPHandler(connector=mock_connector)
result = handler._get_connector()
assert result is mock_connector
def test_get_connector_from_transport(self):
"""Test _get_connector extracts connector from transport"""
mock_connector = Mock(spec=aiohttp.BaseConnector)
# Use a simple object instead of Mock to avoid callable issues
class MockSession:
def __init__(self):
self.connector = mock_connector
mock_session = MockSession()
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
mock_transport.client = mock_session
handler = BaseLLMAIOHTTPHandler(transport=mock_transport)
result = handler._get_connector()
assert result is mock_connector
def test_get_connector_from_transport_with_callable_client(self):
"""Test _get_connector with transport that has callable client"""
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
mock_transport.client = lambda: Mock() # Callable client
handler = BaseLLMAIOHTTPHandler(transport=mock_transport)
result = handler._get_connector()
assert result is None
@patch("aiohttp.ClientSession")
def test_create_client_session_with_transport(self, mock_client_session):
"""Test session creation using transport"""
mock_session_from_transport = Mock()
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
mock_transport._get_valid_client_session = Mock(
return_value=mock_session_from_transport
)
handler = BaseLLMAIOHTTPHandler(transport=mock_transport)
result = handler._create_client_session_with_transport()
# Should use transport's session creation method
mock_transport._get_valid_client_session.assert_called_once()
assert result is mock_session_from_transport
# Should not call aiohttp.ClientSession directly
mock_client_session.assert_not_called()
@patch("aiohttp.ClientSession")
def test_create_client_session_with_connector(self, mock_client_session):
"""Test session creation using connector"""
mock_connector = Mock(spec=aiohttp.BaseConnector)
mock_session_instance = Mock()
mock_client_session.return_value = mock_session_instance
handler = BaseLLMAIOHTTPHandler(connector=mock_connector)
result = handler._create_client_session_with_transport()
# Should create session with connector
mock_client_session.assert_called_once_with(connector=mock_connector)
assert result is mock_session_instance
@pytest.mark.asyncio
async def test_create_client_session_default_honors_global_ssl_verify_false(
self, monkeypatch: pytest.MonkeyPatch
):
"""Regression test for LIT-3369: `litellm.ssl_verify = False` (set via
`litellm_settings.ssl_verify: false`) must reach the default session's
connector instead of being ignored by a bare `aiohttp.ClientSession()`."""
monkeypatch.setattr(litellm, "ssl_verify", False)
handler = BaseLLMAIOHTTPHandler()
session = handler._create_client_session_with_transport()
try:
assert isinstance(session.connector, aiohttp.TCPConnector)
assert session.connector._ssl is False
finally:
await session.close()
await handler.close()
@pytest.mark.asyncio
async def test_create_client_session_default_keeps_ssl_verification(self):
"""Default `ssl_verify=True` must not collapse to `ssl=False`."""
handler = BaseLLMAIOHTTPHandler()
session = handler._create_client_session_with_transport()
try:
assert isinstance(session.connector, aiohttp.TCPConnector)
assert session.connector._ssl is not False
finally:
await session.close()
await handler.close()
def test_get_or_create_transport_resolves_global_ssl_verify(
self, monkeypatch: pytest.MonkeyPatch
):
"""The lazily created transport must carry the resolved global ssl config."""
monkeypatch.setattr(litellm, "ssl_verify", False)
handler = BaseLLMAIOHTTPHandler()
transport = handler._get_or_create_transport()
assert transport is not None
assert transport._ssl_verify is False
def test_get_or_create_transport(self):
"""Test that _get_or_create_transport creates or returns a transport.
When no transport exists, the method should attempt to create one.
If creation succeeds, it should be stored on the handler.
If creation fails (e.g. in test environments), None is returned gracefully.
"""
handler = BaseLLMAIOHTTPHandler()
assert handler.transport is None # no transport initially
result = handler._get_or_create_transport()
# The method should either create a transport or gracefully return None
if result is not None:
assert handler.transport is result
assert handler._owns_transport is True
assert isinstance(result, LiteLLMAiohttpTransport)
else:
# Creation can fail in test environments without full aiohttp setup
# This is the graceful fallback path
pass
def test_get_or_create_transport_with_existing(self):
"""Test _get_or_create_transport returns existing transport"""
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
handler = BaseLLMAIOHTTPHandler(transport=mock_transport)
result = handler._get_or_create_transport()
assert result is mock_transport
@pytest.mark.asyncio
async def test_close_with_owned_transport(self):
"""Test close() method with owned transport"""
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
mock_transport.aclose = AsyncMock()
handler = BaseLLMAIOHTTPHandler()
handler.transport = mock_transport
handler._owns_transport = True
await handler.close()
# Verify transport close was called
mock_transport.aclose.assert_called_once()
@pytest.mark.asyncio
async def test_close_with_non_owned_transport(self):
"""Test close() method with non-owned transport (should not close)"""
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
mock_transport.aclose = AsyncMock()
handler = BaseLLMAIOHTTPHandler(transport=mock_transport)
await handler.close()
# Verify transport close was NOT called since we don't own this transport
mock_transport.aclose.assert_not_called()
@pytest.mark.asyncio
async def test_close_transport_without_aclose_method(self):
"""Test close() handles transport without aclose method gracefully"""
mock_transport = Mock() # No aclose method
handler = BaseLLMAIOHTTPHandler()
handler.transport = mock_transport
handler._owns_transport = True
# Should not raise any exceptions
await handler.close()
def test_transport_priority_hierarchy(self):
"""Test that session creation follows the right priority: transport > connector > default"""
# Test with transport having _get_valid_client_session
mock_transport = Mock(spec=LiteLLMAiohttpTransport)
mock_session_from_transport = Mock()
mock_transport._get_valid_client_session = Mock(
return_value=mock_session_from_transport
)
mock_connector = Mock(spec=aiohttp.BaseConnector)
handler = BaseLLMAIOHTTPHandler(
transport=mock_transport, connector=mock_connector
)
result = handler._create_client_session_with_transport()
# Should use transport, not connector
mock_transport._get_valid_client_session.assert_called_once()
assert result is mock_session_from_transport