File size: 7,636 Bytes
3806142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6faa34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
"""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))