Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

test: migrate proxy security, schema migration and MCP legacy tests (#45937)

devin-ai-integration[bot]102619d47a78
diff --git a/.circleci/config.yml b/.circleci/config.yml
index 40ed959ff29..ceeb4b5fbf8 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -1260,6 +1260,16 @@ jobs:
- run:
name: Build the candidate dashboard
command: cd ui/litellm-dashboard && NEXT_TELEMETRY_DISABLED=1 npm run build
+ - when:
+ condition:
+ equal: [mcp, << parameters.suite >>]
+ steps:
+ - run:
+ name: Install MCP SDK1 peer
+ command: |
+ uv venv --python 3.12 .venv-mcp-peer
+ uv pip install --python .venv-mcp-peer 'mcp==1.28.1' 'langchain-mcp-adapters==0.2.1'
+ echo "export MCP_TEST_PEER_PYTHON=$PWD/.venv-mcp-peer/bin/python" >> "$BASH_ENV"
- start_postgres:
image: postgres:16@sha256:e17e86066e5ef83e0952a9347f5c792b7ece00972e2aa787a6986f471b3dd3d5
server_args: "-c shared_preload_libraries=pg_stat_statements -c pg_stat_statements.track=all -c pg_stat_statements.max=20000"
@@ -1508,7 +1518,7 @@ jobs:
mkdir -p test-results
env -u OPENAI_API_KEY -u ANTHROPIC_API_KEY \
timeout --signal=TERM 20m uv run --no-sync pytest \
- tests/mcp_tests tests/unit/experimental_mcp_client tests/unit/proxy/_experimental/mcp_server \
+ tests/unit/experimental_mcp_client tests/unit/proxy/_experimental/mcp_server \
tests/unit/responses/mcp --tb=short -vv --maxfail=10 -n 2 --dist=loadscope --reruns 0 \
--reruns-delay 1 --timeout=120 --rerun-except "from pytest-timeout" --durations=20 \
--cov=./litellm --cov=./enterprise/litellm_enterprise --cov-report=xml:coverage.xml \
@@ -1732,19 +1742,6 @@ workflows:
shards: 2
requires: [integration-database-replica]
filters: *integration_default_run
- - postgres_suite:
- name: proxy-security
- test_path: tests/proxy_security_tests
- seed: true
- timeout_minutes: 15
- filters: *integration_default_run
- - postgres_suite:
- name: schema-migration
- test_path: tests/proxy_migration_tests
- seed: false
- timeout_minutes: 20
- workers: 2
- filters: *integration_default_run
- postgres_suite:
name: roi-database
test_path: tests/integration/database/test_roi_observed.py
diff --git a/.circleci/scripts/run_integration.sh b/.circleci/scripts/run_integration.sh
index 7c6bee57ba4..0210c2dc6f7 100644
--- a/.circleci/scripts/run_integration.sh
+++ b/.circleci/scripts/run_integration.sh
@@ -254,6 +254,7 @@ env -i PATH="$PATH" HOME="$HOME" PYTHONPATH="$PYTHONPATH" \
INTEGRATION_PROXY_DATABASE_URL="$INTEGRATION_PROXY_DATABASE_URL" \
INTEGRATION_PROXY_READ_REPLICA_URL="$INTEGRATION_PROXY_READ_REPLICA_URL" \
INTEGRATION_ROUTING="$INTEGRATION_ROUTING" \
+ MCP_TEST_PEER_PYTHON="${MCP_TEST_PEER_PYTHON:-}" \
.venv/bin/python tests/integration/run.py "$suite" --results "$results" \
"${shard_arguments[@]}"
diff --git a/.github/workflows/image-scan.yml b/.github/workflows/image-scan.yml
index e2a3783af3f..93eb6c1b325 100644
--- a/.github/workflows/image-scan.yml
+++ b/.github/workflows/image-scan.yml
@@ -27,7 +27,7 @@ on:
- backend/routes/allowlist.py
- pyproject.toml
- litellm-proxy-extras/**
- - tests/proxy_migration_tests/**
+ - tests/integration/database/image/**
- uv.lock
- ui/litellm-dashboard/package-lock.json
- ui/Dockerfile
@@ -92,7 +92,7 @@ jobs:
LITELLM_ADMIN_MCP_SCHEMA_IMAGE: litellm-admin-mcp-schema:${{ github.sha }}
run: |
python -m pip install "pytest==9.0.3"
- python -m pytest tests/proxy_migration_tests/test_offline_image_migration.py tests/proxy_migration_tests/test_image_bedrock_realtime_extra.py tests/proxy_migration_tests/test_image_admin_mcp.py -v
+ python -m pytest --noconftest tests/integration/database/image/test_offline_image_migration.py tests/integration/database/image/test_image_bedrock_realtime_extra.py tests/integration/database/image/test_image_admin_mcp.py -v
# Scans the whole shipped artifact: OS/apk plus every language package
# baked into the image, including ones no lockfile declares (e.g. prisma's
@@ -145,7 +145,7 @@ jobs:
LITELLM_ADMIN_MCP_SCHEMA_IMAGE: litellm-admin-mcp-schema:${{ github.sha }}
run: |
python -m pip install "pytest==9.0.3"
- python -m pytest tests/proxy_migration_tests/test_offline_image_migration.py tests/proxy_migration_tests/test_image_bedrock_realtime_extra.py tests/proxy_migration_tests/test_image_admin_mcp.py -v
+ python -m pytest --noconftest tests/integration/database/image/test_offline_image_migration.py tests/integration/database/image/test_image_bedrock_realtime_extra.py tests/integration/database/image/test_image_admin_mcp.py -v
migrations-image:
@@ -177,7 +177,7 @@ jobs:
LITELLM_MIGRATION_SCRIPT: /app/run.py
run: |
python -m pip install "pytest==9.0.3"
- python -m pytest tests/proxy_migration_tests/test_offline_image_migration.py -v
+ python -m pytest --noconftest tests/integration/database/image/test_offline_image_migration.py -v
gateway-image:
name: gateway-image
@@ -208,7 +208,7 @@ jobs:
LITELLM_IMAGE_COMPONENT: gateway
run: |
python -m pip install "pytest==9.0.3"
- python -m pytest tests/proxy_migration_tests/test_component_image_serves_offline.py tests/proxy_migration_tests/test_image_bedrock_realtime_extra.py tests/proxy_migration_tests/test_image_admin_mcp.py -v
+ python -m pytest --noconftest tests/integration/database/image/test_component_image_serves_offline.py tests/integration/database/image/test_image_bedrock_realtime_extra.py tests/integration/database/image/test_image_admin_mcp.py -v
ui-image:
name: ui-image
@@ -237,7 +237,7 @@ jobs:
LITELLM_IMAGE: litellm-ui-scan:${{ github.sha }}
run: |
python -m pip install "pytest==9.0.3"
- python -m pytest tests/proxy_migration_tests/test_ui_image_serves_offline.py -v
+ python -m pytest --noconftest tests/integration/database/image/test_ui_image_serves_offline.py -v
backend-image:
name: backend-image
@@ -272,4 +272,4 @@ jobs:
LITELLM_IMAGE_COMPONENT: backend
run: |
python -m pip install "pytest==9.0.3"
- python -m pytest tests/proxy_migration_tests/test_component_image_serves_offline.py tests/proxy_migration_tests/test_image_admin_mcp.py -v
+ python -m pytest --noconftest tests/integration/database/image/test_component_image_serves_offline.py tests/integration/database/image/test_image_admin_mcp.py -v
diff --git a/litellm-rust/crates/gateway-mcp/AGENTS.md b/litellm-rust/crates/gateway-mcp/AGENTS.md
index 6f2171769b4..aa608f1e720 100644
--- a/litellm-rust/crates/gateway-mcp/AGENTS.md
+++ b/litellm-rust/crates/gateway-mcp/AGENTS.md
@@ -24,7 +24,7 @@ From the repository root, this loopback-only example runs the existing Python MC
```sh
cargo run --manifest-path litellm-rust/Cargo.toml -p litellm-gateway-mcp --example stdio_proxy -- \
- .venv/bin/python -c 'import runpy; runpy.run_path("tests/mcp_tests/mcp_e2e_upstream_server.py")["mcp"].run(transport="stdio")'
+ .venv/bin/python -c 'import runpy; runpy.run_path("tests/integration/_support/mcp_e2e_upstream_server.py")["mcp"].run(transport="stdio")'
```
```sh
diff --git a/litellm-rust/crates/gateway/README.md b/litellm-rust/crates/gateway/README.md
index c6c169e6115..125c2b07448 100644
--- a/litellm-rust/crates/gateway/README.md
+++ b/litellm-rust/crates/gateway/README.md
@@ -7,7 +7,7 @@ The binary reads YAML from `LITELLM_CONFIG` and mounts configured MCP servers al
From the repository root, start the Python fixture in one terminal:
```sh
-MCP_HOST=127.0.0.1 MCP_PORT=8090 .venv/bin/python tests/mcp_tests/mcp_e2e_upstream_server.py
+MCP_HOST=127.0.0.1 MCP_PORT=8090 .venv/bin/python tests/integration/_support/mcp_e2e_upstream_server.py
```
Start the gateway in another terminal with the example configuration:
diff --git a/tests/e2e/coverage_registry/mcp.yaml b/tests/e2e/coverage_registry/mcp.yaml
index 1cdeac7b77f..9e25d78b6cd 100644
--- a/tests/e2e/coverage_registry/mcp.yaml
+++ b/tests/e2e/coverage_registry/mcp.yaml
@@ -135,3 +135,11 @@
assertions: [toolset_scoped]
source: "user_api_key_auth_mcp.py:2137"
rationale: "A key granted a toolset lists exactly the toolset's tools: the rest of the server's catalog stays hidden and every stored name resolves"
+- id: mcp.list_tools.api_key.semantic_filtered
+ module: mcp
+ tier: P1
+ operation: list_tools
+ auth_family: api_key
+ assertions: [semantic_filtered]
+ source: "litellm/proxy/hooks/mcp_semantic_filter/hook.py"
+ rationale: The semantic tool filter must cut a large MCP catalog to top_k and keep the tool the prompt needs
diff --git a/tests/e2e/mcp/test_mcp_semantic_tool_filter_e2e.py b/tests/e2e/mcp/test_mcp_semantic_tool_filter_e2e.py
new file mode 100644
index 00000000000..6e564f4625a
--- /dev/null
+++ b/tests/e2e/mcp/test_mcp_semantic_tool_filter_e2e.py
@@ -0,0 +1,127 @@
+"""Live e2e: the MCP semantic tool filter narrows a Datadog catalog to the tools the prompt needs.
+
+An admin registers the real Datadog remote MCP server with its whole core toolset, adds an
+embedding deployment, and turns on `litellm_settings.mcp_semantic_tool_filter` through
+/config/update. A chat completion that attaches the server and asks to search logs must report,
+in the x-litellm-semantic-filter headers, that the catalog was cut to at most top_k tools, all
+of them tools the key lists. Requires DD_API_KEY + DD_APP_KEY and the proxy's
+OPENAI_API_KEY for the embedding deployment.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Final
+
+import pytest
+from datadog_mcp import register_datadog_mcp
+from e2e_config import CHEAP_OPENAI_MODEL, POLL_INTERVAL, POLL_TIMEOUT, unique_marker
+from e2e_http import StreamingResponse, unwrap
+from e2e_metadata import Domain, Route, Subject, meta
+from lifecycle import ResourceManager
+from mcp_client import McpClient
+from models import ChatBody, ChatMessage, LiteLLMParamsBody, McpChatTool
+from pydantic import BaseModel
+
+pytestmark = [pytest.mark.e2e, pytest.mark.quiet_stack]
+
+TOP_K: Final = 3
+
+
+class SemanticToolFilterSettings(BaseModel):
+ enabled: bool
+ embedding_model: str | None = None
+ top_k: int | None = None
+ similarity_threshold: float | None = None
+
+
+class SemanticFilterLitellmSettings(BaseModel):
+ mcp_semantic_tool_filter: SemanticToolFilterSettings
+
+
+class SemanticFilterConfigUpdateBody(BaseModel):
+ litellm_settings: SemanticFilterLitellmSettings
+
+
+class ConfigUpdateResponse(BaseModel):
+ message: str
+
+
+def _write_filter(client: McpClient, settings: SemanticToolFilterSettings) -> None:
+ response: Final = unwrap(
+ client.proxy.transport.post(
+ "/config/update",
+ headers=client.proxy.transport.master,
+ json=SemanticFilterConfigUpdateBody(
+ litellm_settings=SemanticFilterLitellmSettings(mcp_semantic_tool_filter=settings)
+ ),
+ response_type=ConfigUpdateResponse,
+ )
+ )
+ assert "success" in response.message.lower(), f"/config/update reported {response.message!r}"
+
+
+def _filtered_chat(client: McpClient, key: str, alias: str) -> StreamingResponse:
+ deadline: Final = time.monotonic() + POLL_TIMEOUT
+ body: Final = ChatBody(
+ model=CHEAP_OPENAI_MODEL,
+ messages=[ChatMessage(role="user", content=f"Search the Datadog logs for the marker {unique_marker()}")],
+ tools=[McpChatTool(server_url=f"litellm_proxy/mcp/{alias}", server_label=alias, require_approval="never")],
+ )
+ while True:
+ response: StreamingResponse = client.proxy.chat_stream(key, body) # rebind-ok: poll until hot reload lands
+ assert response.ok, (
+ f"chat completion with the Datadog MCP server failed: {response.status_code} {response.body}"
+ )
+ if "x-litellm-semantic-filter" in response.headers or time.monotonic() > deadline:
+ return response
+ time.sleep(POLL_INTERVAL)
+
+
+class TestMcpSemanticToolFilter:
+ @pytest.mark.covers("mcp.list_tools.api_key.semantic_filtered")
+ @meta(Subject(domain=Domain.MCP, route=Route.MCP))
+ def test_filter_keeps_the_tool_the_prompt_needs(self, client: McpClient, resources: ResourceManager) -> None:
+ server_id: Final = register_datadog_mcp(client, resources, allowed_tools=None)
+ row: Final = client.await_registered(server_id)
+ alias: Final = row.server_name
+ assert alias, f"the registered Datadog server has no alias to attach it by: {row}"
+
+ embedding_model: Final = f"e2e-semantic-filter-embedding-{unique_marker()}"
+ model_id: Final = client.proxy.create_model(
+ embedding_model,
+ LiteLLMParamsBody(model="openai/text-embedding-3-small", api_key="os.environ/OPENAI_API_KEY"),
+ provider_live=True,
+ )
+ resources.defer(lambda: client.proxy.delete_model(model_id))
+
+ key: Final = client.generate_key(user_id=f"e2e-mcp-semantic-{unique_marker()}", mcp_servers=[server_id])
+ resources.defer(lambda: client.proxy.delete_key(key))
+ catalog: Final = unwrap(client.list_tools(key)).tool_names_for_server(server_id)
+ assert len(catalog) > TOP_K, (
+ f"the Datadog core toolset must serve more than {TOP_K} tools, got {sorted(catalog)}"
+ )
+
+ resources.defer(lambda: _write_filter(client, SemanticToolFilterSettings(enabled=False)))
+ _write_filter(
+ client,
+ SemanticToolFilterSettings(
+ enabled=True, embedding_model=embedding_model, top_k=TOP_K, similarity_threshold=0.0
+ ),
+ )
+
+ response: Final = _filtered_chat(client, key, alias)
+ stats: Final = response.headers.get("x-litellm-semantic-filter")
+ assert stats is not None, f"no x-litellm-semantic-filter header within {POLL_TIMEOUT}s: {response.headers}"
+ before, _, after = stats.partition("->")
+ assert int(before) == len(catalog), f"the filter saw {before} MCP tools, the key lists {len(catalog)}"
+ assert 0 < int(after) <= TOP_K, f"the filter kept {after} tools, expected between 1 and {TOP_K}"
+ kept: Final = frozenset(
+ name.removeprefix(f"{alias}-")
+ for name in response.headers.get("x-litellm-semantic-filter-tools", "").split(",")
+ if name
+ )
+ listed: Final = frozenset(name.removeprefix(f"{alias}-") for name in catalog)
+ assert kept, f"the filter reported keeping {after} tools but named none: {response.headers}"
+ assert len(kept) <= int(after), f"the filter named {sorted(kept)} but reported keeping {after}"
+ assert kept <= listed, f"the filter kept {sorted(kept - listed)}, which the key never listed"
diff --git a/tests/integration/_support/mcp.py b/tests/integration/_support/mcp.py
index c51ecfc96b1..a4032bcb5f3 100644
--- a/tests/integration/_support/mcp.py
+++ b/tests/integration/_support/mcp.py
@@ -21,7 +21,7 @@ from mcp.client.streamable_http import streamable_http_client
from mcp.server.mcpserver import Context, MCPServer
from mcp.server.transport_security import TransportSecuritySettings
from mcp.types import SamplingMessage, TextContent
-from mcp_tests.mcp_e2e_upstream_server import add, multiply
+from integration._support.mcp_e2e_upstream_server import add, multiply
from pydantic import BaseModel, JsonValue
from sse_starlette.sse import AppStatus
from starlette.requests import Request as StarletteRequest
diff --git a/tests/mcp_tests/mcp_e2e_upstream_server.py b/tests/integration/_support/mcp_e2e_upstream_server.py
similarity index 100%
rename from tests/mcp_tests/mcp_e2e_upstream_server.py
rename to tests/integration/_support/mcp_e2e_upstream_server.py
diff --git a/tests/proxy_migration_tests/test_component_image_serves_offline.py b/tests/integration/database/image/test_component_image_serves_offline.py
similarity index 100%
rename from tests/proxy_migration_tests/test_component_image_serves_offline.py
rename to tests/integration/database/image/test_component_image_serves_offline.py
diff --git a/tests/proxy_migration_tests/test_image_admin_mcp.py b/tests/integration/database/image/test_image_admin_mcp.py
similarity index 100%
rename from tests/proxy_migration_tests/test_image_admin_mcp.py
rename to tests/integration/database/image/test_image_admin_mcp.py
diff --git a/tests/proxy_migration_tests/test_image_bedrock_realtime_extra.py b/tests/integration/database/image/test_image_bedrock_realtime_extra.py
similarity index 100%
rename from tests/proxy_migration_tests/test_image_bedrock_realtime_extra.py
rename to tests/integration/database/image/test_image_bedrock_realtime_extra.py
diff --git a/tests/proxy_migration_tests/test_offline_image_migration.py b/tests/integration/database/image/test_offline_image_migration.py
similarity index 100%
rename from tests/proxy_migration_tests/test_offline_image_migration.py
rename to tests/integration/database/image/test_offline_image_migration.py
diff --git a/tests/proxy_migration_tests/test_ui_image_serves_offline.py b/tests/integration/database/image/test_ui_image_serves_offline.py
similarity index 100%
rename from tests/proxy_migration_tests/test_ui_image_serves_offline.py
rename to tests/integration/database/image/test_ui_image_serves_offline.py
diff --git a/tests/proxy_migration_tests/conftest.py b/tests/integration/database/migrations/conftest.py
similarity index 67%
rename from tests/proxy_migration_tests/conftest.py
rename to tests/integration/database/migrations/conftest.py
index de5ba62b1be..880f5aa2b9e 100644
--- a/tests/proxy_migration_tests/conftest.py
+++ b/tests/integration/database/migrations/conftest.py
@@ -1,5 +1,3 @@
-from __future__ import annotations
-
import os
from collections.abc import Iterator
from typing import Final
@@ -7,14 +5,11 @@ from urllib.parse import urlsplit
import pytest
+from tests.integration._support.database import read_rows, scratch_database
[email protected](scope="session", autouse=True)
-def worker_database() -> Iterator[None]:
- if not os.environ.get("PYTEST_XDIST_WORKER") or "DATABASE_URL" not in os.environ:
- yield
- return
- from tests.integration._support.database import read_rows, scratch_database
[email protected](autouse=True)
+def unseeded_database() -> Iterator[None]:
admin_url: Final = os.environ["DATABASE_URL"]
with scratch_database() as database, pytest.MonkeyPatch.context() as environment:
environment.setenv("DATABASE_URL", database)
diff --git a/tests/proxy_migration_tests/test_autorouter_baseline_state.py b/tests/integration/database/migrations/test_autorouter_baseline_state.py
similarity index 97%
rename from tests/proxy_migration_tests/test_autorouter_baseline_state.py
rename to tests/integration/database/migrations/test_autorouter_baseline_state.py
index d9021414bc4..629089eda02 100644
--- a/tests/proxy_migration_tests/test_autorouter_baseline_state.py
+++ b/tests/integration/database/migrations/test_autorouter_baseline_state.py
@@ -19,7 +19,7 @@ from litellm.proxy.db.baseline_accounting import BaselineAccountingStore
from litellm.proxy.db.routing_prisma_wrapper import RoutingPrismaWrapper
from litellm.proxy.utils import PrismaClient, ProxyLogging
-_MIGRATION: Final = Path(__file__).parents[2] / (
+_MIGRATION: Final = Path(__file__).parents[4] / (
"litellm-proxy-extras/litellm_proxy_extras/migrations/20260915010000_add_autorouter_baseline_state/migration.sql"
)
@@ -90,6 +90,7 @@ async def test_locked_projection_is_bounded_and_cancellation_propagates(
url, connection = database
async with _client(monkeypatch, url) as client:
store: Final = BaselineAccountingStore.for_client(client)
+ assert await store.project("scope") == "unchanged"
with connection.transaction():
connection.execute('LOCK TABLE "LiteLLM_AutoRouterBaselineComparison" IN ACCESS EXCLUSIVE MODE')
started: Final = time.monotonic()
diff --git a/tests/proxy_migration_tests/test_db_schema_migration.py b/tests/integration/database/migrations/test_db_schema_migration.py
similarity index 100%
rename from tests/proxy_migration_tests/test_db_schema_migration.py
rename to tests/integration/database/migrations/test_db_schema_migration.py
diff --git a/tests/proxy_migration_tests/test_invalid_index_repair.py b/tests/integration/database/migrations/test_invalid_index_repair.py
similarity index 98%
rename from tests/proxy_migration_tests/test_invalid_index_repair.py
rename to tests/integration/database/migrations/test_invalid_index_repair.py
index 0c971b5d073..df934a174f6 100644
--- a/tests/proxy_migration_tests/test_invalid_index_repair.py
+++ b/tests/integration/database/migrations/test_invalid_index_repair.py
@@ -297,11 +297,6 @@ def test_repair_defaults_to_the_public_schema(monkeypatch: pytest.MonkeyPatch) -
conn.execute(f'DROP TABLE public."{table}"')
-def test_repair_survives_an_unreachable_database(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.delenv("DIRECT_URL", raising=False)
- monkeypatch.setenv("DATABASE_URL", "postgresql://u:[email protected]:9/x?schema=whatever")
-
- assert ProxyExtrasDBManager.repair_invalid_indexes() is False
@requires_db
diff --git a/tests/proxy_migration_tests/test_prisma_toolchain.py b/tests/integration/database/migrations/test_prisma_toolchain.py
similarity index 64%
rename from tests/proxy_migration_tests/test_prisma_toolchain.py
rename to tests/integration/database/migrations/test_prisma_toolchain.py
index ebe2390db16..fecb1fece91 100644
--- a/tests/proxy_migration_tests/test_prisma_toolchain.py
+++ b/tests/integration/database/migrations/test_prisma_toolchain.py
@@ -14,39 +14,26 @@ replays every migration overran the per-command budget on slow machines and
the proxy gave up after four identical timeouts.
"""
-import ast
import json
import logging
import os
import signal
import sys
import time
-from collections.abc import Callable
from pathlib import Path
import pytest
from litellm_proxy_extras.prisma_toolchain import (
- DEFAULT_PRISMA_COMMAND_TIMEOUT,
- DEFAULT_PRISMA_MIGRATE_DEPLOY_TIMEOUT,
PRISMA_BOOTSTRAP_TIMEOUT_ENV_VAR,
PRISMA_COMMAND_TIMEOUT_ENV_VAR,
PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR,
ensure_prisma_toolchain,
- heal_incomplete_nodeenv_cache,
- node_binary_path,
- prisma_bootstrap_timeout,
- prisma_cli_available,
- prisma_command_timeout,
- prisma_migrate_deploy_timeout,
- resolve_prisma_argv,
run_prisma,
)
from litellm_proxy_extras.utils import ProxyExtrasDBManager
from tests._process_helpers import process_is_gone
-REPO_ROOT = Path(__file__).resolve().parents[2]
-PROXY_EXTRAS = REPO_ROOT / "litellm-proxy-extras" / "litellm_proxy_extras"
FAKE_PRISMA = """#!{python}
import json
@@ -125,61 +112,16 @@ def _make_incomplete_cache(cache_dir: Path) -> None:
(cache_dir / "bin").mkdir()
-def _make_complete_cache(cache_dir: Path) -> None:
- node = node_binary_path(cache_dir)
- node.parent.mkdir(parents=True)
- node.write_text("")
-def test_interrupted_toolchain_install_is_removed(
- toolchain_env: tuple[Path, Path],
-) -> None:
- cache_dir, _ = toolchain_env
- _make_incomplete_cache(cache_dir)
-
- assert heal_incomplete_nodeenv_cache() is True
- assert not cache_dir.exists()
-
-def test_installed_toolchain_is_left_alone(toolchain_env: tuple[Path, Path]) -> None:
- cache_dir, _ = toolchain_env
- _make_complete_cache(cache_dir)
- assert heal_incomplete_nodeenv_cache() is False
- assert node_binary_path(cache_dir).exists()
-def test_absent_toolchain_is_not_an_error(toolchain_env: tuple[Path, Path]) -> None:
- cache_dir, _ = toolchain_env
- assert heal_incomplete_nodeenv_cache() is False
- assert not cache_dir.exists()
-_CAN_DENY_ACCESS = os.name != "nt" and hasattr(os, "geteuid") and os.geteuid() != 0
-
-
- not _CAN_DENY_ACCESS, reason="root and Windows do not honour a 0o000 directory"
-)
-def test_unreadable_cache_dir_is_not_an_error(
- toolchain_env: tuple[Path, Path],
-) -> None:
- """A cache dir this process cannot stat means nothing to heal, not a crash.
-
- Images bake the cache under the build user's home, and a container started
- under any other uid cannot search that directory. `Path.is_dir()` only
- swallows ENOENT-shaped errnos, so it raises `PermissionError` there and
- kills the migration before Prisma is ever invoked.
- """
- cache_dir, _ = toolchain_env
- _make_incomplete_cache(cache_dir)
- cache_dir.parent.chmod(0o000)
- try:
- assert heal_incomplete_nodeenv_cache() is False
- finally:
- cache_dir.parent.chmod(0o700)
def test_bootstrap_clears_the_cache_before_invoking_prisma(
@@ -325,75 +267,12 @@ def test_db_push_timeout_hint_names_the_per_command_budget(
]
- ("command_timeout", "deploy_timeout", "expected"),
- [
- ("900", None, 900.0),
- ("12", None, DEFAULT_PRISMA_MIGRATE_DEPLOY_TIMEOUT),
- ("900", "1200", 1200.0),
- ("900", "300", 300.0),
- ],
- ids=["raised_command_budget_carries_over", "lowered_command_budget_does_not", "override_wins_upward", "override_wins_downward"],
-)
-def test_migrate_deploy_budget_keeps_a_raised_command_budget(
- command_timeout: str, deploy_timeout: str | None, expected: float, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """Deployments that raised the per-command budget to survive a long deploy keep that budget for deploy."""
- monkeypatch.setenv(PRISMA_COMMAND_TIMEOUT_ENV_VAR, command_timeout)
- if deploy_timeout is None:
- monkeypatch.delenv(PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, raising=False)
- else:
- monkeypatch.setenv(PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, deploy_timeout)
-
- assert prisma_migrate_deploy_timeout() == expected
-
-
- "raw",
- ["", "0", "-5", "not-a-number", "nan", "inf", "-inf", "1e400"],
-)
- ("env_var", "read_timeout", "default"),
- [
- (PRISMA_COMMAND_TIMEOUT_ENV_VAR, prisma_command_timeout, DEFAULT_PRISMA_COMMAND_TIMEOUT),
- (PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, prisma_migrate_deploy_timeout, DEFAULT_PRISMA_MIGRATE_DEPLOY_TIMEOUT),
- ],
- ids=["command", "migrate_deploy"],
-)
-def test_unusable_timeout_override_falls_back_to_the_default(
- raw: str, env_var: str, read_timeout: Callable[[], float], default: float, monkeypatch: pytest.MonkeyPatch
-) -> None:
- """A non-finite override would silently disable the timeout it configures."""
- monkeypatch.setenv(env_var, raw)
- assert read_timeout() == default
-def test_timeout_overrides_are_independent(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setenv(PRISMA_COMMAND_TIMEOUT_ENV_VAR, "12")
- monkeypatch.setenv(PRISMA_BOOTSTRAP_TIMEOUT_ENV_VAR, "900")
- monkeypatch.setenv(PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, "1200")
- assert prisma_command_timeout() == 12
- assert prisma_bootstrap_timeout() == 900
- assert prisma_migrate_deploy_timeout() == 1200
[email protected]("module", ["utils.py", "replica_identity.py"])
-def test_every_prisma_command_timeout_is_overridable(module: str) -> None:
- tree = ast.parse((PROXY_EXTRAS / module).read_text())
- literals = [
- node.lineno
- for node in ast.walk(tree)
- if isinstance(node, ast.keyword)
- and node.arg == "timeout"
- and isinstance(node.value, ast.Constant)
- ]
-
- assert literals == [], (
- f"{module} still hardcodes a Prisma timeout at lines {literals}; "
- "route it through prisma_command_timeout() so it can be raised without a release"
- )
FAKE_PRISMA_MODULE_MAIN = """import json
@@ -449,40 +328,9 @@ def test_run_prisma_prefers_the_console_script_on_path(
assert "module_argv" not in result.stdout
-def test_resolve_prisma_argv_leaves_an_explicit_cli_path_alone(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setenv("PATH", str(_empty_bin(tmp_path)))
- explicit = ("/app/.cache/prisma-python/prisma", "migrate", "deploy")
-
- assert resolve_prisma_argv(explicit) == explicit
-
-def test_prisma_cli_is_unavailable_with_neither_script_nor_package(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setenv("PATH", str(_empty_bin(tmp_path)))
- monkeypatch.delitem(sys.modules, "prisma", raising=False)
- monkeypatch.setattr(sys, "path", [])
- assert prisma_cli_available() is False
-def test_prisma_cli_is_available_through_the_package_alone(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setenv("PATH", str(_empty_bin(tmp_path)))
- monkeypatch.delitem(sys.modules, "prisma", raising=False)
- monkeypatch.setattr(sys, "path", [str(_write_fake_prisma_module(tmp_path))])
- assert prisma_cli_available() is True
-
-
-def test_prisma_cli_is_available_through_the_console_script_alone(
- tmp_path: Path, monkeypatch: pytest.MonkeyPatch
-) -> None:
- monkeypatch.setenv("PATH", str(_write_fake_prisma(tmp_path)))
- monkeypatch.delitem(sys.modules, "prisma", raising=False)
- monkeypatch.setattr(sys, "path", [])
- assert prisma_cli_available() is True
diff --git a/tests/proxy_migration_tests/test_replica_identity_full.py b/tests/integration/database/migrations/test_replica_identity_full.py
similarity index 74%
rename from tests/proxy_migration_tests/test_replica_identity_full.py
rename to tests/integration/database/migrations/test_replica_identity_full.py
index 6a88e6994e9..e39dcedc6b4 100644
--- a/tests/proxy_migration_tests/test_replica_identity_full.py
+++ b/tests/integration/database/migrations/test_replica_identity_full.py
@@ -11,7 +11,6 @@ import pytest
from litellm_proxy_extras.replica_identity import (
REPLICA_IDENTITY_FULL_ENV_VAR,
- apply_replica_identity_full,
)
from litellm_proxy_extras.utils import ProxyExtrasDBManager
@@ -116,44 +115,7 @@ def test_reports_failure_without_raising(scratch_schema, monkeypatch):
assert _replica_identities(scratch_schema)["LiteLLM_ScratchTable"] == "d"
-def test_reports_an_unrunnable_prisma_cli_without_raising(tmp_path):
- """A deployment without the Prisma CLI on PATH must still finish its
- migration run instead of dying on the optional replication step."""
- assert (
- apply_replica_identity_full(
- schema_path=str(tmp_path / "schema.prisma"),
- prisma_command=str(tmp_path / "no-such-prisma"),
- prisma_env={},
- )
- is False
- )
-
-
-def test_setup_database_applies_after_a_successful_migration_run(monkeypatch):
- applied = []
- monkeypatch.setattr(
- ProxyExtrasDBManager, "_run_migrations", staticmethod(lambda **kwargs: True)
- )
- monkeypatch.setattr(
- ProxyExtrasDBManager,
- "apply_replica_identity_full_if_requested",
- staticmethod(lambda: applied.append(True)),
- )
- assert ProxyExtrasDBManager.setup_database(use_migrate=True) is True
- assert applied == [True]
-def test_setup_database_skips_replica_identity_when_migrations_fail(monkeypatch):
- applied = []
- monkeypatch.setattr(
- ProxyExtrasDBManager, "_run_migrations", staticmethod(lambda **kwargs: False)
- )
- monkeypatch.setattr(
- ProxyExtrasDBManager,
- "apply_replica_identity_full_if_requested",
- staticmethod(lambda: applied.append(True)),
- )
- assert ProxyExtrasDBManager.setup_database(use_migrate=True) is False
- assert applied == []
diff --git a/tests/proxy_migration_tests/test_request_log_indexes.py b/tests/integration/database/migrations/test_request_log_indexes.py
similarity index 99%
rename from tests/proxy_migration_tests/test_request_log_indexes.py
rename to tests/integration/database/migrations/test_request_log_indexes.py
index b351fc054dc..754cffce6a1 100644
--- a/tests/proxy_migration_tests/test_request_log_indexes.py
+++ b/tests/integration/database/migrations/test_request_log_indexes.py
@@ -36,7 +36,7 @@ requires_db: Final = pytest.mark.skipif(
reason="requires a postgres database (DATABASE_URL)",
)
-REPO: Final = Path(__file__).resolve().parents[2]
+REPO: Final = Path(__file__).resolve().parents[4]
PACKAGE: Final = REPO / "litellm-proxy-extras" / "litellm_proxy_extras"
PARTITION_SCRIPT: Final = REPO / "db_scripts" / "partition_spend_logs.sql"
API_KEY_INDEX_MIGRATION: Final = "20260823000000_add_spend_logs_api_key_starttime_index"
diff --git a/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml b/tests/integration/mcp/_config_mcp_e2e.yaml
similarity index 93%
rename from tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml
rename to tests/integration/mcp/_config_mcp_e2e.yaml
index bdf6ad4e15a..43a376b104e 100644
--- a/tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml
+++ b/tests/integration/mcp/_config_mcp_e2e.yaml
@@ -17,7 +17,7 @@ mcp_servers:
transport: stdio
command: python3
args:
- - tests/mcp_tests/mcp_server.py
+ - tests/integration/mcp/_math_server.py
allow_all_keys: true # Needed for master_key auth when DB/object_permission not used
math_streamable_http:
transport: http
diff --git a/tests/mcp_tests/mcp_server.py b/tests/integration/mcp/_math_server.py
similarity index 100%
rename from tests/mcp_tests/mcp_server.py
rename to tests/integration/mcp/_math_server.py
diff --git a/tests/integration/mcp/test_mcp_credentials.py b/tests/integration/mcp/test_mcp_credentials.py
index 208b33b3580..ee36581acdd 100644
--- a/tests/integration/mcp/test_mcp_credentials.py
+++ b/tests/integration/mcp/test_mcp_credentials.py
@@ -659,7 +659,10 @@ def test_oauth_passthrough_probe_uses_server_token_without_admission_key(
assert probes, "expected an upstream initialize authentication probe"
assert all(_header(probe, b"authorization") == f"Bearer {upstream_token}".encode() for probe in probes)
assert len(tool_calls(observed)) == 1
- assert all(_header(request, b"authorization") == f"Bearer {upstream_token}".encode() for request in observed)
+ foreign: Final = tuple(
+ request for request in observed if _header(request, b"authorization") != f"Bearer {upstream_token}".encode()
+ )
+ assert foreign == (), foreign
header_sets: Final = tuple(
TypeAdapter(dict[bytes, bytes]).validate_python(request["headers"]) for request in observed
)
diff --git a/tests/mcp_tests/test_proxy_mcp_e2e.py b/tests/integration/mcp/test_proxy_mcp_e2e.py
similarity index 96%
rename from tests/mcp_tests/test_proxy_mcp_e2e.py
rename to tests/integration/mcp/test_proxy_mcp_e2e.py
index 19e02b8efcc..4cfac6ed784 100644
--- a/tests/mcp_tests/test_proxy_mcp_e2e.py
+++ b/tests/integration/mcp/test_proxy_mcp_e2e.py
@@ -1,4 +1,5 @@
import asyncio
+import importlib
import json
import os
import queue
@@ -27,7 +28,9 @@ from mcp.shared._httpx_utils import create_mcp_http_client
from mcp.types import CallToolResult
from starlette.requests import Request
+import litellm
from litellm.integrations.custom_logger import CustomLogger
+from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
from litellm.proxy._experimental.mcp_server.tool_search import handle_mcp_proxy_tool
from litellm.proxy._types import LiteLLM_ObjectPermissionTable, ProxyException, UserAPIKeyAuth
from litellm.proxy.proxy_server import (
@@ -41,37 +44,37 @@ from tests._master_key import MASTER_KEY
from tests.integration._support.wire import Reply, Wire, wire_server
from tests.integration._support.wire import Request as WireRequest
-CONFIG_TEMPLATE_PATH = Path("tests/mcp_tests/test_configs/test_config_mcp_e2e.yaml")
-MCP_SERVER_SCRIPT = Path("tests/mcp_tests/mcp_server.py")
-MCP_PEER_PYTHON = os.environ.get("MCP_TEST_PEER_PYTHON", sys.executable)
-PROJECT_ROOT = Path(__file__).resolve().parents[2]
+CONFIG_TEMPLATE_PATH = Path("tests/integration/mcp/_config_mcp_e2e.yaml")
+MCP_SERVER_SCRIPT = Path("tests/integration/mcp/_math_server.py")
+MCP_PEER_PYTHON = os.environ.get("MCP_TEST_PEER_PYTHON") or sys.executable
+PROJECT_ROOT = Path(__file__).resolve().parents[3]
PROXY_START_TIMEOUT = 30
+pytestmark: Final = pytest.mark.xdist_group("proxy_mcp_e2e_in_process")
PROXY_AUTHORIZATION_HEADER = f"Bearer {MASTER_KEY}"
-async def test_cold_concurrent_schema_validation_accepts_valid_arguments() -> None:
- from litellm.proxy._experimental.mcp_server.tool_search import _tool_argument_validation_error
[email protected](autouse=True)
+def setup_and_teardown() -> typing.Iterator[None]:
+ importlib.reload(litellm)
+ loop: Final = asyncio.get_event_loop_policy().new_event_loop()
+ asyncio.set_event_loop(loop)
+ yield
+ asyncio.run(GLOBAL_LOGGING_WORKER.clear_queue())
+ loop.close()
+ asyncio.set_event_loop(None)
- schema: Final = {
- "type": "object",
- "$defs": {"amount": {"type": "number", "multipleOf": 0.25}},
- "properties": {"amount": {"$ref": "#/$defs/amount"}},
- }
- original_affinity: Final = os.sched_getaffinity(0) if sys.platform == "linux" else None
+
[email protected](autouse=True)
+async def drain_logging_worker() -> typing.AsyncIterator[None]:
+ yield
try:
- if original_affinity is not None:
- os.sched_setaffinity(0, {min(original_affinity)})
- for _ in range(2):
- results: Final = await asyncio.gather(
- *(_tool_argument_validation_error(schema, {"amount": 0.75}) for _ in range(8))
- )
- assert results == [None] * 8, "Cold and warm workers must accept valid concurrent tool arguments"
- finally:
- if original_affinity is not None:
- os.sched_setaffinity(0, original_affinity)
+ await asyncio.wait_for(GLOBAL_LOGGING_WORKER.clear_queue(), timeout=10)
+ except asyncio.TimeoutError:
+ pass
+
+
@pytest.mark.asyncio
@@ -123,7 +126,7 @@ async def test_schema_validation_stops_expensive_work_and_recovers(cancel: bool,
await group
[email protected](scope="session")
[email protected](scope="module")
def schema_peer() -> typing.Iterator[Wire]:
def respond(request: WireRequest) -> Reply:
if request.method == "GET":
@@ -220,7 +223,7 @@ def test_proxy_schema_validation_resolves_only_local_references(
assert called["content"][0]["text"] == "called"
[email protected](scope="session", autouse=True)
[email protected](scope="module", autouse=True)
def _clear_proxy_database_env() -> typing.Iterator[None]:
"""Ensure local proxy DB settings don't leak into tests."""
mp = pytest.MonkeyPatch()
@@ -345,7 +348,7 @@ def test_proxy_startup_failure_closes_acquired_resources(tmp_path: Path) -> None
sys.executable,
"-P",
"-c",
- "import sys; from tests.mcp_tests.test_proxy_mcp_e2e import _check_failed_startup; "
+ "import sys; from tests.integration.mcp.test_proxy_mcp_e2e import _check_failed_startup; "
"_check_failed_startup(sys.argv[1])",
str(config),
),
@@ -396,19 +399,19 @@ def _math_http_server(offset: int) -> typing.Iterator[str]:
process.wait(timeout=5)
[email protected](scope="session")
[email protected](scope="module")
def math_streamable_http_server() -> typing.Iterator[str]:
with _math_http_server(100) as url:
yield url
[email protected](scope="session")
[email protected](scope="module")
def math_restricted_server() -> typing.Iterator[str]:
with _math_http_server(200) as url:
yield url
[email protected](scope="session")
[email protected](scope="module")
def _proxy_server(
tmp_path_factory: pytest.TempPathFactory,
math_streamable_http_server: str,
diff --git a/tests/integration/run.py b/tests/integration/run.py
index 7db0087a94c..97c79d1845d 100644
--- a/tests/integration/run.py
+++ b/tests/integration/run.py
@@ -24,7 +24,15 @@ GROUPS: Final = MappingProxyType(
}
)
GITHUB_FILES: Final = frozenset(
- {"tests/integration/database/test_roi_observed.py", "tests/integration/mcp/test_interactions.py"}
+ {
+ "tests/integration/database/test_roi_observed.py",
+ "tests/integration/database/image/test_component_image_serves_offline.py",
+ "tests/integration/database/image/test_image_admin_mcp.py",
+ "tests/integration/database/image/test_image_bedrock_realtime_extra.py",
+ "tests/integration/database/image/test_offline_image_migration.py",
+ "tests/integration/database/image/test_ui_image_serves_offline.py",
+ "tests/integration/mcp/test_interactions.py",
+ }
)
diff --git a/tests/integration/security/test_master_key_not_in_db.py b/tests/integration/security/test_master_key_not_in_db.py
new file mode 100644
index 00000000000..d94eacb1fb7
--- /dev/null
+++ b/tests/integration/security/test_master_key_not_in_db.py
@@ -0,0 +1,25 @@
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Final
+
+from integration._support.client import Gateway
+from integration._support.database import read_rows, scratch_database
+from integration._support.process import owned_proxy
+
+from litellm.proxy.utils import hash_token
+
+
+def test_master_key_not_inserted(gateway: Gateway, tmp_path: Path) -> None:
+ with scratch_database() as database:
+ with owned_proxy(
+ gateway, tmp_path, {"DATABASE_URL": database}, remove_environment=("DIRECT_URL", "DATABASE_URL_READ_REPLICA")
+ ) as proxy:
+ assert proxy.request("GET", "/health/liveliness").status_code == 200
+ stored_tokens: Final = frozenset(
+ row["token"]
+ for row in read_rows('SELECT token FROM "LiteLLM_VerificationToken"', (), database_url=database)
+ )
+ for leaked in (hash_token(gateway.key), gateway.key):
+ assert leaked not in stored_tokens, "the master key was found in LiteLLM_VerificationToken"
+ assert stored_tokens == frozenset(), f"startup unexpectedly wrote tokens to LiteLLM_VerificationToken: {stored_tokens}"
diff --git a/tests/mcp_tests/conftest.py b/tests/mcp_tests/conftest.py
deleted file mode 100644
index ca3e25949ba..00000000000
--- a/tests/mcp_tests/conftest.py
+++ /dev/null
@@ -1,87 +0,0 @@
-# conftest.py
-
-import importlib
-import os
-
-import pytest
-
-import litellm
-import asyncio
-from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
-
-
[email protected](scope="session")
-def event_loop():
- try:
- loop = asyncio.get_running_loop()
- except RuntimeError:
- loop = asyncio.new_event_loop()
- yield loop
- loop.close()
-
-
[email protected](scope="function", autouse=True)
-def setup_and_teardown():
- """
- This fixture reloads litellm before every function. To speed up testing by removing callbacks being chained.
- """
- curr_dir = os.getcwd() # Get the current working directory
-
- from litellm import Router
-
- importlib.reload(litellm)
- import asyncio
-
- loop = asyncio.get_event_loop_policy().new_event_loop()
- asyncio.set_event_loop(loop)
- print(litellm)
- # from litellm import Router, completion, aembedding, acompletion, embedding
- yield
-
- # Teardown code (executes after the yield point)
- # LoggingWorker carries still-queued coroutines onto the next test's loop, where they'd log into that test's callbacks
- asyncio.run(GLOBAL_LOGGING_WORKER.clear_queue())
- loop.close() # Close the loop created earlier
- asyncio.set_event_loop(None) # Remove the reference to the loop
-
-
[email protected](scope="function", autouse=True)
-async def drain_logging_worker():
- """
- The logging queue is bound to the running loop, so anything left queued when a test's loop
- goes away is carried onto the next test's loop and fires against its callbacks.
- """
- from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
-
- yield
-
- try:
- await asyncio.wait_for(GLOBAL_LOGGING_WORKER.clear_queue(), timeout=10)
- except asyncio.TimeoutError:
- pass
-
-
-def pytest_collection_modifyitems(config, items):
- # Separate tests in 'test_amazing_proxy_custom_logger.py' and other tests
- custom_logger_tests = [
- item for item in items if "custom_logger" in item.parent.name
- ]
- other_tests = [item for item in items if "custom_logger" not in item.parent.name]
-
- # Sort tests based on their names
- custom_logger_tests.sort(key=lambda x: x.name)
- other_tests.sort(key=lambda x: x.name)
-
- # Reorder the items list
- items[:] = custom_logger_tests + other_tests
-
-
-def config_only_mcp_manager_factory():
- from litellm.proxy._experimental.mcp_server.mcp_server_manager import MCPServerManager
-
- class ConfigOnlyManager(MCPServerManager):
- def initialize_tool_name_to_mcp_server_name_mapping(self):
- return None
-
- return ConfigOnlyManager
diff --git a/tests/mcp_tests/test_aresponses_api_with_mcp_providers.py b/tests/mcp_tests/test_aresponses_api_with_mcp_providers.py
deleted file mode 100644
index 1f9e3e4eb76..00000000000
--- a/tests/mcp_tests/test_aresponses_api_with_mcp_providers.py
+++ /dev/null
@@ -1,389 +0,0 @@
-import logging
-import os
-import pytest
-from mcp.types import Tool as MCPTool
-from typing import Any, cast
-
-import litellm
-from litellm.responses.mcp.litellm_proxy_mcp_handler import LiteLLM_Proxy_MCP_Handler
-
-
-class MockUserAPIKeyAuth:
- """Mock UserAPIKeyAuth for testing"""
-
- def __init__(self):
- self.api_key = "test_key"
- self.user_id = "test_user"
- self.team_id = "test_team"
- self.user_email = "[email protected]"
- self.max_budget = 100.0
- self.spend = 0.0
- self.models = []
- self.aliases = {}
- self.config = {}
- self.permissions = {}
- self.metadata = {}
- self.object_permission_id = "test_permission_id"
-
- "model",
- [
- pytest.param("gpt-4o-mini", id="openai"),
- pytest.param("claude-haiku-4-5", id="anthropic"),
- ],
-)
-async def test_streaming_responses_api_with_mcp_tools(
- model: str, caplog: pytest.LogCaptureFixture
-):
- """
- Test the streaming responses API with MCP tools when using server_url="litellm_proxy"
-
- Under the hood the follow occurs
-
- - MCP: responses called litellm MCP manager.list_tools (MOCKED)
- - Request 1: Made to model under test with fetched tools (REAL LLM CALL)
- - MCP: Execute tool call from request 1 and returns result (MOCKED)
- - Request 2: Made to model under test with fetched tools and tool results (REAL LLM CALL)
-
- Return the user the result of request 2
- """
- if ("claude" in model.lower() or "anthropic" in model.lower()) and not os.getenv(
- "ANTHROPIC_API_KEY"
- ):
- pytest.skip("ANTHROPIC_API_KEY not set, skipping anthropic model test")
- if ("gpt" in model.lower() or "openai" in model.lower()) and not os.getenv(
- "OPENAI_API_KEY"
- ):
- pytest.skip("OPENAI_API_KEY not set, skipping openai model test")
-
- from unittest.mock import AsyncMock, patch
-
- print("🧪 Testing basic streaming with MCP tools...")
-
- mock_mcp_tools = [
- MCPTool.model_validate({
- "name": "search_repo",
- "description": "Search BerriAI/litellm repository for information",
- "inputSchema": {
- "type": "object",
- "properties": {
- "query": {"type": "string", "description": "Search query"}
- },
- "required": ["query"],
- },
- }, by_name=False)
- ]
-
- with caplog.at_level(logging.ERROR):
- with (
- patch.object(
- LiteLLM_Proxy_MCP_Handler,
- "_get_mcp_tools_from_manager",
- new_callable=AsyncMock,
- ) as mock_get_tools,
- patch.object(
- LiteLLM_Proxy_MCP_Handler,
- "execute_tool_calls",
- new_callable=AsyncMock,
- ) as mock_execute_tools,
- ):
- mock_get_tools.return_value = (mock_mcp_tools, ["litellm_proxy"])
-
- def mock_execute_tool_calls_side_effect(
- tool_calls, user_api_key_auth, **kwargs
- ):
- """Mock function that returns results matching the actual tool call IDs from the LLM"""
- results = []
- for tool_call in tool_calls:
- call_id = None
- if isinstance(tool_call, dict):
- call_id = tool_call.get("call_id") or tool_call.get("id")
- elif hasattr(tool_call, "call_id"):
- call_id = tool_call.call_id
- elif hasattr(tool_call, "id"):
- call_id = tool_call.id
-
- if call_id:
- results.append(
- {
- "tool_call_id": call_id,
- "result": "LiteLLM is a unified interface for 100+ LLMs that translates inputs to provider-specific completion endpoints and provides consistent OpenAI-format output.",
- }
- )
- return results
-
- mock_execute_tools.side_effect = mock_execute_tool_calls_side_effect
-
- mcp_tool_config = cast(
- Any,
- {
- "type": "mcp",
- "server_url": "litellm_proxy",
- "require_approval": "never",
- },
- )
- response = await litellm.aresponses(
- model=model,
- tools=[mcp_tool_config],
- tool_choice="required",
- input=[
- {
- "role": "user",
- "type": "message",
- "content": "give me a TLDR of what BerriAI/litellm is about",
- }
- ],
- stream=True,
- )
-
- print(f"📋 Response type: {type(response)}")
- assert hasattr(
- response, "__aiter__"
- ), "Response should be an async streaming response"
-
- chunks = []
- async for chunk in response:
- chunks.append(chunk)
- print(f"📦 Chunk type: {getattr(chunk, 'type', 'unknown')}")
-
- print(f"📊 Total chunks received: {len(chunks)}")
-
- assert (
- mock_get_tools.call_count >= 1
- ), f"Expected MCP tools to be fetched at least once, got {mock_get_tools.call_count}"
- print(f"MCP tools fetched: {len(mock_mcp_tools)}")
-
- assert response is not None
- assert len(chunks) > 0, "Should have received streaming chunks"
-
- print("Basic streaming responses API with MCP tools test passed!")
-
- lite_errors = [
- record
- for record in caplog.records
- if record.levelno >= logging.ERROR
- and ("LiteLLM" in record.name or "LiteLLM" in record.getMessage())
- ]
- assert not lite_errors, "Unexpected LiteLLM errors: " + ", ".join(
- record.getMessage() for record in lite_errors
- )
-
-
-
[email protected]("model", ["gpt-4o-mini"])
-async def test_streaming_mcp_event_order_and_response_id_consistency(
- model: str, caplog: pytest.LogCaptureFixture
-):
- """
- Test that:
- 1. Streaming events are emitted in correct order (response.created, response.in_progress, response.output_item.added before MCP events)
- 2. All response lifecycle events share the same response ID within a cycle
- """
- if ("gpt" in model.lower() or "openai" in model.lower()) and not os.getenv(
- "OPENAI_API_KEY"
- ):
- pytest.skip("OPENAI_API_KEY not set, skipping openai model test")
-
- from unittest.mock import AsyncMock, patch
-
- mock_mcp_tools = [
- MCPTool.model_validate({
- "name": "get_weather",
- "description": "Get weather for a city",
- "inputSchema": {
- "type": "object",
- "properties": {
- "city": {"type": "string", "description": "City name"}
- },
- "required": ["city"],
- },
- }, by_name=False)
- ]
-
- with caplog.at_level(logging.ERROR):
- with (
- patch.object(
- LiteLLM_Proxy_MCP_Handler,
- "_get_mcp_tools_from_manager",
- new_callable=AsyncMock,
- ) as mock_get_tools,
- patch.object(
- LiteLLM_Proxy_MCP_Handler,
- "execute_tool_calls",
- new_callable=AsyncMock,
- ) as mock_execute_tools,
- ):
- mock_get_tools.return_value = (mock_mcp_tools, ["litellm_proxy"])
-
- def mock_execute_side_effect(tool_calls, user_api_key_auth, **kwargs):
- results = []
- for tool_call in tool_calls:
- call_id = None
- if isinstance(tool_call, dict):
- call_id = tool_call.get("call_id") or tool_call.get("id")
- elif hasattr(tool_call, "call_id"):
- call_id = tool_call.call_id
- elif hasattr(tool_call, "id"):
- call_id = tool_call.id
- if call_id:
- results.append(
- {
- "tool_call_id": call_id,
- "result": "Sunny, 72°F",
- }
- )
- return results
-
- mock_execute_tools.side_effect = mock_execute_side_effect
-
- mcp_tool_config = cast(
- Any,
- {
- "type": "mcp",
- "server_url": "litellm_proxy",
- "require_approval": "never",
- },
- )
-
- response = await litellm.aresponses(
- model=model,
- tools=[mcp_tool_config],
- input=[
- {
- "role": "user",
- "type": "message",
- "content": "What's the weather in San Francisco?",
- }
- ],
- stream=True,
- )
-
- events = []
- async for chunk in response:
- events.append(chunk)
-
- assert len(events) > 0, "Should receive streaming events"
-
- created_idx = next(
- (
- i
- for i, e in enumerate(events)
- if getattr(e, "type", None) == "response.created"
- ),
- None,
- )
- in_progress_idx = next(
- (
- i
- for i, e in enumerate(events)
- if getattr(e, "type", None) == "response.in_progress"
- ),
- None,
- )
- output_item_added_idx = next(
- (
- i
- for i, e in enumerate(events)
- if getattr(e, "type", None) == "response.output_item.added"
- ),
- None,
- )
- mcp_in_progress_idx = next(
- (
- i
- for i, e in enumerate(events)
- if "mcp_list_tools.in_progress" in str(getattr(e, "type", ""))
- ),
- None,
- )
- completed_idx = next(
- (
- i
- for i, e in enumerate(events)
- if getattr(e, "type", None) == "response.completed"
- ),
- None,
- )
-
- assert created_idx is not None, "response.created event should be present"
- assert (
- in_progress_idx is not None
- ), "response.in_progress event should be present"
- assert (
- output_item_added_idx is not None
- ), "response.output_item.added event should be present"
-
- assert (
- created_idx < in_progress_idx
- ), "response.created should come before response.in_progress"
- assert (
- in_progress_idx < output_item_added_idx
- ), "response.in_progress should come before response.output_item.added"
-
- if mcp_in_progress_idx is not None:
- assert (
- output_item_added_idx < mcp_in_progress_idx
- ), "response.output_item.added should come before response.mcp_list_tools.in_progress"
-
- response_ids = []
- for i, event in enumerate(events):
- event_type = getattr(event, "type", None)
- if hasattr(event, "response"):
- response_obj = getattr(event, "response", None)
- if response_obj and hasattr(response_obj, "id"):
- event_type_value = (
- event_type.value
- if hasattr(event_type, "value")
- else str(event_type)
- )
- if any(
- x in event_type_value
- for x in [
- "response.created",
- "response.in_progress",
- "response.completed",
- ]
- ):
- response_ids.append((i, event_type_value, response_obj.id))
-
- assert (
- len(response_ids) >= 2
- ), f"Should have at least 2 response lifecycle events. Found {len(response_ids)}"
-
- cycles = []
- current_cycle = []
- current_id = None
-
- for idx, event_type, resp_id in response_ids:
- if current_id is None or resp_id == current_id:
- current_cycle.append((idx, event_type, resp_id))
- current_id = resp_id
- else:
- if current_cycle:
- cycles.append(current_cycle)
- current_cycle = [(idx, event_type, resp_id)]
- current_id = resp_id
- if current_cycle:
- cycles.append(current_cycle)
-
- for cycle_num, cycle in enumerate(cycles):
- cycle_ids = set(resp_id for _, _, resp_id in cycle)
- assert (
- len(cycle_ids) == 1
- ), f"Cycle {cycle_num + 1} should have consistent response ID. Found {len(cycle_ids)} unique IDs"
-
- assert (
- completed_idx is not None
- ), "response.completed event should be present"
-
- lite_errors = [
- record
- for record in caplog.records
- if record.levelno >= logging.ERROR
- and ("LiteLLM" in record.name or "LiteLLM" in record.getMessage())
- ]
- assert not lite_errors, "Unexpected LiteLLM errors: " + ", ".join(
- record.getMessage() for record in lite_errors
- )
diff --git a/tests/mcp_tests/test_mcp_litellm_client.py b/tests/mcp_tests/test_mcp_litellm_client.py
deleted file mode 100644
index cfc0692c8fa..00000000000
--- a/tests/mcp_tests/test_mcp_litellm_client.py
+++ /dev/null
@@ -1,108 +0,0 @@
-# Create server parameters for stdio connection
-import os
-import pytest
-import asyncio
-
-
-from mcp import ClientSession, StdioServerParameters
-from mcp.client.stdio import stdio_client
-from litellm import experimental_mcp_client
-import litellm
-import json
-
-
- reason="Fails due to missing 'mcp' package and connection issues in CI/local env."
-)
-async def test_mcp_agent():
- """Test MCP agent functionality with a simple math server"""
- try:
- local_server_path = "./mcp_server.py"
- ci_cd_server_path = "tests/mcp_tests/mcp_server.py"
-
- # Use the correct path for the server
- server_path = (
- ci_cd_server_path
- if os.path.exists(ci_cd_server_path)
- else local_server_path
- )
-
- if not os.path.exists(server_path):
- pytest.skip(f"MCP server file not found at {server_path}")
-
- server_params = StdioServerParameters(
- command="python3",
- args=[server_path],
- )
-
- # Add timeout to prevent hanging
- async with asyncio.timeout(30): # 30 second timeout
- async with stdio_client(server_params) as (read, write):
- async with ClientSession(read, write) as session:
- # Initialize the connection
- await session.initialize()
-
- # Get tools
- tools = await experimental_mcp_client.load_mcp_tools(
- session=session, format="openai"
- )
- print("MCP TOOLS: ", tools)
-
- # Create and run the agent
- messages = [{"role": "user", "content": "what's (3 + 5)"}]
- llm_response = await litellm.acompletion(
- model="gpt-4o",
- api_key=os.getenv("OPENAI_API_KEY"),
- messages=messages,
- tools=tools,
- tool_choice="required",
- )
- print(
- "LLM RESPONSE: ",
- json.dumps(llm_response, indent=4, default=str),
- )
- # Add assertions to verify the response
- assert (
- llm_response["choices"][0]["message"]["tool_calls"] is not None
- )
-
- assert (
- llm_response["choices"][0]["message"]["tool_calls"][0][
- "function"
- ]["name"]
- == "add"
- )
- openai_tool = llm_response["choices"][0]["message"]["tool_calls"][0]
-
- # Call the tool using MCP client
- call_result = await experimental_mcp_client.call_openai_tool(
- session=session,
- openai_tool=openai_tool,
- )
- print("CALL RESULT: ", call_result)
-
- # send the tool result to the LLM
- messages.append(llm_response["choices"][0]["message"])
- messages.append(
- {
- "role": "tool",
- "content": str(call_result.content[0].text),
- "tool_call_id": openai_tool["id"],
- }
- )
- print("final messages: ", messages)
- llm_response = await litellm.acompletion(
- model="gpt-4o",
- api_key=os.getenv("OPENAI_API_KEY"),
- messages=messages,
- tools=tools,
- )
- print(
- "FINAL LLM RESPONSE: ",
- json.dumps(llm_response, indent=4, default=str),
- )
- except asyncio.TimeoutError:
- pytest.skip("MCP server connection timed out - skipping test")
- except Exception as e:
- pytest.skip(f"MCP test failed with error: {str(e)} - skipping test")
diff --git a/tests/mcp_tests/test_semantic_tool_filter_e2e.py b/tests/mcp_tests/test_semantic_tool_filter_e2e.py
deleted file mode 100644
index aa25c98107e..00000000000
--- a/tests/mcp_tests/test_semantic_tool_filter_e2e.py
+++ /dev/null
@@ -1,134 +0,0 @@
-"""
-End-to-end test for MCP Semantic Tool Filtering
-"""
-
-import asyncio
-import os
-from unittest.mock import Mock
-
-import pytest
-
-
-from mcp.types import Tool as MCPTool
-
-# Check if semantic-router is available
-try:
- import semantic_router
-
- SEMANTIC_ROUTER_AVAILABLE = True
-except ImportError:
- SEMANTIC_ROUTER_AVAILABLE = False
-
-
- not SEMANTIC_ROUTER_AVAILABLE,
- reason="semantic-router not installed. Install the `litellm[semantic-router]` extra.",
-)
- not os.environ.get("OPENAI_API_KEY"), reason="OPENAI_API_KEY not set in environment"
-)
-async def test_e2e_semantic_filter():
- """E2E: Load router/filter and verify hook filters tools."""
- from litellm import Router
- from litellm.proxy.hooks.mcp_semantic_filter import SemanticToolFilterHook
- from litellm.proxy._experimental.mcp_server.semantic_tool_filter import (
- SemanticMCPToolFilter,
- )
-
- # Create router and filter
- router = Router(
- model_list=[
- {
- "model_name": "text-embedding-3-small",
- "litellm_params": {"model": "openai/text-embedding-3-small"},
- }
- ]
- )
-
- filter_instance = SemanticMCPToolFilter(
- embedding_model="text-embedding-3-small",
- litellm_router_instance=router,
- top_k=3,
- enabled=True,
- )
-
- # Create 10 tools
- tools = [
- MCPTool(
- name="gmail_send",
- description="Send an email via Gmail",
- inputSchema={"type": "object"},
- ),
- MCPTool(
- name="calendar_create",
- description="Create a calendar event",
- inputSchema={"type": "object"},
- ),
- MCPTool(
- name="file_upload",
- description="Upload a file",
- inputSchema={"type": "object"},
- ),
- MCPTool(
- name="web_search",
- description="Search the web",
- inputSchema={"type": "object"},
- ),
- MCPTool(
- name="slack_send",
- description="Send Slack message",
- inputSchema={"type": "object"},
- ),
- MCPTool(
- name="doc_read", description="Read document", inputSchema={"type": "object"}
- ),
- MCPTool(
- name="db_query",
- description="Query database",
- inputSchema={"type": "object"},
- ),
- MCPTool(
- name="api_call", description="Make API call", inputSchema={"type": "object"}
- ),
- MCPTool(
- name="task_create",
- description="Create task",
- inputSchema={"type": "object"},
- ),
- MCPTool(
- name="note_add", description="Add note", inputSchema={"type": "object"}
- ),
- ]
-
- # Build router with test tools
- filter_instance._build_router(tools)
-
- hook = SemanticToolFilterHook(filter_instance)
-
- data = {
- "model": "gpt-4",
- "messages": [
- {"role": "user", "content": "Send an email and create a calendar event"}
- ],
- "tools": tools,
- "metadata": {}, # Initialize metadata dict for hook to store filter stats
- }
-
- # Call hook
- result = await hook.async_pre_call_hook(
- user_api_key_dict=Mock(),
- cache=Mock(),
- data=data,
- call_type="completion",
- )
-
- # Single assertion: hook filtered tools
- assert result and len(result["tools"]) < len(
- tools
- ), f"Expected filtered tools, got {len(result['tools'])} tools (original: {len(tools)})"
-
- print(
- f"✅ E2E test passed: Filtering reduced tools from {len(tools)} to {len(result['tools'])}"
- )
- print(f" Filtered tools: {[t.name for t in result['tools']]}")
diff --git a/tests/proxy_security_tests/test_master_key_not_in_db.py b/tests/proxy_security_tests/test_master_key_not_in_db.py
deleted file mode 100644
index 1eaaafae708..00000000000
--- a/tests/proxy_security_tests/test_master_key_not_in_db.py
+++ /dev/null
@@ -1,61 +0,0 @@
-import os
-import pytest
-from fastapi.testclient import TestClient
-from litellm.proxy.proxy_server import app, ProxyLogging, hash_token
-from litellm.caching import DualCache
-from tests._master_key import MASTER_KEY
-
-
[email protected](autouse=True)
-def override_env_settings(monkeypatch):
- if "DATABASE_URL" not in os.environ:
- pytest.fail(
- "DATABASE_URL not set - this test requires a postgres database to be running"
- )
- monkeypatch.setenv("LITELLM_MASTER_KEY", MASTER_KEY)
- monkeypatch.setenv("LITELLM_LOG", "DEBUG")
-
-
[email protected](scope="module")
-def test_client():
- """Starting the test client triggers FastAPI startup, where Prisma connects to the DB."""
- with pytest.MonkeyPatch.context() as boot_env:
- boot_env.setenv("LITELLM_DANGEROUSLY_PERMIT_WEAK_OR_UNSET_MASTER_KEY", "true")
- with TestClient(app) as client:
- yield client
-
-
-async def test_master_key_not_inserted(test_client):
- """The master key must never be persisted to the verification-token table on startup."""
- response = test_client.get("/health/liveliness")
- assert response.status_code == 200
-
- from litellm.proxy.utils import PrismaClient
-
- prisma_client = PrismaClient(
- database_url=os.environ["DATABASE_URL"],
- proxy_logging_obj=ProxyLogging(
- user_api_key_cache=DualCache(), premium_user=True
- ),
- )
-
- await prisma_client.connect()
- stored_tokens = {
- row.token
- for row in await prisma_client.db.litellm_verificationtoken.find_many()
- }
-
- for leaked in (hash_token(MASTER_KEY), MASTER_KEY):
- assert leaked not in stored_tokens, (
- "SECURITY ALERT: the master key was found in the litellm_verificationtoken "
- "table. The master key must never be inserted into the DB."
- )
-
- # Canary against any other unexpected startup write (default key, rotation
- # artifact, ...). The job gives each run a fresh DB, so a clean startup must
- # leave the table empty; if startup ever legitimately seeds a token, narrow
- # this while keeping the master-key assertion above.
- assert (
- not stored_tokens
- ), f"startup unexpectedly wrote token(s) to litellm_verificationtoken: {stored_tokens}"
diff --git a/tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py b/tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py
index a4ed691f5ee..697c5a828bb 100644
--- a/tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py
+++ b/tests/unit/litellm_proxy_extras/test_litellm_proxy_extras_utils.py
@@ -2150,3 +2150,12 @@ def test_redact_command_error_masks_password_in_tuple_url_argument(
assert message.startswith("Command '('")
assert password not in message
assert "postgresql://REDACTED@db:5432/litellm" in message
+
+
+def test_repair_survives_an_unreachable_database(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.delenv("DIRECT_URL", raising=False)
+ monkeypatch.setenv("DATABASE_URL", "postgresql://u:[email protected]:9/x?schema=whatever")
+
+ assert ProxyExtrasDBManager.repair_invalid_indexes() is False
+
+
diff --git a/tests/unit/litellm_proxy_extras/test_prisma_toolchain.py b/tests/unit/litellm_proxy_extras/test_prisma_toolchain.py
new file mode 100644
index 00000000000..e44b8183f96
--- /dev/null
+++ b/tests/unit/litellm_proxy_extras/test_prisma_toolchain.py
@@ -0,0 +1,257 @@
+import os
+import sys
+from collections.abc import Callable
+from pathlib import Path
+
+import pytest
+from litellm_proxy_extras.prisma_toolchain import (
+ DEFAULT_PRISMA_COMMAND_TIMEOUT,
+ DEFAULT_PRISMA_MIGRATE_DEPLOY_TIMEOUT,
+ PRISMA_BOOTSTRAP_TIMEOUT_ENV_VAR,
+ PRISMA_COMMAND_TIMEOUT_ENV_VAR,
+ PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR,
+ heal_incomplete_nodeenv_cache,
+ node_binary_path,
+ prisma_bootstrap_timeout,
+ prisma_cli_available,
+ prisma_command_timeout,
+ prisma_migrate_deploy_timeout,
+ resolve_prisma_argv,
+)
+
+
+FAKE_PRISMA = """#!{python}
+import json
+import os
+import pathlib
+import subprocess
+import sys
+import time
+
+args = sys.argv[1:]
+cache_dir = os.environ["PRISMA_NODEENV_CACHE_DIR"]
+log_path = pathlib.Path(os.environ["FAKE_PRISMA_LOG"])
+earlier_same_command = sum(
+ 1
+ for line in (log_path.read_text().splitlines() if log_path.exists() else [])
+ if json.loads(line)["args"][:2] == args[:2]
+)
+with log_path.open("a") as log:
+ log.write(
+ json.dumps({{"args": args, "cache_dir_present": os.path.isdir(cache_dir)}})
+ + "\\n"
+ )
+time.sleep(float(os.environ.get("FAKE_PRISMA_SLEEP", "0")))
+if args[:2] == ["migrate", "deploy"]:
+ if earlier_same_command == 0:
+ if os.environ.get("FAKE_PRISMA_GRANDCHILD_PIDFILE"):
+ grandchild = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(600)"])
+ pathlib.Path(os.environ["FAKE_PRISMA_GRANDCHILD_PIDFILE"]).write_text(str(grandchild.pid))
+ time.sleep(float(os.environ.get("FAKE_PRISMA_FIRST_DEPLOY_SLEEP", "0")))
+ elif os.environ.get("FAKE_PRISMA_LATER_DEPLOY_STDERR"):
+ print(os.environ["FAKE_PRISMA_LATER_DEPLOY_STDERR"], file=sys.stderr)
+ sys.exit(1)
+ print("No pending migrations to apply")
+if args[:2] == ["db", "push"] and earlier_same_command == 0:
+ time.sleep(float(os.environ.get("FAKE_PRISMA_FIRST_PUSH_SLEEP", "0")))
+sys.exit(0)
+"""
+
+
+def _write_fake_prisma(tmp_path: Path) -> Path:
+ bin_dir = tmp_path / "fakebin"
+ bin_dir.mkdir()
+ script = bin_dir / "prisma"
+ script.write_text(FAKE_PRISMA.format(python=sys.executable))
+ script.chmod(0o755)
+ return bin_dir
+
+
+def toolchain_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]:
+ """Point the toolchain at a scratch cache dir driven by a fake Prisma CLI."""
+ cache_dir = tmp_path / "nodeenv"
+ log_path = tmp_path / "prisma-calls.jsonl"
+ bin_dir = _write_fake_prisma(tmp_path)
+ monkeypatch.setenv("PRISMA_NODEENV_CACHE_DIR", str(cache_dir))
+ monkeypatch.setenv("FAKE_PRISMA_LOG", str(log_path))
+ monkeypatch.setenv("PATH", f"{bin_dir}{os.pathsep}{os.environ['PATH']}")
+ monkeypatch.delenv(PRISMA_COMMAND_TIMEOUT_ENV_VAR, raising=False)
+ monkeypatch.delenv(PRISMA_BOOTSTRAP_TIMEOUT_ENV_VAR, raising=False)
+ monkeypatch.delenv(PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, raising=False)
+ return cache_dir, log_path
+
+
+def _make_incomplete_cache(cache_dir: Path) -> None:
+ (cache_dir / "lib").mkdir(parents=True)
+ (cache_dir / "bin").mkdir()
+
+
+FAKE_PRISMA_MODULE_MAIN = """import json
+import sys
+
+print(json.dumps({"module_argv": sys.argv[1:]}))
+"""
+
+
+def _write_fake_prisma_module(tmp_path: Path) -> Path:
+ package_dir = tmp_path / "fakemodule" / "prisma"
+ package_dir.mkdir(parents=True)
+ (package_dir / "__init__.py").write_text("")
+ (package_dir / "__main__.py").write_text(FAKE_PRISMA_MODULE_MAIN)
+ return package_dir.parent
+
+
+def _empty_bin(tmp_path: Path) -> Path:
+ bin_dir = tmp_path / "emptybin"
+ bin_dir.mkdir()
+ return bin_dir
+
+
+def _make_complete_cache(cache_dir: Path) -> None:
+ node = node_binary_path(cache_dir)
+ node.parent.mkdir(parents=True)
+ node.write_text("")
+
+
+def test_interrupted_toolchain_install_is_removed(
+ toolchain_env: tuple[Path, Path],
+) -> None:
+ cache_dir, _ = toolchain_env
+ _make_incomplete_cache(cache_dir)
+
+ assert heal_incomplete_nodeenv_cache() is True
+ assert not cache_dir.exists()
+
+
+def test_installed_toolchain_is_left_alone(toolchain_env: tuple[Path, Path]) -> None:
+ cache_dir, _ = toolchain_env
+ _make_complete_cache(cache_dir)
+
+ assert heal_incomplete_nodeenv_cache() is False
+ assert node_binary_path(cache_dir).exists()
+
+
+def test_absent_toolchain_is_not_an_error(toolchain_env: tuple[Path, Path]) -> None:
+ cache_dir, _ = toolchain_env
+
+ assert heal_incomplete_nodeenv_cache() is False
+ assert not cache_dir.exists()
+
+
+_CAN_DENY_ACCESS = os.name != "nt" and hasattr(os, "geteuid") and os.geteuid() != 0
+
+
[email protected](not _CAN_DENY_ACCESS, reason="root and Windows do not honour a 0o000 directory")
+def test_unreadable_cache_dir_is_not_an_error(
+ toolchain_env: tuple[Path, Path],
+) -> None:
+ """A cache dir this process cannot stat means nothing to heal, not a crash.
+
+ Images bake the cache under the build user's home, and a container started
+ under any other uid cannot search that directory. `Path.is_dir()` only
+ swallows ENOENT-shaped errnos, so it raises `PermissionError` there and
+ kills the migration before Prisma is ever invoked.
+ """
+ cache_dir, _ = toolchain_env
+ _make_incomplete_cache(cache_dir)
+ cache_dir.parent.chmod(0o000)
+
+ try:
+ assert heal_incomplete_nodeenv_cache() is False
+ finally:
+ cache_dir.parent.chmod(0o700)
+
+
+ ("command_timeout", "deploy_timeout", "expected"),
+ [
+ ("900", None, 900.0),
+ ("12", None, DEFAULT_PRISMA_MIGRATE_DEPLOY_TIMEOUT),
+ ("900", "1200", 1200.0),
+ ("900", "300", 300.0),
+ ],
+ ids=[
+ "raised_command_budget_carries_over",
+ "lowered_command_budget_does_not",
+ "override_wins_upward",
+ "override_wins_downward",
+ ],
+)
+def test_migrate_deploy_budget_keeps_a_raised_command_budget(
+ command_timeout: str, deploy_timeout: str | None, expected: float, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Deployments that raised the per-command budget to survive a long deploy keep that budget for deploy."""
+ monkeypatch.setenv(PRISMA_COMMAND_TIMEOUT_ENV_VAR, command_timeout)
+ if deploy_timeout is None:
+ monkeypatch.delenv(PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, raising=False)
+ else:
+ monkeypatch.setenv(PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, deploy_timeout)
+
+ assert prisma_migrate_deploy_timeout() == expected
+
+
+ "raw",
+ ["", "0", "-5", "not-a-number", "nan", "inf", "-inf", "1e400"],
+)
+ ("env_var", "read_timeout", "default"),
+ [
+ (PRISMA_COMMAND_TIMEOUT_ENV_VAR, prisma_command_timeout, DEFAULT_PRISMA_COMMAND_TIMEOUT),
+ (PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, prisma_migrate_deploy_timeout, DEFAULT_PRISMA_MIGRATE_DEPLOY_TIMEOUT),
+ ],
+ ids=["command", "migrate_deploy"],
+)
+def test_unusable_timeout_override_falls_back_to_the_default(
+ raw: str, env_var: str, read_timeout: Callable[[], float], default: float, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """A non-finite override would silently disable the timeout it configures."""
+ monkeypatch.setenv(env_var, raw)
+
+ assert read_timeout() == default
+
+
+def test_timeout_overrides_are_independent(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv(PRISMA_COMMAND_TIMEOUT_ENV_VAR, "12")
+ monkeypatch.setenv(PRISMA_BOOTSTRAP_TIMEOUT_ENV_VAR, "900")
+ monkeypatch.setenv(PRISMA_MIGRATE_DEPLOY_TIMEOUT_ENV_VAR, "1200")
+
+ assert prisma_command_timeout() == 12
+ assert prisma_bootstrap_timeout() == 900
+ assert prisma_migrate_deploy_timeout() == 1200
+
+
+def test_resolve_prisma_argv_leaves_an_explicit_cli_path_alone(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("PATH", str(_empty_bin(tmp_path)))
+ explicit = ("/app/.cache/prisma-python/prisma", "migrate", "deploy")
+
+ assert resolve_prisma_argv(explicit) == explicit
+
+
+def test_prisma_cli_is_unavailable_with_neither_script_nor_package(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("PATH", str(_empty_bin(tmp_path)))
+ monkeypatch.delitem(sys.modules, "prisma", raising=False)
+ monkeypatch.setattr(sys, "path", [])
+
+ assert prisma_cli_available() is False
+
+
+def test_prisma_cli_is_available_through_the_package_alone(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("PATH", str(_empty_bin(tmp_path)))
+ monkeypatch.delitem(sys.modules, "prisma", raising=False)
+ monkeypatch.setattr(sys, "path", [str(_write_fake_prisma_module(tmp_path))])
+
+ assert prisma_cli_available() is True
+
+
+def test_prisma_cli_is_available_through_the_console_script_alone(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ monkeypatch.setenv("PATH", str(_write_fake_prisma(tmp_path)))
+ monkeypatch.delitem(sys.modules, "prisma", raising=False)
+ monkeypatch.setattr(sys, "path", [])
+
+ assert prisma_cli_available() is True
diff --git a/tests/unit/proxy/_experimental/mcp_server/test_mcp_env_vars.py b/tests/unit/proxy/_experimental/mcp_server/test_mcp_env_vars.py
index 6970ffb6b08..807061c946f 100644
--- a/tests/unit/proxy/_experimental/mcp_server/test_mcp_env_vars.py
+++ b/tests/unit/proxy/_experimental/mcp_server/test_mcp_env_vars.py
@@ -3,7 +3,7 @@
These cover the pure helpers in
``litellm.proxy._experimental.mcp_server.utils`` and do not require a DB
connection. The DB-backed per-user flow is exercised in higher-level
-tests in tests/mcp_tests.
+tests in tests/integration/mcp.
"""
from typing import Final
diff --git a/tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.py b/tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.py
index c3a94e04b9f..bd4962829c2 100644
--- a/tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.py
+++ b/tests/unit/proxy/_experimental/mcp_server/test_mcp_tool_search.py
@@ -10,7 +10,10 @@ Covers:
- call_tool_rest_api intercepts mcp_tool_call calls
"""
+import asyncio
import json
+import os
+import sys
from collections.abc import Mapping, Sequence
from types import SimpleNamespace
from typing import Any, Final
@@ -1386,3 +1389,28 @@ async def test_mcp_tool_search_leaves_the_listed_tools_slot_empty(monkeypatch: p
assert result.is_error is False
assert [hit["name"] for hit in json.loads(result.content[0].text)] == ["search-slot-echo"]
assert listed == [None, None]
+
+
+async def test_cold_concurrent_schema_validation_accepts_valid_arguments() -> None:
+ from litellm.proxy._experimental.mcp_server.tool_search import _tool_argument_validation_error
+
+ schema: Final = {
+ "type": "object",
+ "$defs": {"amount": {"type": "number", "multipleOf": 0.25}},
+ "properties": {"amount": {"$ref": "#/$defs/amount"}},
+ }
+ original_affinity: Final = os.sched_getaffinity(0) if sys.platform == "linux" else None
+ try:
+ if original_affinity is not None:
+ os.sched_setaffinity(0, {min(original_affinity)})
+ for _ in range(2):
+ results: Final = await asyncio.gather(
+ *(_tool_argument_validation_error(schema, {"amount": 0.75}) for _ in range(8))
+ )
+ assert results == [None] * 8, "Cold and warm workers must accept valid concurrent tool arguments"
+ finally:
+ if original_affinity is not None:
+ os.sched_setaffinity(0, original_affinity)
+
+
diff --git a/tests/unit/proxy/db/test_replica_identity.py b/tests/unit/proxy/db/test_replica_identity.py
index 9738fc9bd98..f2fbaf929a0 100644
--- a/tests/unit/proxy/db/test_replica_identity.py
+++ b/tests/unit/proxy/db/test_replica_identity.py
@@ -1,7 +1,7 @@
"""The opt-in REPLICA IDENTITY FULL step, without a database.
The behavior against real Postgres is covered by
-tests/proxy_migration_tests/test_replica_identity_full.py; these pin the two
+tests/integration/database/migrations/test_replica_identity_full.py; these pin the two
things that hold with no database at all: the statement handed to the Prisma
CLI, and the promise that no failure of this optional step escapes into a
migration run that already succeeded.
@@ -83,3 +83,48 @@ def test_an_unusable_migrations_dir_skips_the_step_instead_of_killing_the_run(
monkeypatch.setenv("LITELLM_MIGRATION_DIR", str(blocker / "migrations"))
assert ProxyExtrasDBManager.apply_replica_identity_full_if_requested() is False
+
+
+def test_reports_an_unrunnable_prisma_cli_without_raising(tmp_path):
+ """A deployment without the Prisma CLI on PATH must still finish its
+ migration run instead of dying on the optional replication step."""
+ assert (
+ apply_replica_identity_full(
+ schema_path=str(tmp_path / "schema.prisma"),
+ prisma_command=str(tmp_path / "no-such-prisma"),
+ prisma_env={},
+ )
+ is False
+ )
+
+
+def test_setup_database_applies_after_a_successful_migration_run(monkeypatch):
+ applied = []
+ monkeypatch.setattr(
+ ProxyExtrasDBManager, "_run_migrations", staticmethod(lambda **kwargs: True)
+ )
+ monkeypatch.setattr(
+ ProxyExtrasDBManager,
+ "apply_replica_identity_full_if_requested",
+ staticmethod(lambda: applied.append(True)),
+ )
+
+ assert ProxyExtrasDBManager.setup_database(use_migrate=True) is True
+ assert applied == [True]
+
+
+def test_setup_database_skips_replica_identity_when_migrations_fail(monkeypatch):
+ applied = []
+ monkeypatch.setattr(
+ ProxyExtrasDBManager, "_run_migrations", staticmethod(lambda **kwargs: False)
+ )
+ monkeypatch.setattr(
+ ProxyExtrasDBManager,
+ "apply_replica_identity_full_if_requested",
+ staticmethod(lambda: applied.append(True)),
+ )
+
+ assert ProxyExtrasDBManager.setup_database(use_migrate=True) is False
+ assert applied == []
+
+
diff --git a/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py b/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py
index 842b64ae380..745a48d0f6e 100644
--- a/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py
+++ b/tests/unit/responses/mcp/test_aresponses_api_with_mcp.py
@@ -1,6 +1,13 @@
+import json
+import logging
+from collections.abc import Mapping, Sequence
+from types import MappingProxyType
+
+import httpx
import pytest
+import respx
from mcp.types import Tool as MCPTool
-from typing import List, Any, cast
+from typing import Final, List, Any, cast
from unittest.mock import AsyncMock, patch
@@ -1275,3 +1282,207 @@ async def test_no_duplicate_mcp_tools_in_streaming_e2e():
"tools_per_call": [len(tools) for tools in llm_call_tools],
"duplicate_tools_found": False,
}
+
+
+WEATHER_TOOL: Final = MCPTool(
+ name="get_weather",
+ description="Get weather for a city",
+ inputSchema={"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
+)
+WEATHER_ARGUMENTS: Final = {"city": "San Francisco"}
+WEATHER_RESULT: Final = "Sunny, 72F"
+WEATHER_ANSWER: Final = "It is sunny in San Francisco"
+SSE_HEADERS: Final = {"content-type": "text/event-stream"}
+
+
+def _sse(events: Sequence[Mapping[str, object]]) -> bytes:
+ return "".join(f"event: {event['type']}\ndata: {json.dumps(event)}\n\n" for event in events).encode()
+
+
+def _openai_response(response_id: str, status: str, output: Sequence[Mapping[str, object]]) -> dict[str, object]:
+ return {
+ "id": response_id,
+ "object": "response",
+ "created_at": 1700000000,
+ "status": status,
+ "model": "gpt-4o-mini",
+ "output": list(output),
+ "parallel_tool_calls": True,
+ "tool_choice": "auto",
+ "tools": [],
+ "usage": {"input_tokens": 5, "output_tokens": 5, "total_tokens": 10},
+ }
+
+
+def _openai_round(response_id: str, item: Mapping[str, object], done_item: Mapping[str, object]) -> bytes:
+ events: Final = (
+ {"type": "response.created", "response": _openai_response(response_id, "in_progress", ())},
+ {"type": "response.in_progress", "response": _openai_response(response_id, "in_progress", ())},
+ {"type": "response.output_item.added", "output_index": 0, "item": dict(item)},
+ {"type": "response.output_item.done", "output_index": 0, "item": dict(done_item)},
+ {"type": "response.completed", "response": _openai_response(response_id, "completed", (done_item,))},
+ )
+ return _sse(tuple({**event, "sequence_number": number} for number, event in enumerate(events)))
+
+
+def _openai_tool_round() -> bytes:
+ call: Final = {"type": "function_call", "id": "fc_1", "call_id": "call_weather", "name": "get_weather"}
+ return _openai_round(
+ "resp_tool_round",
+ {**call, "arguments": "", "status": "in_progress"},
+ {**call, "arguments": json.dumps(WEATHER_ARGUMENTS), "status": "completed"},
+ )
+
+
+def _openai_answer_round() -> bytes:
+ message: Final = {"type": "message", "id": "msg_1", "role": "assistant"}
+ return _openai_round(
+ "resp_answer_round",
+ {**message, "status": "in_progress", "content": []},
+ {**message, "status": "completed", "content": [{"type": "output_text", "text": WEATHER_ANSWER, "annotations": []}]},
+ )
+
+
+def _anthropic_round(message_id: str, block: Mapping[str, object], delta: Mapping[str, object], stop: str) -> bytes:
+ return _sse(
+ (
+ {
+ "type": "message_start",
+ "message": {
+ "id": message_id,
+ "type": "message",
+ "role": "assistant",
+ "model": "claude-haiku-4-5",
+ "content": [],
+ "stop_reason": None,
+ "usage": {"input_tokens": 5, "output_tokens": 1},
+ },
+ },
+ {"type": "content_block_start", "index": 0, "content_block": dict(block)},
+ {"type": "content_block_delta", "index": 0, "delta": dict(delta)},
+ {"type": "content_block_stop", "index": 0},
+ {"type": "message_delta", "delta": {"stop_reason": stop}, "usage": {"output_tokens": 5}},
+ {"type": "message_stop"},
+ )
+ )
+
+
+def _anthropic_tool_round() -> bytes:
+ return _anthropic_round(
+ "msg_tool_round",
+ {"type": "tool_use", "id": "call_weather", "name": "get_weather", "input": {}},
+ {"type": "input_json_delta", "partial_json": json.dumps(WEATHER_ARGUMENTS)},
+ "tool_use",
+ )
+
+
+def _anthropic_answer_round() -> bytes:
+ return _anthropic_round(
+ "msg_answer_round",
+ {"type": "text", "text": ""},
+ {"type": "text_delta", "text": WEATHER_ANSWER},
+ "end_turn",
+ )
+
+
+SCRIPTED_PROVIDERS: Final = MappingProxyType(
+ {
+ "openai": ("openai/gpt-4o-mini", "https://api.openai.com/v1/responses", _openai_tool_round, _openai_answer_round),
+ "anthropic": (
+ "anthropic/claude-haiku-4-5",
+ "https://api.anthropic.com/v1/messages",
+ _anthropic_tool_round,
+ _anthropic_answer_round,
+ ),
+ }
+)
+
+
+def _event_type(event: object) -> str:
+ event_type: Final = getattr(event, "type", "")
+ return str(getattr(event_type, "value", event_type))
+
+
+def _first_index(events: Sequence[object], event_type: str) -> int:
+ return next(index for index, event in enumerate(events) if _event_type(event) == event_type)
+
+
+async def _scripted_mcp_stream(
+ model: str, upstream_url: str, rounds: Sequence[bytes]
+) -> tuple[tuple[object, ...], respx.Route, AsyncMock, AsyncMock]:
+ upstream: Final = respx.post(upstream_url).mock(
+ side_effect=[httpx.Response(200, content=body, headers=SSE_HEADERS) for body in rounds]
+ )
+ with (
+ patch.object(LiteLLM_Proxy_MCP_Handler, "_get_mcp_tools_from_manager", new_callable=AsyncMock) as fetch,
+ patch.object(LiteLLM_Proxy_MCP_Handler, "execute_tool_calls", new_callable=AsyncMock) as execute,
+ ):
+ fetch.return_value = ([WEATHER_TOOL], ["litellm_proxy"])
+ execute.return_value = [{"tool_call_id": "call_weather", "result": WEATHER_RESULT}]
+ response: Final = await litellm.aresponses(
+ model=model,
+ api_key="sk-scripted",
+ tools=[cast(Any, {"type": "mcp", "server_url": "litellm_proxy", "require_approval": "never"})],
+ tool_choice="required",
+ input=[{"role": "user", "type": "message", "content": "What's the weather in San Francisco?"}],
+ stream=True,
+ )
+ events: Final = tuple([event async for event in response])
+ return events, upstream, fetch, execute
+
+
[email protected]("provider", tuple(SCRIPTED_PROVIDERS))
+async def test_streaming_responses_api_with_mcp_tools(
+ provider: str, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ model, upstream_url, tool_round, answer_round = SCRIPTED_PROVIDERS[provider]
+
+ with caplog.at_level(logging.ERROR):
+ events, upstream, fetch, execute = await _scripted_mcp_stream(
+ model, upstream_url, (tool_round(), answer_round())
+ )
+
+ assert fetch.await_count == 1
+ executed: Final = execute.await_args.kwargs["tool_calls"]
+ assert [(call.name, json.loads(call.arguments)) for call in executed] == [("get_weather", WEATHER_ARGUMENTS)]
+ assert upstream.call_count == 2
+ first_body: Final = json.loads(upstream.calls[0].request.content)
+ follow_up: Final = json.dumps(json.loads(upstream.calls[1].request.content))
+ assert "get_weather" in json.dumps(first_body["tools"])
+ assert WEATHER_RESULT in follow_up and "call_weather" in follow_up
+ event_types: Final = [_event_type(event) for event in events]
+ assert event_types.index("response.mcp_list_tools.completed") < event_types.index("response.mcp_call.completed")
+ assert event_types[-1] == "response.completed"
+ assert WEATHER_ANSWER in json.dumps(events[-1].response.model_dump(mode="json"))
+ assert not [record.getMessage() for record in caplog.records if record.levelno >= logging.ERROR]
+
+
+async def test_streaming_mcp_event_order_and_response_id_consistency(
+ monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture
+) -> None:
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+ model, upstream_url, tool_round, answer_round = SCRIPTED_PROVIDERS["openai"]
+
+ with caplog.at_level(logging.ERROR):
+ events, _, _, _ = await _scripted_mcp_stream(model, upstream_url, (tool_round(), answer_round()))
+
+ created: Final = _first_index(events, "response.created")
+ in_progress: Final = _first_index(events, "response.in_progress")
+ output_item_added: Final = _first_index(events, "response.output_item.added")
+ mcp_list_in_progress: Final = _first_index(events, "response.mcp_list_tools.in_progress")
+ completed: Final = _first_index(events, "response.completed")
+ assert created < in_progress < output_item_added < mcp_list_in_progress < completed
+ lifecycle_ids: Final = [
+ event.response.id
+ for event in events
+ if _event_type(event) in ("response.created", "response.in_progress", "response.completed")
+ ]
+ assert len(lifecycle_ids) == 3
+ assert lifecycle_ids[0] == lifecycle_ids[1]
+ assert lifecycle_ids[2] != lifecycle_ids[0]
+ assert not [record.getMessage() for record in caplog.records if record.levelno >= logging.ERROR]
diff --git a/tests/unit/test_assert_ci_coverage.py b/tests/unit/test_assert_ci_coverage.py
index 443adf86d9a..c0e5339c925 100644
--- a/tests/unit/test_assert_ci_coverage.py
+++ b/tests/unit/test_assert_ci_coverage.py
@@ -123,11 +123,7 @@ def test_every_circleci_postgres_suite_is_credited_on_the_repo_as_it_stands() ->
for job in circle["workflows"]["integration"]["jobs"]
if isinstance(job, dict) and "postgres_suite" in job
)
- assert paths == (
- "tests/proxy_security_tests",
- "tests/proxy_migration_tests",
- "tests/integration/database/test_roi_observed.py",
- )
+ assert paths == ("tests/integration/database/test_roi_observed.py",)
assert set(paths) <= coverage._invoked_test_tokens(coverage._all_scalars())
diff --git a/tests/proxy_migration_tests/test_migration_ci.py b/tests/unit/test_circleci_run_migration_tests.py
similarity index 100%
rename from tests/proxy_migration_tests/test_migration_ci.py
rename to tests/unit/test_circleci_run_migration_tests.py