BlueGit

projects-timfalken-com meteors

Files

meteors / test / planet-playwright.py

planet-playwright.py

planet-playwright.py 11.5 KiB Download Raw
1#!/usr/bin/env python3
2"""Stage 3: planet selection on desktop and mobile, plus two-player lobby picks."""
3from __future__ import annotations
4
5import os
6import shutil
7import socket
8import subprocess
9import sys
10import tempfile
11from pathlib import Path
12
13from playwright.sync_api import sync_playwright
14
15ROOT = Path("/workspace/meteors")
16SHOTS = Path("/workspace/meteors-shots")
17SHOTS.mkdir(parents=True, exist_ok=True)
18PHP = os.environ.get("PHP", "/home/box/.local/bin/php")
19CHROME = "/usr/bin/google-chrome"
20CHROME_ARGS = ["--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage"]
21LIVE = "https://projects.timfalken.com/meteors/"
22URL = None
23FAILURES = []
24
25MOBILE = {
26 "viewport": {"width": 390, "height": 844},
27 "device_scale_factor": 2,
28 "is_mobile": True,
29 "has_touch": True,
30 "user_agent": (
31 "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) "
32 "AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 "
33 "Mobile/15E148 Safari/604.1"
34 ),
35}
36
37
38def check(cond, msg):
39 if cond:
40 print("OK ", msg)
41 else:
42 print("FAIL", msg)
43 FAILURES.append(msg)
44 return cond
45
46
47def shot(page, name):
48 path = SHOTS / name
49 page.screenshot(path=str(path), full_page=False)
50 print(f"wrote {path} ({path.stat().st_size} bytes)")
51
52
53def free_port():
54 s = socket.socket()
55 s.bind(("127.0.0.1", 0))
56 port = s.getsockname()[1]
57 s.close()
58 return port
59
60
61def start_php(port, data):
62 env = os.environ.copy()
63 env["METEORS_DATA_DIR"] = str(data)
64 return subprocess.Popen(
65 [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")],
66 cwd=str(ROOT / "build"),
67 env=env,
68 stdout=subprocess.DEVNULL,
69 stderr=subprocess.DEVNULL,
70 )
71
72
73def open_picker(page):
74 page.goto(URL, wait_until="networkidle", timeout=25000)
75 page.wait_for_timeout(500)
76 page.locator("#btn-survival").click()
77 page.locator("#planet-select").wait_for(state="visible", timeout=8000)
78 page.wait_for_timeout(300)
79
80
81def cards(page):
82 return page.locator("#planet-grid .planet-card")
83
84
85def run_desktop(browser):
86 print("\n======== desktop planet select ========")
87 ctx = browser.new_context(viewport={"width": 1280, "height": 900})
88 page = ctx.new_page()
89 open_picker(page)
90 n = cards(page).count()
91 check(n >= 8 and n <= 12, f"catalog has 8–12 cards (got {n})")
92 texts = [cards(page).nth(i).inner_text() for i in range(n)]
93 joined = "\n".join(texts)
94 for name in ("Terra", "Aurel", "Cinder", "Lunara", "Forge"):
95 check(name in joined, f"desktop grid lists {name}")
96 # Numeric stats, no long explanation — Terra mid values.
97 terra = next(t for t in texts if t.startswith("Terra"))
98 check("Terrans" in terra, "Terra people name")
99 check("g 9.81" in terra and "d 1.05" in terra and "F 104 N" in terra and "Power 44%" in terra,
100 "Terra numeric stats on the card")
101 cinder = next(t for t in texts if t.startswith("Cinder"))
102 check("Cindari" in cinder and "Power 92%" in cinder and "g 19.62" in cinder,
103 "Cinder is the hardest (Power 92%)")
104 aurel = next(t for t in texts if t.startswith("Aurel"))
105 check("Aurelians" in aurel and "Power 0%" in aurel, "Aurel is the easiest (Power 0%)")
106 # Each card has 5 unique placeholder images.
107 imgs = page.locator("#planet-grid .planet-card").nth(0).locator("img")
108 check(imgs.count() == 5, "five color placeholders on a card")
109 shot(page, "stage3-planet-select-desktop.png")
110
111 # Pick Cinder and start.
112 page.locator('.planet-card[data-planet="cinder"]').click()
113 page.wait_for_timeout(200)
114 check("selected" in (page.locator('.planet-card[data-planet="cinder"]').get_attribute("class") or ""),
115 "Cinder card is selected")
116 page.locator("#btn-planet-go").click()
117 page.wait_for_function("() => app && app.mode === 'playing' && app.core", timeout=8000)
118 hud = page.evaluate("""() => ({
119 name: document.getElementById('planet-name').textContent,
120 stats: document.getElementById('planet-stats').textContent,
121 id: app.planet && app.planet.id,
122 miss: app.core && app.core.missChance,
123 power: Planet.power(app.planet)
124 })""")
125 print("HUD", hud)
126 check(hud["id"] == "cinder" and "Cinder" in hud["name"] and "Cindari" in hud["name"],
127 "HUD shows Cinder · Cindari")
128 check("Power 92%" in hud["stats"] and "g 19.62" in hud["stats"], "HUD shows Cinder numbers")
129 check(abs(hud["miss"] - 0.05) < 1e-9, "GameCore missChance is Cinder's 5%")
130 shot(page, "stage3-play-cinder-desktop.png")
131 ctx.close()
132
133
134def run_mobile(browser):
135 print("\n======== mobile planet select ========")
136 ctx = browser.new_context(**MOBILE)
137 page = ctx.new_page()
138 open_picker(page)
139 n = cards(page).count()
140 check(n >= 8, f"mobile grid has the catalog (got {n})")
141 # Scroll to Cinder if needed, then pick it.
142 card = page.locator('.planet-card[data-planet="cinder"]')
143 card.scroll_into_view_if_needed()
144 page.wait_for_timeout(200)
145 shot(page, "stage3-planet-select-mobile.png")
146 card.click()
147 page.locator("#btn-planet-go").click()
148 page.wait_for_function("() => app && app.mode === 'playing' && app.planet && app.planet.id === 'cinder'", timeout=8000)
149 playing = page.evaluate("() => ({mode: app.mode, id: app.planet.id, w: window.innerWidth})")
150 print("mobile play", playing)
151 check(playing["mode"] == "playing" and playing["id"] == "cinder", "mobile starts Cinder after the picker")
152 shot(page, "stage3-play-cinder-mobile.png")
153 ctx.close()
154
155
156def login(page, n):
157 # test login, then land on the game with online panel openable
158 page.goto(f"{URL}auth.php?test={n}&next=index.html", wait_until="networkidle", timeout=20000)
159 page.wait_for_timeout(300)
160 page.goto(f"{URL}index.html?online=1", wait_until="networkidle", timeout=20000)
161 page.wait_for_timeout(600)
162 # If the online panel isn't auto-opened, click the button.
163 if not page.locator("#online-panel").is_visible():
164 if page.locator("#btn-online").is_visible():
165 page.locator("#btn-online").click()
166 page.wait_for_timeout(800)
167
168
169def run_lobby(browser):
170 print("\n======== lobby planet picks (two contexts) ========")
171 c1 = browser.new_context(viewport={"width": 1280, "height": 900})
172 c2 = browser.new_context(viewport={"width": 1100, "height": 900})
173 p1 = c1.new_page()
174 p2 = c2.new_page()
175 login(p1, 1)
176 login(p2, 2)
177 # Host creates a lobby (default planet), then picks Aurel.
178 p1.locator("#btn-create").wait_for(state="visible", timeout=8000)
179 p1.locator("#btn-create").click()
180 p1.locator("#online-lobby").wait_for(state="visible", timeout=8000)
181 p1.wait_for_timeout(400)
182 p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').scroll_into_view_if_needed()
183 p1.locator('#lobby-planet-grid .planet-card[data-planet="aurel"]').click()
184 p1.wait_for_timeout(600)
185 code = p1.locator("#lobby-code").inner_text().strip()
186 check(len(code) == 4, f"lobby code {code}")
187 # Guest joins and picks Cinder.
188 p2.locator("#join-code").fill(code)
189 p2.locator("#btn-join").click()
190 p2.locator("#online-lobby").wait_for(state="visible", timeout=8000)
191 p2.wait_for_timeout(500)
192 p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').scroll_into_view_if_needed()
193 p2.locator('#lobby-planet-grid .planet-card[data-planet="cinder"]').click()
194 p2.wait_for_timeout(800)
195 # Poll so both see each other's pick.
196 p1.wait_for_timeout(1000)
197 p2.wait_for_timeout(400)
198 host_list = p1.locator("#lobby-players").inner_text()
199 guest_list = p2.locator("#lobby-players").inner_text()
200 print("host list:", host_list.replace("\n", " | "))
201 print("guest list:", guest_list.replace("\n", " | "))
202 check("Aurel" in host_list and "Cinder" in host_list, "host lobby shows both planet names")
203 check("Aurel" in guest_list and "Cinder" in guest_list, "guest lobby shows both planet names")
204 shot(p1, "stage3-lobby-planets-host.png")
205 shot(p2, "stage3-lobby-planets-guest.png")
206 # Ready and start; each plays their own planet.
207 p1.locator("#btn-ready").click()
208 p2.locator("#btn-ready").click()
209 p1.wait_for_timeout(800)
210 p1.locator("#btn-start").click()
211 p1.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
212 p2.wait_for_function("() => app && app.mode === 'playing' && app.online", timeout=10000)
213 ids = {
214 "host": p1.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
215 "guest": p2.evaluate("() => ({id: app.planet.id, miss: app.core.missChance, name: app.planet.name})"),
216 }
217 print("match planets", ids)
218 check(ids["host"]["id"] == "aurel" and abs(ids["host"]["miss"] - 0.60) < 1e-9,
219 "host plays Aurel (60% miss from own Power)")
220 check(ids["guest"]["id"] == "cinder" and abs(ids["guest"]["miss"] - 0.05) < 1e-9,
221 "guest plays Cinder (5% miss from own Power)")
222 shot(p1, "stage3-game-aurel-host.png")
223 shot(p2, "stage3-game-cinder-guest.png")
224 c1.close()
225 c2.close()
226
227
228def run_live(browser):
229 print("\n======== live site ========")
230 try:
231 ctx = browser.new_context(viewport={"width": 1280, "height": 900})
232 page = ctx.new_page()
233 page.goto(LIVE, wait_until="networkidle", timeout=25000)
234 page.wait_for_timeout(800)
235 if not page.locator("#btn-survival").is_visible():
236 check(False, "live menu not reachable")
237 ctx.close()
238 return
239 page.locator("#btn-survival").click()
240 page.wait_for_timeout(1000)
241 if page.locator("#planet-select").is_visible():
242 n = page.locator("#planet-grid .planet-card").count()
243 check(n >= 8, f"live planet grid has the catalog (got {n})")
244 shot(page, "stage3-live-planet-select.png")
245 page.locator('.planet-card[data-planet="terra"]').click()
246 page.locator("#btn-planet-go").click()
247 page.wait_for_timeout(800)
248 playing = page.evaluate("() => app && app.mode === 'playing' && app.planet && app.planet.id")
249 check(playing == "terra", "live solo starts on the chosen planet")
250 shot(page, "stage3-live-play-terra.png")
251 else:
252 # Not deployed yet: just note it; this check is re-run after deploy.
253 print("live planet select not present yet (expected before this deploy)")
254 shot(page, "stage3-live-planet-select.png")
255 ctx.close()
256 except Exception as e:
257 check(False, f"live site check: {e}")
258
259
260def main():
261 global URL
262 if not Path(PHP).is_file():
263 print("php not found at", PHP)
264 return 1
265 port = free_port()
266 URL = f"http://127.0.0.1:{port}/"
267 data = Path(tempfile.mkdtemp(prefix="meteors-pw3-"))
268 print("PHP", PHP, "URL", URL)
269 proc = start_php(port, data)
270 try:
271 with sync_playwright() as p:
272 browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
273 run_desktop(browser)
274 run_mobile(browser)
275 run_lobby(browser)
276 run_live(browser)
277 browser.close()
278 finally:
279 proc.terminate()
280 try:
281 proc.wait(timeout=3)
282 except Exception:
283 proc.kill()
284 shutil.rmtree(data, ignore_errors=True)
285 print("\n======== summary ========")
286 if FAILURES:
287 print(f"{len(FAILURES)} failure(s):")
288 for f in FAILURES:
289 print(" -", f)
290 return 1
291 print("all stage-3 playwright checks passed")
292 return 0
293
294
295if __name__ == "__main__":
296 sys.exit(main())