BlueGit

projects-timfalken-com meteors

Files

meteors / test / online-playwright.py

online-playwright.py

online-playwright.py 9.6 KiB Download Raw
1#!/usr/bin/env python3
2"""Stage-2 online flow: two Playwright contexts against a local PHP server.
3Also a live solo/online-panel check where the public site is reachable.
4"""
5from __future__ import annotations
6
7import json
8import os
9import shutil
10import socket
11import subprocess
12import sys
13import tempfile
14import time
15from pathlib import Path
16
17from playwright.sync_api import sync_playwright
18
19ROOT = Path("/workspace/meteors")
20OUT = Path("/workspace/meteors-shots")
21OUT.mkdir(parents=True, exist_ok=True)
22CHROME = "/usr/bin/google-chrome"
23CHROME_ARGS = [
24 "--use-gl=angle",
25 "--use-angle=swiftshader",
26 "--no-sandbox",
27 "--disable-dev-shm-usage",
28]
29LIVE = "https://projects.timfalken.com/meteors/"
30PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")
31FAILURES = []
32
33
34def free_port():
35 s = socket.socket()
36 s.bind(("127.0.0.1", 0))
37 port = s.getsockname()[1]
38 s.close()
39 return port
40
41
42def check(cond, msg):
43 if not cond:
44 FAILURES.append(msg)
45 print("FAIL", msg)
46 else:
47 print("OK ", msg)
48 return cond
49
50
51def shot(page, name):
52 path = OUT / name
53 page.screenshot(path=str(path), full_page=False)
54 print(f"wrote {path} ({path.stat().st_size} bytes)")
55 return path
56
57
58def start_php(port, data_dir):
59 env = os.environ.copy()
60 env["METEORS_DATA_DIR"] = str(data_dir)
61 proc = subprocess.Popen(
62 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
63 cwd=str(ROOT / "build"),
64 stdout=subprocess.DEVNULL,
65 stderr=subprocess.PIPE,
66 env=env,
67 )
68 time.sleep(0.4)
69 if proc.poll() is not None:
70 err = proc.stderr.read().decode("utf-8", "replace") if proc.stderr else ""
71 raise RuntimeError("php -S failed: " + err)
72 return proc
73
74
75def login(page, n, next_path="index.html?online=1"):
76 # Log in first (test= is only honoured on loopback), then open the online panel.
77 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="domcontentloaded", timeout=15000)
78 page.wait_for_timeout(300)
79 page.goto(f"{URL}{next_path}", wait_until="domcontentloaded", timeout=15000)
80 page.wait_for_timeout(400)
81
82
83def wait_visible(page, sel, timeout=8000):
84 page.locator(sel).wait_for(state="visible", timeout=timeout)
85
86
87def run_two_contexts(browser):
88 print("\n======== two local contexts ========")
89 c1 = browser.new_context(viewport={"width": 1280, "height": 800})
90 c2 = browser.new_context(viewport={"width": 1100, "height": 760})
91 p1 = c1.new_page()
92 p2 = c2.new_page()
93 bag = []
94 for p, tag in ((p1, "p1"), (p2, "p2")):
95 p.on("pageerror", lambda e, tag=tag: bag.append(f"{tag} pageerror: {e}"))
96 p.on("console", lambda m, tag=tag: bag.append(f"{tag} {m.type}: {m.text}") if m.type == "error" else None)
97
98 login(p1, 1)
99 login(p2, 2)
100 wait_visible(p1, "#online-panel")
101 wait_visible(p2, "#online-panel")
102 check(p1.locator("#online-home").is_visible() or p1.locator("#online-lobby").is_visible(),
103 "user 1 landed in the online panel")
104 check(p2.locator("#online-home").is_visible() or p2.locator("#online-lobby").is_visible(),
105 "user 2 landed in the online panel")
106 # If we landed in a leftover lobby, leave first.
107 for p in (p1, p2):
108 if p.locator("#online-lobby").is_visible() and p.locator("#btn-leave-lobby").is_visible():
109 p.locator("#btn-leave-lobby").click()
110 p.wait_for_timeout(400)
111
112 wait_visible(p1, "#btn-create")
113 shot(p1, "stage2-online-home.png")
114 p1.locator("#btn-create").click()
115 wait_visible(p1, "#online-lobby")
116 p1.wait_for_function("() => document.getElementById('lobby-code') && document.getElementById('lobby-code').textContent.trim().length >= 4", timeout=8000)
117 code = p1.locator("#lobby-code").inner_text().strip()
118 check(len(code) >= 4, f"lobby code visible ({code!r})")
119 shot(p1, "stage2-lobby-host.png")
120
121 wait_visible(p2, "#join-code")
122 p2.locator("#join-code").fill(code)
123 p2.locator("#btn-join").click()
124 wait_visible(p2, "#online-lobby")
125 p2.wait_for_timeout(500)
126 players2 = p2.locator("#lobby-players li").count()
127 players1 = p1.locator("#lobby-players li").count()
128 # Host poll should pick up the joiner shortly.
129 for _ in range(12):
130 if p1.locator("#lobby-players li").count() >= 2:
131 break
132 p1.wait_for_timeout(400)
133 players1 = p1.locator("#lobby-players li").count()
134 check(players2 >= 2, f"guest sees two players ({players2})")
135 check(players1 >= 2, f"host sees two players ({players1})")
136 shot(p2, "stage2-lobby-guest.png")
137
138 p1.locator("#btn-ready").click()
139 p2.locator("#btn-ready").click()
140 # Host start becomes enabled once both ready (poll).
141 start = p1.locator("#btn-start")
142 enabled = False
143 for _ in range(16):
144 if start.is_visible() and start.is_enabled():
145 enabled = True
146 break
147 p1.wait_for_timeout(400)
148 check(enabled, "host Starten is enabled when both are ready")
149 shot(p1, "stage2-lobby-ready.png")
150 start.click()
151
152 # Both should enter the game: HUD + canvas + opponent minis.
153 for p, name in ((p1, "host"), (p2, "guest")):
154 p.wait_for_function("() => app && app.mode === 'playing' && app.online && app.core", timeout=10000)
155 p.wait_for_selector("canvas", state="visible", timeout=8000)
156 p.wait_for_timeout(600)
157 nminis = p.locator("#minis .mini").count()
158 check(nminis >= 1, f"{name} sees at least one opponent miniature ({nminis})")
159 hud = p.locator("#hud").is_visible()
160 check(hud, f"{name} HUD visible")
161 shot(p1, "stage2-game-host.png")
162 shot(p2, "stage2-game-guest.png")
163
164 # Inject a shot so we can screenshot the flight tween.
165 p1.evaluate(
166 """() => {
167 if (!app.core) return;
168 const shots = [{id: 9001, color: 0, col: 4, y: 12}];
169 Online.rememberFlightLocal(shots[0], window.innerWidth/2, 200);
170 Online.queueShots(shots);
171 // Force a poll-like result locally so the tween plays even before the server answers.
172 Online.spawnFlights([{client_id: '9001', miss: false, target_id: Online.aliveOpponents()[0] && Online.aliveOpponents()[0].id, color: 0, flight_duration: 1.2}], {'9001': {col: 4, y: 12, color: 0}});
173 }"""
174 )
175 p1.wait_for_timeout(350)
176 flights = p1.evaluate("() => document.querySelectorAll('#flights .flight').length")
177 check(flights >= 1, f"flight tween appears ({flights})")
178 shot(p1, "stage2-flight.png")
179
180 # Incoming garbage path: ingest a grey on the guest and wait a frame.
181 p2.evaluate("() => { const b = app.core.ingestGarbage(); return b && {col: b.col, color: b.color, state: b.state}; }")
182 p2.wait_for_timeout(200)
183 grey = p2.evaluate("() => app.core.blocks.some(b => b.color === -1 && b.state === 'falling')")
184 check(grey, "ingestGarbage drops a falling grey on the guest")
185 shot(p2, "stage2-garbage.png")
186
187 if bag:
188 print("console:", bag[:12])
189 c1.close()
190 c2.close()
191
192
193def run_live(browser):
194 print("\n======== live site ========")
195 try:
196 ctx = browser.new_context(viewport={"width": 1280, "height": 800})
197 page = ctx.new_page()
198 page.goto(LIVE, wait_until="networkidle", timeout=20000)
199 page.wait_for_timeout(600)
200 title = page.locator("h1")
201 check(title.is_visible() and "Meteors" in title.inner_text(), "live menu title")
202 shot(page, "stage2-live-menu.png")
203 # Solo still works.
204 page.locator("#btn-survival").click()
205 page.wait_for_timeout(600)
206 if page.locator("#planet-select").is_visible():
207 page.locator("#btn-planet-go").click()
208 page.wait_for_timeout(800)
209 playing = page.evaluate("() => app && app.mode === 'playing'")
210 check(playing, "live solo Play still starts a game")
211 shot(page, "stage2-live-solo.png")
212 # Back via evaluating return — game-over takes 2s+ after a full lock, so just reload.
213 page.goto(LIVE, wait_until="networkidle", timeout=20000)
214 page.wait_for_timeout(400)
215 if page.locator("#btn-online").is_visible():
216 page.locator("#btn-online").click()
217 page.wait_for_timeout(1200)
218 shot(page, "stage2-live-online-panel.png")
219 # Either unconfigured notice, login, or a live API error — solo is already confirmed.
220 panel = page.locator("#online-panel").is_visible()
221 check(panel, "live Online spelen opens the panel")
222 body = page.locator("#online-panel").inner_text()
223 print("live online panel text:", body[:400].replace("\n", " / "))
224 ctx.close()
225 except Exception as e:
226 check(False, f"live site check: {e}")
227
228
229def main():
230 global URL
231 if not Path(PHP).is_file():
232 print("php not found at", PHP)
233 return 1
234 port = free_port()
235 URL = f"http://127.0.0.1:{port}/"
236 data = Path(tempfile.mkdtemp(prefix="meteors-pw-"))
237 print("PHP", PHP, "URL", URL, "data", data)
238 proc = start_php(port, data)
239 try:
240 with sync_playwright() as p:
241 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
242 run_two_contexts(browser)
243 run_live(browser)
244 browser.close()
245 finally:
246 proc.terminate()
247 try:
248 proc.wait(timeout=3)
249 except Exception:
250 proc.kill()
251 shutil.rmtree(data, ignore_errors=True)
252
253 print("\n======== summary ========")
254 if FAILURES:
255 print(f"{len(FAILURES)} failure(s):")
256 for f in FAILURES:
257 print(" -", f)
258 return 1
259 print("all stage-2 playwright checks passed")
260 return 0
261
262
263if __name__ == "__main__":
264 sys.exit(main())