BlueGit

projects-timfalken-com meteors

Files

meteors / test / offline-playwright.py

offline-playwright.py

offline-playwright.py 7.4 KiB Download Raw
1#!/usr/bin/env python3
2"""Smoke test for Offline Strijd (t1119), chain HUD, column warn (t1123)."""
3from __future__ import annotations
4
5import socket
6import subprocess
7import sys
8import time
9from pathlib import Path
10
11from playwright.sync_api import sync_playwright
12
13ROOT = Path("/workspace/meteors")
14OUT = Path("/workspace/meteors-shots")
15OUT.mkdir(parents=True, exist_ok=True)
16CHROME = "/usr/bin/google-chrome"
17CHROME_ARGS = [
18 "--use-gl=angle",
19 "--use-angle=swiftshader",
20 "--no-sandbox",
21 "--disable-dev-shm-usage",
22 "--disable-gpu-sandbox",
23]
24FAILURES = []
25
26
27def free_port():
28 s = socket.socket()
29 s.bind(("127.0.0.1", 0))
30 port = s.getsockname()[1]
31 s.close()
32 return port
33
34
35def check(cond, msg):
36 if not cond:
37 FAILURES.append(msg)
38 print("FAIL", msg)
39 else:
40 print("OK ", msg)
41 return cond
42
43
44def shot(page, name):
45 path = OUT / name
46 page.screenshot(path=str(path), full_page=False)
47 print(f"wrote {path} ({path.stat().st_size} bytes)")
48 return path
49
50
51def start_http(port):
52 proc = subprocess.Popen(
53 ["python3", "-m", "http.server", str(port), "--bind", "127.0.0.1",
54 "--directory", str(ROOT / "build")],
55 stdout=subprocess.DEVNULL,
56 stderr=subprocess.DEVNULL,
57 )
58 time.sleep(0.35)
59 if proc.poll() is not None:
60 raise RuntimeError("http.server failed to start")
61 return proc
62
63
64def open_offline(page, url):
65 page.goto(url, wait_until="domcontentloaded", timeout=15000)
66 page.wait_for_timeout(400)
67 page.locator("#btn-play").click()
68 page.wait_for_selector("#planet-select:not([hidden])", timeout=8000)
69 page.locator("#btn-planet-go").click()
70 page.wait_for_function(
71 "() => app && app.mode === 'playing' && app.offline && app.battle && app.core",
72 timeout=10000,
73 )
74
75
76def run(page, tag):
77 hud = page.evaluate("""() => ({
78 round: document.getElementById('offline-round') && document.getElementById('offline-round').textContent,
79 opponents: document.getElementById('offline-opponents') && document.getElementById('offline-opponents').textContent,
80 skill: document.getElementById('offline-skill') && document.getElementById('offline-skill').textContent,
81 hidden: document.getElementById('offline-hud') && document.getElementById('offline-hud').hidden,
82 bots: app.battle && app.battle.bots.length,
83 schedule: app.battle && app.battle.schedule,
84 jump: app.planet && app.planet.baseJumpHeight,
85 fall: app.planet && app.planet.fallSpeed,
86 clusterFall: app.planet && app.planet.clusterFallSpeed,
87 })""")
88 print("HUD", hud)
89 check(hud["hidden"] is False, f"{tag}: offline HUD visible")
90 check(hud["round"] == "Ronde 1", f"{tag}: round is Ronde 1 ({hud['round']})")
91 check("1 tegenstander" in (hud["opponents"] or ""), f"{tag}: one opponent ({hud['opponents']})")
92 check(hud["skill"] == "Skill 5%", f"{tag}: skill 5% ({hud['skill']})")
93 check(hud["bots"] == 1, f"{tag}: one bot field")
94 check(abs(hud["jump"] - 1.5 * 13 / 2) < 1e-9, f"{tag}: +50% jump height ({hud['jump']})")
95 check(abs(hud["fall"] - 13 / 3) < 1e-9, f"{tag}: full spawn fallSpeed ({hud['fall']})")
96 check(abs(hud["clusterFall"] - 0.5 * 13 / 3) < 1e-9, f"{tag}: halved cluster float-down ({hud['clusterFall']})")
97 mini = page.locator("#minis .mini")
98 check(mini.count() >= 1, f"{tag}: at least one bot mini")
99 name = mini.first.locator(".mini-name").inner_text()
100 check(name.startswith("Bot 1"), f"{tag}: mini named {name!r}")
101 shot(page, f"t1119-offline-ronde1-{tag}.png")
102
103 # Many opponents: jump to a high-N schedule and check minis stay cheap.
104 info = page.evaluate("""() => {
105 app.battle.advanceRound(); // 2
106 app.battle.advanceRound(); // 3, 3 opponents after two advances from 1?
107 // From round 1, advance → 2 (2 bots), advance → 3 (3 bots).
108 // Call more to get 6 opponents (round 12 starts 6? let's set round).
109 const Offline = window.Offline;
110 app.battle.round = 8;
111 app.battle.schedule = Offline.scheduleForRound(8);
112 app.battle._initBots();
113 if (typeof renderOfflineMinis === 'function') renderOfflineMinis();
114 else if (app.battle) { /* tick will render */ }
115 return { round: app.battle.round, n: app.battle.bots.length, skill: app.battle.schedule.skill };
116 }""")
117 print("many", info)
118 page.wait_for_timeout(200)
119 page.evaluate("() => { if (typeof renderOfflineMinis === 'function') renderOfflineMinis(); }")
120 page.wait_for_timeout(150)
121 nmini = page.locator("#minis .mini").count()
122 check(nmini == info["n"], f"{tag}: {nmini} minis for {info['n']} bots")
123 shot(page, f"t1119-offline-many-{tag}.png")
124
125 # Column warn: 10 grounded in column 0, pulse visible on the player field.
126 page.evaluate("""() => {
127 const g = app.core;
128 // Clear and fill column 0 with 10 still blocks.
129 for (let i = g.blocks.length - 1; i >= 0; i--) {
130 try { g.removeBlock(g.blocks[i]); } catch (e) {}
131 }
132 for (let r = 0; r < 10; r++) g.place(0, r, r % 5);
133 if (typeof updateColumnWarn === 'function') updateColumnWarn(0.4);
134 }""")
135 page.wait_for_timeout(200)
136 warn = page.evaluate("""() => ({
137 needs: app.core.columnNeedsWarn(0),
138 count: app.core.groundedCount(0),
139 visible: !!(app.columnWarn && app.columnWarn[0] && app.columnWarn[0].renderer.visible),
140 alpha: app.columnWarn && app.columnWarn[0] && app.columnWarn[0].renderer.alpha,
141 })""")
142 print("warn", warn)
143 check(warn["needs"] is True and warn["count"] >= 10, f"{tag}: column 0 needs warn")
144 check(warn["visible"] is True and warn["alpha"] > 0, f"{tag}: warn quad visible alpha={warn['alpha']}")
145 shot(page, f"t1123-column-warn-{tag}.png")
146
147 # Result screen.
148 page.evaluate("""() => {
149 app.core.state = 'gameover';
150 app.battle.state = 'lost';
151 if (typeof showOfflineResult === 'function') showOfflineResult();
152 }""")
153 page.wait_for_selector("#offline-result:not([hidden])", timeout=5000)
154 reached = page.locator("#offline-reached").inner_text()
155 check(reached.isdigit() and int(reached) >= 1, f"{tag}: reached round shown ({reached})")
156 shot(page, f"t1119-offline-result-{tag}.png")
157
158
159def main():
160 # Ensure a fresh build is what we serve.
161 port = free_port()
162 proc = start_http(port)
163 url = f"http://127.0.0.1:{port}/index.html"
164 try:
165 with sync_playwright() as p:
166 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS)
167 # desktop
168 ctx = browser.new_context(viewport={"width": 1280, "height": 900})
169 page = ctx.new_page()
170 open_offline(page, url)
171 run(page, "desktop")
172 ctx.close()
173 # mobile
174 ctx = browser.new_context(
175 viewport={"width": 393, "height": 851},
176 device_scale_factor=2,
177 is_mobile=True,
178 has_touch=True,
179 )
180 page = ctx.new_page()
181 open_offline(page, url)
182 run(page, "mobile")
183 ctx.close()
184 browser.close()
185 finally:
186 proc.terminate()
187 try:
188 proc.wait(timeout=2)
189 except Exception:
190 proc.kill()
191
192 if FAILURES:
193 print(f"\n{len(FAILURES)} FAILURES:")
194 for f in FAILURES:
195 print(" -", f)
196 sys.exit(1)
197 print("\nall offline playwright checks passed")
198
199
200if __name__ == "__main__":
201 main()