litellm/tests/unit/test_model_block_unblock.py
yuneng-jiang f6882246d4
test: move tests/test_litellm root and small trees into tests/unit (#43186)
* ci: run the unit_selection.sh shard files on every event instead of only fork pull requests

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

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

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

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

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

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

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

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

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

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

* test: make the new tests/unit directories packages

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

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

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

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

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

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

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

---------

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

253 lines
8.7 KiB
Python

from unittest.mock import AsyncMock, MagicMock
import pytest
import litellm
from litellm.proxy._types import (
BlockModelRequest,
LitellmUserRoles,
ProxyException,
ReconcileOutcome,
UserAPIKeyAuth,
)
from litellm.types.router import RouterRateLimitError
def _setup_model_block_mocks(monkeypatch, *, updated_blocked: bool):
model_id = "model-123"
existing_row = MagicMock()
existing_row.model_dump.return_value = {
"model_name": "gpt-4o",
"litellm_params": {"model": "openai/gpt-4o"},
"model_info": {"id": model_id},
}
updated_row = MagicMock()
updated_row.model_id = model_id
updated_row.blocked = updated_blocked
model_table = MagicMock()
model_table.find_unique = AsyncMock(return_value=existing_row)
model_table.update = AsyncMock(return_value=updated_row)
mock_prisma_client = MagicMock()
mock_prisma_client.db.litellm_proxymodeltable = model_table
mock_router = MagicMock()
mock_router.get_model_ids.return_value = [model_id]
# No reconcile ran in these tests, so both fields are None and the verdict falls
# back to reading the router live -- which is what the get_model_ids side_effects
# below drive.
mock_clear_cache = AsyncMock(
return_value=ReconcileOutcome(still_desired=None, live_after=None)
)
mock_audit_log = AsyncMock(return_value=None)
monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", mock_prisma_client)
monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", True)
monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", mock_router)
monkeypatch.setattr("litellm.proxy.proxy_server.litellm_proxy_admin_name", "admin")
monkeypatch.setattr(
"litellm.proxy.management_endpoints.model_management_endpoints.clear_cache",
mock_clear_cache,
)
monkeypatch.setattr(
"litellm.proxy.management_endpoints.model_management_endpoints.create_object_audit_log",
mock_audit_log,
)
return model_id, model_table, updated_row, mock_clear_cache, mock_audit_log
def _proxy_admin() -> UserAPIKeyAuth:
return UserAPIKeyAuth(
user_id="admin",
user_role=LitellmUserRoles.PROXY_ADMIN,
api_key="sk-admin",
)
@pytest.mark.asyncio
async def test_model_block_endpoint_sets_blocked_true(monkeypatch):
from litellm.proxy.management_endpoints.model_management_endpoints import (
block_model,
)
model_id, model_table, updated_row, mock_clear_cache, mock_audit_log = (
_setup_model_block_mocks(monkeypatch, updated_blocked=True)
)
result = await block_model(
data=BlockModelRequest(model_id=model_id),
http_request=MagicMock(),
user_api_key_dict=_proxy_admin(),
litellm_changed_by="operator@example.com",
)
assert result == updated_row
model_table.update.assert_awaited_once()
update_kwargs = model_table.update.await_args.kwargs
assert update_kwargs["where"] == {"model_id": model_id}
assert update_kwargs["data"]["blocked"] is True
assert update_kwargs["data"]["updated_by"] == "admin"
assert "updated_at" in update_kwargs["data"]
mock_clear_cache.assert_awaited_once_with()
assert mock_audit_log.call_args.kwargs["action"] == "blocked"
assert (
mock_audit_log.call_args.kwargs["litellm_changed_by"] == "operator@example.com"
)
@pytest.mark.asyncio
async def test_model_unblock_endpoint_sets_blocked_false(monkeypatch):
from litellm.proxy.management_endpoints.model_management_endpoints import (
unblock_model,
)
model_id, model_table, updated_row, mock_clear_cache, mock_audit_log = (
_setup_model_block_mocks(monkeypatch, updated_blocked=False)
)
result = await unblock_model(
data=BlockModelRequest(model_id=model_id),
http_request=MagicMock(),
user_api_key_dict=_proxy_admin(),
litellm_changed_by=None,
)
assert result == updated_row
model_table.update.assert_awaited_once()
assert model_table.update.await_args.kwargs["data"]["blocked"] is False
mock_clear_cache.assert_awaited_once_with()
assert mock_audit_log.call_args.kwargs["action"] == "unblocked"
@pytest.mark.asyncio
async def test_model_block_endpoint_requires_proxy_admin(monkeypatch):
from litellm.proxy.management_endpoints.model_management_endpoints import (
block_model,
)
model_id, model_table, _, _, _ = _setup_model_block_mocks(
monkeypatch, updated_blocked=True
)
non_admin = UserAPIKeyAuth(
user_id="internal-user",
user_role=LitellmUserRoles.INTERNAL_USER,
api_key="sk-user",
)
with pytest.raises(ProxyException) as exc_info:
await block_model(
data=BlockModelRequest(model_id=model_id),
http_request=MagicMock(),
user_api_key_dict=non_admin,
litellm_changed_by=None,
)
assert exc_info.value.code == "403"
assert "Only proxy admins" in exc_info.value.message
model_table.update.assert_not_awaited()
def test_router_returns_no_healthy_deployment_when_model_is_fully_blocked():
router = litellm.Router(
model_list=[
{
"model_name": "gpt-4o",
"litellm_params": {"model": "openai/gpt-4o-0"},
"model_info": {"id": "dep-0", "blocked": True},
},
{
"model_name": "gpt-4o",
"litellm_params": {"model": "openai/gpt-4o-1"},
"model_info": {"id": "dep-1", "blocked": True},
},
]
)
with pytest.raises(RouterRateLimitError) as exc_info:
router.get_available_deployment(model="gpt-4o", request_kwargs={})
assert "No deployments available for selected model" in str(exc_info.value)
assert "Passed model=gpt-4o" in str(exc_info.value)
@pytest.mark.asyncio
async def test_route_request_returns_403_when_model_is_fully_blocked(monkeypatch):
from litellm.proxy.route_llm_request import route_request
router = litellm.Router(
model_list=[
{
"model_name": "gpt-4o",
"litellm_params": {"model": "openai/gpt-4o"},
"model_info": {"id": "dep-0", "blocked": True},
}
]
)
monkeypatch.setattr(
"litellm.proxy.route_llm_request.add_shared_session_to_data",
AsyncMock(return_value=None),
)
with pytest.raises(litellm.PermissionDeniedError) as exc_info:
await route_request(
data={"model": "gpt-4o"},
llm_router=router,
user_model=None,
route_type="acreate_eval",
)
assert exc_info.value.status_code == 403
assert "Model is blocked" in exc_info.value.message
@pytest.mark.asyncio
async def test_model_block_surfaces_wholesale_reload_failure(monkeypatch):
"""The write endpoints owe the caller an error when the pod failed to reload at all;
the DB row is saved but this pod is not serving the change."""
from litellm.proxy._types import ProxyException
from litellm.proxy.management_endpoints.model_management_endpoints import block_model
model_id, model_table, updated_row, mock_clear_cache, mock_audit_log = _setup_model_block_mocks(
monkeypatch, updated_blocked=True
)
wiped_router = MagicMock()
wiped_router.get_model_ids.side_effect = [[model_id], []]
monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", wiped_router)
with pytest.raises(ProxyException, match=model_id):
await block_model(
data=BlockModelRequest(model_id=model_id),
http_request=MagicMock(),
user_api_key_dict=_proxy_admin(),
litellm_changed_by="operator@example.com",
)
assert mock_audit_log.call_args.kwargs["object_id"] == model_id
@pytest.mark.asyncio
async def test_model_block_surfaces_model_dropped_by_reload(monkeypatch):
"""A reload that completes but drops the written model (ignore_invalid_deployments
swallowed its re-add) must not produce an unqualified success."""
from litellm.proxy._types import ProxyException
from litellm.proxy.management_endpoints.model_management_endpoints import block_model
model_id, model_table, updated_row, mock_clear_cache, _ = _setup_model_block_mocks(
monkeypatch, updated_blocked=True
)
dropped_router = MagicMock()
dropped_router.get_model_ids.return_value = []
monkeypatch.setattr("litellm.proxy.proxy_server.llm_router", dropped_router)
with pytest.raises(ProxyException, match=model_id):
await block_model(
data=BlockModelRequest(model_id=model_id),
http_request=MagicMock(),
user_api_key_dict=_proxy_admin(),
litellm_changed_by="operator@example.com",
)