Spaces:
Running on CPU Upgrade

File size: 5,951 Bytes
80340d8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Optional browser check: every request is mocked; no live radio is contacted.

Run: python tests/check_player.py
Requires Playwright and Chromium (or BROWSER_EXECUTABLE).
"""
import json
import os
import shutil
from pathlib import Path
from urllib.parse import urlparse

from playwright.sync_api import sync_playwright

ROOT = Path(__file__).resolve().parents[1]
ARTIFACTS = ROOT / "test-artifacts"
ARTIFACTS.mkdir(exist_ok=True)
(ARTIFACTS / "tmp").mkdir(exist_ok=True)
os.environ["TMPDIR"] = str(ARTIFACTS / "tmp")
SOURCES = json.loads((ROOT / "music_sources.json").read_text())["sources"]
HTML = (ROOT / "static/index.html").read_text()
COVER = '<svg xmlns="http://www.w3.org/2000/svg" width="640" height="640"><rect width="640" height="640" fill="#20182f"/><circle cx="320" cy="320" r="210" fill="#563779"/><circle cx="320" cy="320" r="100" fill="#eab082"/><circle cx="320" cy="320" r="22" fill="#20182f"/></svg>'


def status_for(source):
    return {
        "is_playing": True, "is_loading": False, "now_playing_type": "song",
        "track_count": 52, "current_index": 6, "elapsed": 20,
        "active_listeners": 12, "signed_in_listener_count": 0,
        "mode": "random", "likes_enabled": True, "music_sources": SOURCES,
        "track": {
            "id": source["id"] + ":test", "title": "Neon Afterglow", "duration": 120,
            "tags": ["synth-pop", "community"], "description": "A late-night community track.",
            "lyrics": "A city sings beneath the stars", "audio_url": "https://radio.test/song.wav",
            "thumb_url": "https://radio.test/cover.svg", "source_id": source["id"],
            "source_label": source["label"], "source_space_url": source["space_url"],
        },
    }


def main():
    with sync_playwright() as playwright:
        executable = os.environ.get("BROWSER_EXECUTABLE") or shutil.which("chromium")
        browser = playwright.chromium.launch(executable_path=executable, headless=True,
                                             args=["--no-sandbox", "--disable-dev-shm-usage"])
        for name, width, height in [("desktop", 1440, 1050), ("mobile", 390, 844)]:
            context = browser.new_context(viewport={"width": width, "height": height},
                                          is_mobile=name == "mobile", has_touch=name == "mobile")
            current = status_for(SOURCES[0])
            errors = []

            def route_request(route):
                path = urlparse(route.request.url).path
                if route.request.url == "https://radio.test/":
                    route.fulfill(content_type="text/html", body=HTML)
                elif path == "/api/status":
                    route.fulfill(json=current)
                elif path == "/api/me":
                    route.fulfill(json={"authenticated": False, "user": None})
                elif route.request.resource_type == "image":
                    route.fulfill(content_type="image/svg+xml", body=COVER)
                elif path.startswith("/api/"):
                    route.fulfill(json={"ok": True})
                else:
                    route.fulfill(status=200, body="")

            context.route("**/*", route_request)
            page = context.new_page()
            page.on("pageerror", lambda error: errors.append(str(error)))
            page.goto("https://radio.test/")
            page.wait_for_function("document.getElementById('trackSource').textContent === 'MiniMax Music 3'")
            assert page.locator("#trackSource").get_attribute("href") == SOURCES[0]["space_url"]
            assert page.locator("#sourceLinks a").count() == 2
            assert page.evaluate("document.documentElement.scrollWidth <= window.innerWidth"), name + " horizontal overflow"
            page.screenshot(path=str(ARTIFACTS / f"player-{name}.png"), full_page=True)

            current = status_for(SOURCES[1])
            page.evaluate("value => renderStatus(value, {forceTrackUpdate: true})", current)
            assert page.locator("#trackSource").inner_text() == "ACE-Step"
            assert page.locator("#trackSource").get_attribute("href") == SOURCES[1]["space_url"]
            for flag, label in [("is_jingle", "Station jingle"), ("is_segment", "Editorial segment"), ("is_custom_track", "Studio selection")]:
                current = status_for(SOURCES[0])
                current["track"][flag] = True
                page.evaluate("value => renderStatus(value, {forceTrackUpdate: true})", current)
                assert page.locator("#trackSource").inner_text() == label
                assert page.locator("#trackSource").get_attribute("href") is None
                assert page.locator("#trackSourceCaption").inner_text() == ""

            current = status_for(SOURCES[0])
            current["track"].update(source_label="Future Model", source_space_url="https://huggingface.co/spaces/owner/future")
            current["music_sources"] = SOURCES + [{"id": "future", "label": "Future Model", "space_url": current["track"]["source_space_url"]}]
            page.evaluate("value => renderStatus(value, {forceTrackUpdate: true})", current)
            assert page.locator("#trackSource").inner_text() == "Future Model"
            assert page.locator("#sourceLinks a").count() == 3

            page.evaluate("renderTrackSource({source_label:'<img src=x>', source_space_url:'javascript:alert(1)'})")
            assert page.locator("#trackSource").inner_text() == "<img src=x>"
            assert page.locator("#trackSource img").count() == 0
            assert page.locator("#trackSource").get_attribute("href") is None
            page.evaluate("renderTrackSource(null)")
            assert page.locator("#trackOrigin").is_hidden()
            assert not errors, errors
            print(f"{name}: labels, links, future source, editorial items, empty state and layout OK")
            context.close()
        browser.close()


if __name__ == "__main__":
    main()