mirror of
https://github.com/BerriAI/litellm.git
synced 2026-09-27 01:22:18 +00:00
* 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: move tests/test_litellm integrations and secret_managers into tests/unit Rename-only. Mirrors the old paths, including the directory conftests and the prompt and JSON fixtures. Follow-up commits prune and wire them. * test: prune and repoint the moved integrations tests Deletes the 7 audited tests a stronger test in the same tree already covers, imports the TLS sink helpers from their new conftest path, and restores os.environ after each integrations test. Some presets write OTEL_EXPORTER_OTLP_HEADERS straight into os.environ, and without the legacy tree's test ordering that header leaked into the AgentOps tests. * ci: run the moved integrations tests under their legacy flag The integrations GHA shard and a new CircleCI job run the integrations unit selection. secret_managers joins the misc selection. * docs: point integrations and secret_managers references at tests/unit * test: make the moved integrations directories packages * 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: move tests/test_litellm core utils, routing, responses, caching and rust_bridge into tests/unit Rename-only. Mirrors the old paths, including fixtures, the stubtest config and the native-route wheel script. Two files that collide with existing unit files are merged in a follow-up commit. * test: merge, prune and repoint the moved core, routing, responses, caching and rust_bridge tests Merges the two files that collided with existing unit files, folding the legacy extra case into test_is_chat_completion_cached_dict, and deletes the 9 audited tests a stronger test in the same file already covers. Keeps what needs the network in tests/test_litellm: test_tokenizers pulls a tokenizer from the Hugging Face hub, and the gpt2 and r50k_base tokenizer cases download their BPE files. The unit core_utils conftest points TIKTOKEN_CACHE_DIR at litellm's bundled encodings so the rest never depend on import order to stay offline, and FakeSecretVault moves to a shared module so both trees can build it. * ci: run the moved core, routing, responses, caching and rust_bridge tests under their flags core_utils gets a core-utils flag and CircleCI job, and its GHA shard keeps the legacy path for the retained network tests. router_utils and router_strategy join enterprise-routing, responses joins responses-caching-types (minus responses/mcp, which mcp-integration owns), caching joins caching-local and rust_bridge joins misc. The redis-compat, test-rust, stubtest and merge-smoke paths follow the move. * docs: point the Rust crate references at tests/unit * test: make the moved core, routing and rust_bridge directories packages * test: keep the no-loop DualCache batch_get_cache regression test It runs the sync path outside any event loop, which the inside-loop test cannot, so a change that picks the Redis client by loop state would only show up there. * test: keep the job's UNIT_FLAG out of the shard-script tests * fix(url_utils): block 192.0.0.0/24 on every Python patch release * test: move the new budget limiter tests into tests/unit/router_strategy * test: move the new sentry scrubbing tests into tests/unit/litellm_core_utils * test: move the new zerobus tests into tests/unit/integrations * test: make tests/unit/integrations/zerobus a package * test: load litellm's own tiktoken cache setup once instead of resetting it per test --------- Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
298 lines
9.9 KiB
Python
298 lines
9.9 KiB
Python
"""
|
|
Tests for Router interactions API endpoint initialization functions.
|
|
"""
|
|
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
|
|
import pytest
|
|
|
|
from litellm import Router
|
|
|
|
|
|
class TestInitializeInteractionsEndpoints:
|
|
"""Test cases for _initialize_interactions_endpoints method"""
|
|
|
|
def test_initialize_interactions_endpoints_creates_methods(self):
|
|
"""Test that _initialize_interactions_endpoints creates the expected interaction methods on the router."""
|
|
router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "gpt-4",
|
|
"litellm_params": {"model": "gpt-4"},
|
|
}
|
|
]
|
|
)
|
|
|
|
# Verify the interaction methods are created
|
|
assert hasattr(router, "acreate_interaction")
|
|
assert hasattr(router, "create_interaction")
|
|
assert hasattr(router, "aget_interaction")
|
|
assert hasattr(router, "get_interaction")
|
|
assert hasattr(router, "adelete_interaction")
|
|
assert hasattr(router, "delete_interaction")
|
|
assert hasattr(router, "acancel_interaction")
|
|
assert hasattr(router, "cancel_interaction")
|
|
|
|
# Verify they are callable
|
|
assert callable(router.acreate_interaction)
|
|
assert callable(router.create_interaction)
|
|
assert callable(router.aget_interaction)
|
|
assert callable(router.get_interaction)
|
|
|
|
def test_initialize_interactions_endpoints_can_be_called_directly(self):
|
|
"""Test that _initialize_interactions_endpoints can be called directly to reinitialize endpoints."""
|
|
router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "gpt-4",
|
|
"litellm_params": {"model": "gpt-4"},
|
|
}
|
|
]
|
|
)
|
|
|
|
# Call _initialize_interactions_endpoints directly
|
|
router._initialize_interactions_endpoints()
|
|
|
|
# Verify the interaction methods still exist after re-initialization
|
|
assert hasattr(router, "acreate_interaction")
|
|
assert hasattr(router, "create_interaction")
|
|
assert callable(router.acreate_interaction)
|
|
|
|
|
|
class TestInitInteractionsApiEndpoints:
|
|
"""Test cases for _init_interactions_api_endpoints method"""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_interactions_api_endpoints_passes_custom_llm_provider(self):
|
|
"""Test that _init_interactions_api_endpoints passes custom_llm_provider to the original function."""
|
|
router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "gpt-4",
|
|
"litellm_params": {"model": "gpt-4"},
|
|
}
|
|
]
|
|
)
|
|
|
|
mock_function = AsyncMock(return_value={"result": "success"})
|
|
|
|
result = await router._init_interactions_api_endpoints(
|
|
original_function=mock_function,
|
|
custom_llm_provider="gemini",
|
|
interaction_id="test-id",
|
|
)
|
|
|
|
mock_function.assert_called_once_with(
|
|
custom_llm_provider="gemini",
|
|
interaction_id="test-id",
|
|
)
|
|
assert result == {"result": "success"}
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_interactions_api_endpoints_defaults_to_gemini(self):
|
|
"""Test that _init_interactions_api_endpoints defaults to gemini when no custom_llm_provider is specified."""
|
|
router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "gpt-4",
|
|
"litellm_params": {"model": "gpt-4"},
|
|
}
|
|
]
|
|
)
|
|
|
|
mock_function = AsyncMock(return_value={"result": "success"})
|
|
|
|
result = await router._init_interactions_api_endpoints(
|
|
original_function=mock_function,
|
|
interaction_id="test-id",
|
|
)
|
|
|
|
mock_function.assert_called_once_with(
|
|
custom_llm_provider="gemini",
|
|
interaction_id="test-id",
|
|
)
|
|
assert result == {"result": "success"}
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_interactions_api_endpoints_does_not_override_existing_provider(
|
|
self,
|
|
):
|
|
"""Test that _init_interactions_api_endpoints does not override custom_llm_provider if already in kwargs."""
|
|
router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "gpt-4",
|
|
"litellm_params": {"model": "gpt-4"},
|
|
}
|
|
]
|
|
)
|
|
|
|
mock_function = AsyncMock(return_value={"result": "success"})
|
|
|
|
# Pass custom_llm_provider in kwargs directly (not as separate param)
|
|
result = await router._init_interactions_api_endpoints(
|
|
original_function=mock_function,
|
|
custom_llm_provider="vertex_ai",
|
|
)
|
|
|
|
# Should use the provided custom_llm_provider
|
|
mock_function.assert_called_once_with(
|
|
custom_llm_provider="vertex_ai",
|
|
)
|
|
assert result == {"result": "success"}
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_interactions_api_endpoints_clears_model_when_equals_agent(
|
|
self,
|
|
):
|
|
"""Managed agent interactions must not pass agent name as model to the SDK."""
|
|
router = Router(model_list=[])
|
|
|
|
mock_function = AsyncMock(return_value={"result": "success"})
|
|
|
|
await router._init_interactions_api_endpoints(
|
|
original_function=mock_function,
|
|
agent="mqy-custom-slides-agent",
|
|
model="mqy-custom-slides-agent",
|
|
input="hello",
|
|
)
|
|
|
|
mock_function.assert_called_once_with(
|
|
custom_llm_provider="gemini",
|
|
agent="mqy-custom-slides-agent",
|
|
model=None,
|
|
input="hello",
|
|
)
|
|
|
|
|
|
class TestRouterCreateInteractionRouting:
|
|
"""acreate_interaction routing: agent-only vs model + fallbacks."""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_acreate_interaction_agent_only_uses_init_interactions(self):
|
|
"""Agent-only create must not use model-group fallback lookup."""
|
|
router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "openai/*",
|
|
"litellm_params": {"model": "gpt-4"},
|
|
}
|
|
]
|
|
)
|
|
|
|
with (
|
|
patch.object(
|
|
router,
|
|
"_init_interactions_api_endpoints",
|
|
new_callable=AsyncMock,
|
|
return_value={"id": "int-1"},
|
|
) as mock_init,
|
|
patch.object(
|
|
router,
|
|
"_ageneric_api_call_with_fallbacks",
|
|
new_callable=AsyncMock,
|
|
) as mock_generic,
|
|
):
|
|
result = await router.acreate_interaction(
|
|
agent="mqy-custom-slides-agent",
|
|
input="hello",
|
|
custom_llm_provider="gemini",
|
|
)
|
|
|
|
mock_init.assert_called_once()
|
|
mock_generic.assert_not_called()
|
|
assert result == {"id": "int-1"}
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_interactions_model_uses_generic_fallbacks(self):
|
|
"""Model-based create uses _ageneric_api_call_with_fallbacks inside _init_interactions."""
|
|
router = Router(model_list=[])
|
|
|
|
with patch.object(
|
|
router,
|
|
"_ageneric_api_call_with_fallbacks",
|
|
new_callable=AsyncMock,
|
|
return_value={"id": "int-1"},
|
|
) as mock_generic:
|
|
result = await router._init_interactions_api_endpoints(
|
|
original_function=AsyncMock(),
|
|
model="gemini-2.5-flash",
|
|
input="hello",
|
|
custom_llm_provider="gemini",
|
|
)
|
|
|
|
mock_generic.assert_called_once()
|
|
assert result == {"id": "int-1"}
|
|
|
|
|
|
class TestInitializeManagedAgentsEndpoints:
|
|
"""Tests for _initialize_managed_agents_endpoints."""
|
|
|
|
def test_initialize_managed_agents_endpoints_creates_methods(self):
|
|
router = Router(
|
|
model_list=[
|
|
{
|
|
"model_name": "gpt-4",
|
|
"litellm_params": {"model": "gpt-4"},
|
|
}
|
|
]
|
|
)
|
|
|
|
for method_name in (
|
|
"acreate_agent",
|
|
"alist_agents",
|
|
"aget_agent",
|
|
"adelete_agent",
|
|
"alist_agent_versions",
|
|
):
|
|
assert hasattr(router, method_name), f"missing {method_name}"
|
|
assert callable(getattr(router, method_name)), f"{method_name} not callable"
|
|
|
|
def test_initialize_managed_agents_endpoints_can_be_called_directly(self):
|
|
router = Router(model_list=[])
|
|
router._initialize_managed_agents_endpoints()
|
|
assert callable(router.acreate_agent)
|
|
assert callable(router.alist_agents)
|
|
|
|
|
|
class TestInitManagedAgentsApiEndpoints:
|
|
"""Tests for _init_managed_agents_api_endpoints."""
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_managed_agents_api_endpoints_defaults_to_gemini(self):
|
|
router = Router(model_list=[])
|
|
mock_fn = AsyncMock(return_value={"agents": []})
|
|
|
|
await router._init_managed_agents_api_endpoints(
|
|
original_function=mock_fn,
|
|
)
|
|
|
|
call_kwargs = mock_fn.call_args.kwargs
|
|
assert call_kwargs["custom_llm_provider"] == "gemini"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_managed_agents_api_endpoints_passes_custom_provider(self):
|
|
router = Router(model_list=[])
|
|
mock_fn = AsyncMock(return_value={"agents": []})
|
|
|
|
await router._init_managed_agents_api_endpoints(
|
|
original_function=mock_fn,
|
|
custom_llm_provider="vertex_ai",
|
|
)
|
|
|
|
call_kwargs = mock_fn.call_args.kwargs
|
|
assert call_kwargs["custom_llm_provider"] == "vertex_ai"
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_init_managed_agents_api_endpoints_does_not_override_existing_provider(
|
|
self,
|
|
):
|
|
router = Router(model_list=[])
|
|
mock_fn = AsyncMock(return_value={"agents": []})
|
|
|
|
await router._init_managed_agents_api_endpoints(
|
|
original_function=mock_fn,
|
|
custom_llm_provider="vertex_ai",
|
|
)
|
|
|
|
mock_fn.assert_called_once_with(custom_llm_provider="vertex_ai")
|