Spaces:
Sleeping

LS / tests /test_app.py
Adarsh Kumar
Upload 20 files
f45a595 verified
Raw History Blame Contribute Delete
13.6 kB
from __future__ import annotations
import json
from collections import deque
from types import SimpleNamespace
import httpx
import pytest
import app as gateway
from upstage_provider import StreamEvent, UpstageStreamError
@pytest.fixture
def anyio_backend():
return "asyncio"
class FakeProvider:
def __init__(self, events=None, error=None, capture=None):
self.events = events or []
self.error = error
self.capture = capture
self.last_response = ""
self.last_reasoning = ""
self.last_sources = []
self.last_usage = None
async def stream(self, **kwargs):
if self.capture is not None:
self.capture.append(kwargs)
if self.error:
raise self.error
content, reasoning = [], []
for event in self.events:
if event.kind == "content":
content.append(event.text)
elif event.kind == "thinking":
reasoning.append(event.text)
elif event.kind == "sources":
self.last_sources = json.loads(event.text).get("sources", [])
yield event
self.last_response = "".join(content)
self.last_reasoning = "".join(reasoning)
self.last_usage = SimpleNamespace(
api_usage={"prompt_tokens": 5, "completion_tokens": 3, "total_tokens": 8}
)
def factory_queue(monkeypatch, providers):
queue = deque(providers)
monkeypatch.setattr(gateway, "provider_factory", lambda: queue.popleft())
return queue
@pytest.fixture(autouse=True)
def reset_config(monkeypatch):
gateway.rate_buckets.clear()
monkeypatch.setattr(gateway, "PUBLIC_ACCESS", True)
monkeypatch.setattr(gateway, "RATE_LIMIT_PER_MINUTE", 0)
monkeypatch.setattr(gateway, "UPSTREAM_RETRIES", 0)
monkeypatch.setattr(gateway, "TOOL_PROTOCOL_RETRIES", 1)
@pytest.fixture
def client():
return httpx.AsyncClient(
transport=httpx.ASGITransport(app=gateway.app), base_url="http://test"
)
@pytest.mark.anyio
async def test_health_home_and_models(client):
health = await client.get("/healthz")
ready = await client.get("/readyz")
home = await client.get("/")
models = await client.get("/v1/models")
one = await client.get("/v1/models/solar-pro3")
assert health.status_code == ready.status_code == home.status_code == 200
assert "Built for ZCode" in home.text
assert [item["id"] for item in models.json()["data"]] == [
"solar-pro3",
"solar-pro2",
"syn-pro",
"upstage/solar-1-mini-chat",
]
assert one.json()["capabilities"]["tools"] is True
await client.aclose()
@pytest.mark.anyio
async def test_nonstream_chat_reasoning_sources_and_usage(client, monkeypatch):
sources = {"sources": [{"title": "A", "url": "https://a.test", "score": 0.9}]}
fake = FakeProvider(
[
StreamEvent("sources", json.dumps(sources)),
StreamEvent("thinking", "hmm"),
StreamEvent("content", "O"),
StreamEvent("content", "K"),
StreamEvent("done", ""),
]
)
factory_queue(monkeypatch, [fake])
response = await client.post(
"/v1/chat/completions",
json={
"model": "solar-pro3",
"messages": [{"role": "user", "content": "hello"}],
"search": True,
"reasoning_effort": "high",
},
)
assert response.status_code == 200
body = response.json()
assert body["choices"][0]["message"]["content"] == "OK"
assert body["choices"][0]["message"]["reasoning_content"] == "hmm"
assert body["sources"][0]["url"] == "https://a.test"
assert body["usage"]["total_tokens"] == 8
await client.aclose()
@pytest.mark.anyio
async def test_realtime_sse_and_usage(client, monkeypatch):
fake = FakeProvider(
[
StreamEvent("thinking", "plan"),
StreamEvent("content", "Hel"),
StreamEvent("content", "lo"),
StreamEvent("done", ""),
]
)
factory_queue(monkeypatch, [fake])
async with client.stream(
"POST",
"/v1/chat/completions",
json={
"model": "solar-pro3",
"stream": True,
"stream_options": {"include_usage": True},
"messages": [{"role": "user", "content": "hello"}],
},
) as response:
text = (await response.aread()).decode()
assert response.status_code == 200
assert response.headers["content-type"].startswith("text/event-stream")
assert '"reasoning_content":"plan"' in text
assert '"content":"Hel"' in text and '"content":"lo"' in text
assert '"choices":[],"usage"' in text
assert text.rstrip().endswith("data: [DONE]")
await client.aclose()
def tool_payload(stream=False, choice="required"):
return {
"model": "solar-pro3",
"stream": stream,
"stream_options": {"include_usage": True},
"messages": [{"role": "user", "content": "Read app.py"}],
"tools": [
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read a file",
"parameters": {
"type": "object",
"properties": {"path": {"type": "string"}},
"required": ["path"],
"additionalProperties": False,
},
},
}
],
"tool_choice": choice,
}
TOOL_WIRE = (
'<|tool_call:begin|>q123q<|tool_call:name|>read_file'
'<|tool_call:args|>{"path":"app.py"}<|tool_call:end|>'
)
@pytest.mark.anyio
async def test_nonstream_validated_tool_call(client, monkeypatch):
capture = []
fake = FakeProvider([StreamEvent("content", TOOL_WIRE), StreamEvent("done", "")], capture=capture)
factory_queue(monkeypatch, [fake])
response = await client.post("/v1/chat/completions", json=tool_payload())
assert response.status_code == 200
choice = response.json()["choices"][0]
assert choice["finish_reason"] == "tool_calls"
call = choice["message"]["tool_calls"][0]
assert call["function"]["name"] == "read_file"
assert json.loads(call["function"]["arguments"]) == {"path": "app.py"}
assert "TOOL GATEWAY PROTOCOL" in capture[0]["messages"][0]["content"]
await client.aclose()
@pytest.mark.anyio
async def test_streamed_tool_call_is_openai_sse(client, monkeypatch):
fake = FakeProvider(
[StreamEvent("thinking", "need file"), StreamEvent("content", TOOL_WIRE), StreamEvent("done", "")]
)
factory_queue(monkeypatch, [fake])
response = await client.post("/v1/chat/completions", json=tool_payload(stream=True))
text = response.text
assert response.status_code == 200
assert '"tool_calls":[{"id":"call_' in text
assert '"finish_reason":"tool_calls"' in text
assert '"reasoning_content":"need file"' in text
assert TOOL_WIRE not in text
assert "data: [DONE]" in text
await client.aclose()
@pytest.mark.anyio
async def test_required_tool_output_retries_once(client, monkeypatch):
first = FakeProvider([StreamEvent("content", "I forgot the tool"), StreamEvent("done", "")])
second_capture = []
second = FakeProvider(
[StreamEvent("content", TOOL_WIRE), StreamEvent("done", "")],
capture=second_capture,
)
queue = factory_queue(monkeypatch, [first, second])
response = await client.post("/v1/chat/completions", json=tool_payload())
assert response.status_code == 200 and not queue
retry_messages = second_capture[0]["messages"]
assert "VALIDATION ERROR" in retry_messages[-1]["content"]
assert response.json()["usage"]["total_tokens"] == 16
await client.aclose()
@pytest.mark.anyio
async def test_auto_tool_choice_allows_plain_answer(client, monkeypatch):
fake = FakeProvider([StreamEvent("content", "No tool needed."), StreamEvent("done", "")])
factory_queue(monkeypatch, [fake])
response = await client.post("/v1/chat/completions", json=tool_payload(choice="auto"))
assert response.status_code == 200
choice = response.json()["choices"][0]
assert choice["finish_reason"] == "stop"
assert choice["message"]["content"] == "No tool needed."
await client.aclose()
@pytest.mark.anyio
async def test_auto_retries_narrated_tool_intent(client, monkeypatch):
first = FakeProvider(
[
StreamEvent(
"content",
"We need to write the file using the read_file tool. I will call it now.",
),
StreamEvent("done", ""),
]
)
second = FakeProvider([StreamEvent("content", TOOL_WIRE), StreamEvent("done", "")])
queue = factory_queue(monkeypatch, [first, second])
response = await client.post("/v1/chat/completions", json=tool_payload(choice="auto"))
assert response.status_code == 200 and not queue
assert response.json()["choices"][0]["finish_reason"] == "tool_calls"
await client.aclose()
@pytest.mark.anyio
async def test_tool_result_round_trip_is_normalized(client, monkeypatch):
capture = []
fake = FakeProvider([StreamEvent("content", "The file says OK."), StreamEvent("done", "")], capture=capture)
factory_queue(monkeypatch, [fake])
payload = tool_payload(choice="auto")
payload["messages"] = [
{"role": "user", "content": "Read app.py"},
{
"role": "assistant",
"content": None,
"tool_calls": [
{
"id": "call_previous",
"type": "function",
"function": {"name": "read_file", "arguments": '{"path":"app.py"}'},
}
],
},
{"role": "tool", "tool_call_id": "call_previous", "content": "OK"},
]
response = await client.post("/v1/chat/completions", json=payload)
assert response.status_code == 200
sent = capture[0]["messages"]
assert "<|tool_call:name|>read_file" in sent[-2]["content"]
assert "TOOL RESULT" in sent[-1]["content"]
assert "function: read_file" in sent[-1]["content"]
await client.aclose()
@pytest.mark.anyio
async def test_upstream_prefetch_error_stays_json(client, monkeypatch):
monkeypatch.setattr(gateway, "UPSTREAM_RETRIES", 0)
factory_queue(monkeypatch, [FakeProvider(error=UpstageStreamError("boom"))])
response = await client.post(
"/v1/chat/completions",
json={
"model": "solar-pro3",
"stream": True,
"messages": [{"role": "user", "content": "hi"}],
},
)
assert response.status_code == 502
assert response.headers["content-type"].startswith("application/json")
assert response.json()["error"]["code"] == "upstream_error"
await client.aclose()
@pytest.mark.anyio
async def test_transient_generation_retry(client, monkeypatch):
monkeypatch.setattr(gateway, "UPSTREAM_RETRIES", 1)
bad = FakeProvider(error=UpstageStreamError("temporary"))
good = FakeProvider([StreamEvent("content", "OK"), StreamEvent("done", "")])
queue = factory_queue(monkeypatch, [bad, good])
response = await client.post(
"/v1/chat/completions",
json={"model": "solar-pro3", "messages": [{"role": "user", "content": "hi"}]},
)
assert response.status_code == 200 and not queue
assert response.json()["choices"][0]["message"]["content"] == "OK"
await client.aclose()
@pytest.mark.anyio
@pytest.mark.parametrize(
"payload,code,status",
[
({}, "missing_model", 400),
({"model": "nope", "messages": [{"role": "user", "content": "x"}]}, "model_not_found", 404),
({"model": "solar-pro3", "messages": []}, "invalid_messages", 400),
({"model": "solar-pro3", "messages": [{"role": "user", "content": "x"}], "n": 2}, "unsupported_parameter", 400),
({"model": "solar-pro3", "messages": [{"role": "user", "content": "x"}], "max_tokens": 999999}, "context_length_exceeded", 400),
],
)
async def test_clean_validation_errors(client, payload, code, status):
response = await client.post("/v1/chat/completions", json=payload)
assert response.status_code == status
assert response.json()["error"]["code"] == code
await client.aclose()
@pytest.mark.anyio
async def test_invalid_json_and_unsupported_image(client):
bad = await client.post(
"/v1/chat/completions",
content=b"{bad",
headers={"content-type": "application/json"},
)
image = await client.post(
"/v1/chat/completions",
json={
"model": "solar-pro3",
"messages": [
{
"role": "user",
"content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,AA=="}}],
}
],
},
)
assert bad.status_code == 400 and bad.json()["error"]["code"] == "invalid_json"
assert image.status_code == 400
assert image.json()["error"]["code"] == "unsupported_content_type"
await client.aclose()
@pytest.mark.anyio
async def test_optional_auth(client, monkeypatch):
monkeypatch.setattr(gateway, "PUBLIC_ACCESS", False)
monkeypatch.setattr(gateway, "PROVIDER_API_KEY", "secret")
denied = await client.get("/v1/models")
allowed = await client.get("/v1/models", headers={"authorization": "Bearer secret"})
assert denied.status_code == 401
assert allowed.status_code == 200
await client.aclose()