spaceforge / backend /tests /test_api.py
2Btainment's picture
feat(ui): labels/ordering/platform hints for Linux AppImage, Arch PKGBUILD, MCP; API tests; README
d6faa34
Raw History Blame Contribute Delete
7.64 kB
"""API tests — uses httpx ASGITransport against FastAPI app."""
from __future__ import annotations
import io
import zipfile
from pathlib import Path
from unittest.mock import AsyncMock, patch
import pytest
from httpx import ASGITransport, AsyncClient
from backend.app.main import app
from backend.app.config import MAX_DOWNLOAD_BYTES
from backend.app.services.builds import build_manager
SAMPLE_INFO = {
"repo_id": "gradio/hello_world",
"owner": "gradio",
"name": "hello_world",
"title": "Hello World",
"emoji": "👋",
"short_description": "demo",
"sdk": "gradio",
"sdk_version": "4.0.0",
"hardware": "cpu-basic",
"runtime_stage": "RUNNING",
"private": False,
"likes": 1,
"tags": [],
"needs_gpu": False,
"has_external_apis": False,
"space_url": "https://huggingface.co/spaces/gradio/hello_world",
"embed_url": "https://gradio-hello-world.hf.space",
"app_port": None,
"raw_card": {},
}
@pytest.fixture
async def client():
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as ac:
yield ac
@pytest.mark.asyncio
async def test_health(client):
r = await client.get("/api/health")
assert r.status_code == 200
assert r.json()["status"] == "ok"
@pytest.mark.asyncio
async def test_analyze_invalid_url(client):
r = await client.post("/api/analyze", json={"url": "https://evil.example/x"})
assert r.status_code == 400
assert r.json()["detail"]["code"] == "invalid_url"
@pytest.mark.asyncio
async def test_analyze_missing_space(client):
async def boom(*a, **k):
from backend.app.providers.huggingface import SpaceProviderError
raise SpaceProviderError("Space not found: no/such", "not_found", 404)
with patch("backend.app.api.routes.fetch_space_info", boom):
r = await client.post("/api/analyze", json={"url": "no/such"})
assert r.status_code == 404
@pytest.mark.asyncio
async def test_analyze_public_gradio(client):
with patch("backend.app.api.routes.fetch_space_info", AsyncMock(return_value=SAMPLE_INFO)):
r = await client.post("/api/analyze", json={"url": "gradio/hello_world"})
assert r.status_code == 200
body = r.json()
assert body["space"]["sdk"] == "gradio"
assert any(t["id"] == "html_widget" for t in body["compatibility"]["targets"])
@pytest.mark.asyncio
async def test_analyze_static_sdk(client):
info = {**SAMPLE_INFO, "sdk": "static", "repo_id": "user/static-demo", "name": "static-demo"}
with patch("backend.app.api.routes.fetch_space_info", AsyncMock(return_value=info)):
r = await client.post("/api/analyze", json={"url": "user/static-demo"})
assert r.status_code == 200
assert r.json()["compatibility"]["local_offline_full"] is True
@pytest.mark.asyncio
async def test_analyze_gpu(client):
info = {**SAMPLE_INFO, "needs_gpu": True, "hardware": "t4-small"}
with patch("backend.app.api.routes.fetch_space_info", AsyncMock(return_value=info)):
r = await client.post("/api/analyze", json={"url": "gradio/hello_world"})
assert any("GPU" in w for w in r.json()["compatibility"]["warnings"])
@pytest.mark.asyncio
async def test_analyze_external_apis_flag(client):
info = {**SAMPLE_INFO, "has_external_apis": True, "tags": ["inference"]}
with patch("backend.app.api.routes.fetch_space_info", AsyncMock(return_value=info)):
r = await client.post("/api/analyze", json={"url": "gradio/hello_world"})
assert r.json()["space"]["has_external_apis"] is True
@pytest.mark.asyncio
async def test_analyze_unknown_sdk(client):
info = {**SAMPLE_INFO, "sdk": "unknown"}
with patch("backend.app.api.routes.fetch_space_info", AsyncMock(return_value=info)):
r = await client.post("/api/analyze", json={"url": "gradio/hello_world"})
assert any("Unknown SDK" in w for w in r.json()["compatibility"]["warnings"])
@pytest.mark.asyncio
async def test_build_widget_firefox_pwa(client):
with patch("backend.app.api.routes.fetch_space_info", AsyncMock(return_value=SAMPLE_INFO)):
r = await client.post(
"/api/build",
json={"url": "gradio/hello_world", "targets": ["html_widget", "pwa", "firefox_ext"]},
)
assert r.status_code == 200
bid = r.json()["build_id"]
# poll
for _ in range(50):
st = await client.get(f"/api/build/{bid}")
body = st.json()
if body["status"] in ("done", "error"):
break
import asyncio
await asyncio.sleep(0.1)
assert body["status"] == "done"
assert "html_widget" in body["artifacts"]
assert "pwa" in body["artifacts"]
assert "firefox_ext" in body["artifacts"]
# download
dl = await client.get(f"/api/build/{bid}/download", params={"target": "html_widget"})
assert dl.status_code == 200
assert zipfile.is_zipfile(io.BytesIO(dl.content))
logs = await client.get(f"/api/build/{bid}/logs")
assert "html_widget" in logs.text
# delete
d = await client.delete(f"/api/build/{bid}")
assert d.status_code == 200
@pytest.mark.asyncio
async def test_large_download_rejected(client, tmp_path, monkeypatch):
"""Simulate oversized artifact → 413."""
with patch("backend.app.api.routes.fetch_space_info", AsyncMock(return_value=SAMPLE_INFO)):
r = await client.post("/api/build", json={"url": "gradio/hello_world", "targets": ["html_widget"]})
bid = r.json()["build_id"]
import asyncio
for _ in range(50):
st = (await client.get(f"/api/build/{bid}")).json()
if st["status"] in ("done", "error"):
break
await asyncio.sleep(0.1)
job = build_manager.get(bid)
assert job and job.work_dir
# inflate reported file
art = job.artifacts["html_widget"]
path = job.work_dir / art["path_name"]
path.write_bytes(b"x" * 1024)
monkeypatch.setattr("backend.app.api.routes.MAX_DOWNLOAD_BYTES", 100)
dl = await client.get(f"/api/build/{bid}/download", params={"target": "html_widget"})
assert dl.status_code == 413
@pytest.mark.asyncio
async def test_targets_include_new_desktop_and_mcp(client):
r = await client.get("/api/targets")
ids = [t["id"] for t in r.json()["targets"]]
for tid in ("linux_appimage", "arch_pkgbuild", "mcp", "windows_portable"):
assert tid in ids
by = {t["id"]: t for t in r.json()["targets"]}
assert by["windows_portable"]["stub"] is True and by["windows_portable"]["available"] is False
assert by["mcp"]["available"] is True and by["mcp"]["stub"] is False
assert by["arch_pkgbuild"]["label"] == "Arch Linux (PKGBUILD)"
@pytest.mark.asyncio
async def test_build_mcp_docker_space(client):
info = dict(SAMPLE_INFO, repo_id="2Btainment/repospace", owner="2Btainment", name="repospace",
sdk="docker", embed_url="https://2btainment-repospace.hf.space")
with patch("backend.app.api.routes.fetch_space_info", AsyncMock(return_value=info)):
r = await client.post("/api/build", json={"url": "2Btainment/repospace", "targets": ["mcp"]})
bid = r.json()["build_id"]
import asyncio
for _ in range(50):
body = (await client.get(f"/api/build/{bid}")).json()
if body["status"] in ("done", "error"):
break
await asyncio.sleep(0.1)
assert body["status"] == "done", body
art = body["artifacts"]["mcp"]
assert art["filename"] == "repospace-mcp.zip" and art["binary_included"] is False
dl = await client.get(f"/api/build/{bid}/download", params={"target": "mcp"})
assert zipfile.is_zipfile(io.BytesIO(dl.content))