Files
Atrium/backend/tests/test_model_server_list_unit.py
T
tobayahandClaude Opus 5.5 18623f0fee fix(providers): poprawki po recenzji
- dodanie dostawcy z setkami modeli (OpenRouter) nie konczy sie 422 (limit 100 -> 1000)
- opcjonalna lista LM Studio (302/HTML/401) nie wywraca discover/refresh
- nieoczekiwany ksztalt JSON od cudzego serwera = 422 provider_unreachable, nie 500
- wklejony adres chmurowy (api.anthropic.com) pytany po swojemu
- ten sam model u dwoch dostawcow pokazany raz, pod tym, ktory odpowie
- testy: jeden limit czasu na cala wymiane, przekierowanie bez drugiego zadania;
  piec mutacji, kazda zlapana

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016uwxqJbh3fPYdfdLG3MU6f
2026-11-06 16:06:04 +01:00

184 lines
7.3 KiB
Python

"""`model_server.list_models` on a mocked transport: what counts as a chat model, the outbound limits
(no redirects, 2 MB), the refusal codes, and that the key never appears in an error."""
from __future__ import annotations
import asyncio
import json
import httpx
import pytest
from app.errors import ValidationError
from app.integrations import model_server
KEY = "sk-secret-value-123"
def _resp(status, json_=None, content=b"", headers=None):
"""A STREAMED response, as the network gives one (`content=` would arrive already read)."""
body = json.dumps(json_).encode() if json_ is not None else content
return httpx.Response(status, headers=headers, stream=httpx.ByteStream(body))
def _run(handler, base="http://gpu.example:8000/v1", key=KEY, vendor=None):
return asyncio.run(model_server.list_models(base, key, vendor, transport=httpx.MockTransport(handler)))
def _refused(handler, code, **kw):
with pytest.raises(ValidationError) as exc:
_run(handler, **kw)
assert exc.value.extra["code"] == code
assert KEY not in exc.value.detail and KEY not in json.dumps(exc.value.extra)
return exc.value
def test_vllm_max_model_len_becomes_the_context_window_and_the_key_is_a_bearer():
seen = []
def handler(req):
seen.append(req)
if req.url.path == "/v1/models":
return _resp(200, json_={"data": [{"id": "qwen/qwen3.5-9b", "max_model_len": 32768},
{"id": "bielik-11b"}]})
return _resp(404)
assert _run(handler) == [{"id": "qwen/qwen3.5-9b", "dialect": "openai", "context_window": 32768},
{"id": "bielik-11b", "dialect": "openai"}]
assert seen[0].headers["authorization"] == f"Bearer {KEY}"
def test_lm_studio_drops_embeddings_and_keeps_models_not_loaded():
def handler(req):
if req.url.path == "/v1/models":
return _resp(200, json_={"data": [{"id": "qwen3"}, {"id": "nomic-text-v1"}, {"id": "gemma"}]})
return _resp(200, json_={"data": [
{"id": "qwen3", "type": "llm", "state": "loaded"},
{"id": "nomic-text-v1", "type": "embeddings", "state": "not-loaded"},
{"id": "gemma", "type": "vlm", "state": "not-loaded"}]})
assert [m["id"] for m in _run(handler, base="http://localhost:1234", key=None)] == ["qwen3", "gemma"]
def test_non_chat_ids_are_dropped_by_pattern():
def handler(req):
return _resp(200, json_={"data": [{"id": "gpt-5"}, {"id": "text-embedding-3-large"},
{"id": "whisper-1"}, {"id": "gpt-image-1"}]})
assert [m["id"] for m in _run(handler, vendor="openai")] == ["gpt-5"]
def test_a_redirect_is_refused():
_refused(lambda req: _resp(302, headers={"Location": "http://169.254.169.254/"}),
"provider_unreachable")
def test_an_answer_over_2_mb_is_cut_and_refused():
big = b'{"data": [' + b" " * (model_server.LIST_MAX_BYTES + 1) + b"]}"
_refused(lambda req: _resp(200, content=big), "provider_unreachable")
def test_401_is_a_refused_key():
_refused(lambda req: _resp(401, json_={"error": f"bad key {KEY}"}), "provider_key_refused")
def test_no_answer_is_unreachable():
def handler(req):
raise httpx.ConnectError(f"cannot connect with {KEY}")
_refused(handler, "provider_unreachable")
def test_an_empty_list_after_the_filter_is_no_models():
_refused(lambda req: _resp(200, json_={"data": [{"id": "text-embedding-3-small"}]}),
"provider_no_models", vendor="openai")
def test_a_compressed_answer_is_refused_and_identity_is_asked_for():
seen = []
def handler(req):
seen.append(req.headers["accept-encoding"])
return _resp(200, headers={"Content-Encoding": "gzip"}, content=b"\x1f\x8b")
_refused(handler, "provider_unreachable")
assert seen == ["identity"]
ANTHROPIC = "https://api.anthropic.com/v1"
def _anthropic(handler):
return _run(handler, base=ANTHROPIC, vendor="anthropic")
def test_anthropic_keeps_active_models_and_sends_its_own_headers():
seen = []
def handler(req):
seen.append(req)
return _resp(200, json_={"data": [
{"id": "claude-opus-5-5", "lifecycle": "active", "max_input_tokens": 1000000},
{"id": "claude-old-3", "lifecycle": "deprecated", "max_input_tokens": 200000},
{"id": "claude-haiku-5-5", "lifecycle": "active", "max_input_tokens": 0}]})
assert _anthropic(handler) == [
{"id": "claude-opus-5-5", "dialect": "openai", "context_window": 1000000},
{"id": "claude-haiku-5-5", "dialect": "openai"}]
req, = seen
assert req.url.path == "/v1/models" and req.url.params["limit"] == "1000"
assert req.headers["x-api-key"] == KEY
assert req.headers["anthropic-version"] == model_server.ANTHROPIC_VERSION
assert "authorization" not in req.headers
def test_anthropic_refusals_never_carry_the_key():
_refused(lambda req: _resp(401, json_={"error": f"bad key {KEY}"}), "provider_key_refused",
base=ANTHROPIC, vendor="anthropic")
_refused(lambda req: _resp(302, headers={"Location": "http://169.254.169.254/"}),
"provider_unreachable", base=ANTHROPIC, vendor="anthropic")
_refused(lambda req: _resp(200, json_={"data": [{"id": "claude-old-3", "lifecycle": "deprecated"}]}),
"provider_no_models", base=ANTHROPIC, vendor="anthropic")
def test_a_redirect_is_not_followed_one_request_and_no_second_host():
seen = []
def handler(req):
seen.append(str(req.url))
return _resp(302, headers={"Location": "http://169.254.169.254/latest/meta-data/"})
_refused(handler, "provider_unreachable")
assert len(seen) == 1 and "169.254" not in seen[0]
def test_one_deadline_covers_the_whole_exchange_not_each_read(monkeypatch):
"""A body trickled slower than the deadline in total, but each chunk fast enough for a per-read
timeout, must still end at the deadline."""
import time
class Trickle(httpx.AsyncByteStream):
async def __aiter__(self):
yield b'{"data": ['
for _ in range(50):
await asyncio.sleep(0.05)
yield b" "
yield b"]}"
monkeypatch.setattr(model_server, "LIST_DEADLINE", 0.5)
started = time.monotonic()
_refused(lambda req: httpx.Response(200, stream=Trickle()), "provider_unreachable")
assert time.monotonic() - started < 2
@pytest.mark.parametrize("answer", [
lambda: _resp(302, headers={"Location": "/login"}),
lambda: _resp(200, content=b"<html>login</html>"),
lambda: _resp(401),
], ids=["redirect", "html", "401"])
def test_a_broken_optional_lm_studio_listing_does_not_sink_the_discovery(answer):
def handler(req):
if req.url.path == "/v1/models":
return _resp(200, json_={"data": [{"id": "qwen3"}]})
return answer()
assert [m["id"] for m in _run(handler, key=None)] == ["qwen3"]
@pytest.mark.parametrize("body", [b"[]", b"null", b'"x"', b'{"data": null}', b'{"data": "x"}',
b"[" * 100_000 + b"]" * 100_000],
ids=["list", "null", "string", "data-null", "data-string", "deep-nesting"])
@pytest.mark.parametrize("vendor", [None, "anthropic"])
def test_an_unexpected_json_shape_is_a_422_not_a_500(body, vendor):
_refused(lambda req: _resp(200, content=body), "provider_unreachable", vendor=vendor)