Spaces:
Sleeping
Sleeping
Adarsh Kumar commited on
Delete tests/test_app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242from __future__ import annotations
import json
import httpximport pytest
import app as relay
class MockSSEStream(httpx.AsyncByteStream): def __init__(self, content: bytes): self.content = content
async def __aiter__(self): # Two chunks also exercise boundary-transparent forwarding. middle = len(self.content) // 2 yield self.content[:middle] yield self.content[middle:]
@pytest.fixturedef anyio_backend(): return "asyncio"
@pytest.fixture(autouse=True)def reset_state(monkeypatch): relay.model_cache["value"] = None relay.model_cache["stored_at"] = 0.0 relay.rate_buckets.clear() monkeypatch.setattr(relay, "PUBLIC_ACCESS", True) monkeypatch.setattr(relay, "RATE_LIMIT_PER_MINUTE", 0) monkeypatch.setattr(relay, "ALLOWED_MODELS", set())
@pytest.fixturedef mock_upstream(monkeypatch): seen: list[dict] = []
def handler(request: httpx.Request) -> httpx.Response: if request.url.path.endswith("/models"): return httpx.Response( 200, json={ "object": "list", "data": [ {"id": "coding-model", "object": "model"}, {"id": "vision-model", "object": "model"}, ], }, headers={"x-ratelimit-remaining": "11"}, ) if request.url.path.endswith("/chat/completions"): payload = json.loads(request.content) seen.append(payload) if payload.get("stream"): body = ( 'data: {"id":"one","object":"chat.completion.chunk",' '"choices":[{"index":0,"delta":{"content":"OK"},' '"finish_reason":null}]}\n\n' 'data: {"id":"one","object":"chat.completion.chunk",' '"choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n' "data: [DONE]\n\n" ).encode() return httpx.Response( 200, stream=MockSSEStream(body), headers={"content-type": "text/event-stream"}, ) return httpx.Response( 200, json={ "id": "chatcmpl-test", "object": "chat.completion", "model": payload["model"], "choices": [ { "index": 0, "message": { "role": "assistant", "content": None, "tool_calls": [ { "id": "call_1", "type": "function", "function": { "name": "read_file", "arguments": '{"path":"a.py"}', }, } ], }, "finish_reason": "tool_calls", } ], "usage": {"total_tokens": 12}, }, ) return httpx.Response(404, json={"error": {"message": "not found"}})
client = httpx.AsyncClient( transport=httpx.MockTransport(handler), base_url="https://mock.example/v1" ) monkeypatch.setattr(relay, "upstream_client", client) monkeypatch.setattr(relay, "UPSTREAM_BASE_URL", "https://mock.example/v1") return seen, client
@pytest.mark.anyioasync def test_health_and_home(mock_upstream): _, upstream = mock_upstream async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: health = await client.get("/healthz") assert health.status_code == 200 assert health.json()["ok"] is True home = await client.get("/") assert home.status_code == 200 assert "ZCode provider" in home.text await upstream.aclose()
@pytest.mark.anyioasync def test_dynamic_models_and_cache(mock_upstream): _, upstream = mock_upstream async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: first = await client.get("/v1/models") second = await client.get("/v1/models") assert first.status_code == 200 assert [m["id"] for m in first.json()["data"]] == [ "coding-model", "vision-model", ] assert first.headers["x-model-cache"] == "miss" assert second.headers["x-model-cache"] == "hit" await upstream.aclose()
@pytest.mark.anyioasync def test_tools_and_multimodal_body_are_preserved(mock_upstream): seen, upstream = mock_upstream payload = { "model": "coding-model", "stream": False, "messages": [ { "role": "user", "content": [ {"type": "text", "text": "Inspect this image and file."}, { "type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}, }, ], } ], "tools": [ { "type": "function", "function": { "name": "read_file", "parameters": {"type": "object"}, }, } ], "tool_choice": "required", "parallel_tool_calls": True, "temperature": 0.2, } async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: response = await client.post("/v1/chat/completions", json=payload) assert response.status_code == 200 message = response.json()["choices"][0]["message"] assert message["tool_calls"][0]["function"]["name"] == "read_file" assert seen == [payload] await upstream.aclose()
@pytest.mark.anyioasync def test_sse_is_passed_through(mock_upstream): _, upstream = mock_upstream payload = { "model": "coding-model", "stream": True, "stream_options": {"include_usage": True}, "messages": [{"role": "user", "content": "hello"}], } async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: async with client.stream("POST", "/v1/chat/completions", json=payload) as response: text = (await response.aread()).decode() assert response.status_code == 200 assert response.headers["content-type"].startswith("text/event-stream") assert '"content":"OK"' in text assert "data: [DONE]" in text await upstream.aclose()
@pytest.mark.anyioasync def test_clean_validation_errors(mock_upstream): _, upstream = mock_upstream async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: bad_json = await client.post( "/v1/chat/completions", content=b"{bad", headers={"content-type": "application/json"}, ) assert bad_json.status_code == 400 assert bad_json.json()["error"]["code"] == "invalid_json" bad_shape = await client.post("/v1/chat/completions", json=[]) assert bad_shape.status_code == 400 missing_model = await client.post( "/v1/chat/completions", json={"messages": []} ) assert missing_model.status_code == 400 await upstream.aclose()
@pytest.mark.anyioasync def test_optional_bearer_auth(mock_upstream, monkeypatch): _, upstream = mock_upstream monkeypatch.setattr(relay, "PUBLIC_ACCESS", False) monkeypatch.setattr(relay, "PROVIDER_API_KEY", "secret-value") async with httpx.AsyncClient( transport=httpx.ASGITransport(app=relay.app), base_url="http://test" ) as client: denied = await client.get("/v1/models") allowed = await client.get( "/v1/models", headers={"authorization": "Bearer secret-value"} ) assert denied.status_code == 401 assert allowed.status_code == 200 await upstream.aclose()tests/test_app.pyDeleted-242