litellm/tests/unit/test_shared_session_integration.py
yuneng-jiang f6882246d4
test: move tests/test_litellm root and small trees into tests/unit (#43186)
* 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: 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.

---------

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

190 lines
7 KiB
Python

"""
Integration tests for shared session functionality in main.py
"""
from unittest.mock import MagicMock, patch
import pytest
# Add the litellm directory to the path
import litellm
class TestSharedSessionIntegration:
"""Test cases for shared session integration in main.py"""
def test_acompletion_shared_session_parameter(self):
"""Test that acompletion accepts shared_session parameter"""
import inspect
# Get the function signature
sig = inspect.signature(litellm.acompletion)
params = list(sig.parameters.keys())
# Verify shared_session parameter exists
assert "shared_session" in params
# Verify the parameter type annotation
shared_session_param = sig.parameters["shared_session"]
assert "ClientSession" in str(shared_session_param.annotation)
# Verify default value is None
assert shared_session_param.default is None
def test_completion_shared_session_parameter(self):
"""Test that completion accepts shared_session parameter"""
import inspect
# Get the function signature
sig = inspect.signature(litellm.completion)
params = list(sig.parameters.keys())
# Verify shared_session parameter exists
assert "shared_session" in params
# Verify the parameter type annotation
shared_session_param = sig.parameters["shared_session"]
assert "ClientSession" in str(shared_session_param.annotation)
# Verify default value is None
assert shared_session_param.default is None
@pytest.mark.asyncio
async def test_acompletion_with_shared_session_mock(self):
"""Test acompletion with mocked shared session (no actual API call)"""
import inspect
# Create a mock session
mock_session = MagicMock()
mock_session.closed = False
# Mock the completion function to avoid actual API calls
with patch("litellm.completion") as mock_completion:
mock_completion.return_value = {
"choices": [{"message": {"content": "test"}}]
}
# This should not raise an error even though we can't make actual API calls
try:
# We can't actually call acompletion without proper setup,
# but we can verify the parameter is accepted
sig = inspect.signature(litellm.acompletion)
assert "shared_session" in sig.parameters
except Exception as e:
# Expected to fail due to missing API keys, but parameter should be valid
sig = inspect.signature(litellm.acompletion)
assert "shared_session" in sig.parameters
def test_shared_session_passed_to_completion_kwargs(self):
"""Test that shared_session is passed through completion_kwargs"""
# This test verifies that the shared_session parameter
# is properly included in the completion_kwargs dictionary
# We can't easily test the internal logic without mocking,
# but we can verify the parameter exists in the function signature
import inspect
sig = inspect.signature(litellm.acompletion)
shared_session_param = sig.parameters["shared_session"]
# Verify the parameter is properly typed
assert "ClientSession" in str(shared_session_param.annotation)
assert shared_session_param.default is None
def test_backward_compatibility(self):
"""Test that existing code without shared_session still works"""
import inspect
# Verify that shared_session has a default value of None
sig = inspect.signature(litellm.acompletion)
shared_session_param = sig.parameters["shared_session"]
# This ensures backward compatibility
assert shared_session_param.default is None
def test_type_annotations_consistency(self):
"""Test that type annotations are consistent between acompletion and completion"""
import inspect
# Get signatures for both functions
acompletion_sig = inspect.signature(litellm.acompletion)
completion_sig = inspect.signature(litellm.completion)
# Get the shared_session parameters
acompletion_param = acompletion_sig.parameters["shared_session"]
completion_param = completion_sig.parameters["shared_session"]
# Verify they have the same type annotation
assert str(acompletion_param.annotation) == str(completion_param.annotation)
# Verify they have the same default value
assert acompletion_param.default == completion_param.default
def test_shared_session_parameter_position(self):
"""Test that shared_session parameter is in the correct position"""
import inspect
sig = inspect.signature(litellm.acompletion)
params = list(sig.parameters.keys())
# Find the position of shared_session
shared_session_index = params.index("shared_session")
# It should be near the end, before **kwargs
assert shared_session_index > 0
assert shared_session_index < len(params) - 1 # Should be before **kwargs
# Verify it's after the main parameters
assert "model" in params[:shared_session_index]
assert "messages" in params[:shared_session_index]
class TestSharedSessionUsage:
"""Test cases demonstrating proper usage of shared sessions"""
def test_shared_session_usage_example(self):
"""Test example usage pattern for shared sessions"""
# This test demonstrates the expected usage pattern
# without actually making API calls
import inspect
# Verify the function signature allows for the expected usage
sig = inspect.signature(litellm.acompletion)
params = sig.parameters
# Verify all expected parameters exist
expected_params = ["model", "messages", "shared_session"]
for param in expected_params:
assert (
param in params
), f"Parameter {param} not found in acompletion signature"
# Verify shared_session is optional
assert params["shared_session"].default is None
def test_shared_session_with_other_parameters(self):
"""Test that shared_session works with other parameters"""
import inspect
sig = inspect.signature(litellm.acompletion)
params = sig.parameters
# Verify shared_session doesn't conflict with other parameters
assert "shared_session" in params
assert "model" in params
assert "messages" in params
assert "timeout" in params
# Verify the parameter order makes sense
param_list = list(params.keys())
shared_session_index = param_list.index("shared_session")
# shared_session should be after the main parameters but before **kwargs
assert shared_session_index > param_list.index("model")
assert shared_session_index > param_list.index("messages")
# Should be before **kwargs (last parameter)
assert shared_session_index < len(param_list) - 1