test: Playwright online flow with two contexts
Local PHP server, test_user_1 and test_user_2: create/join lobby, ready, start, minis, flight tween and incoming garbage. Also checks that live solo play still works. Screenshots go to meteors-shots.
@@ -0,0 +1,261 @@
1
#!/usr/bin/env python3
2
"""Stage-2 online flow: two Playwright contexts against a local PHP server.
3
Also a live solo/online-panel check where the public site is reachable.
4
"""
5
from __future__ import annotations
6
7
import json
8
import os
9
import shutil
10
import socket
11
import subprocess
12
import sys
13
import tempfile
14
import time
15
from pathlib import Path
16
17
from playwright.sync_api import sync_playwright
18
19
ROOT = Path("/workspace/meteors")
20
OUT = Path("/workspace/meteors-shots")
21
OUT.mkdir(parents=True, exist_ok=True)
22
CHROME = "/usr/bin/google-chrome"
23
CHROME_ARGS = [
24
"--use-gl=angle",
25
"--use-angle=swiftshader",
26
"--no-sandbox",
27
"--disable-dev-shm-usage",
28
]
29
LIVE = "https://projects.timfalken.com/meteors/"
30
PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")
31
FAILURES = []
32
33
34
def 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
42
def 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
51
def 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
58
def 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
75
def 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
83
def wait_visible(page, sel, timeout=8000):
84
page.locator(sel).wait_for(state="visible", timeout=timeout)
85
86
87
def 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
193
def 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-play").click()
205
page.wait_for_timeout(800)
206
playing = page.evaluate("() => app && app.mode === 'playing'")
207
check(playing, "live solo Play still starts a game")
208
shot(page, "stage2-live-solo.png")
209
# Back via evaluating return — game-over takes 2s+ after a full lock, so just reload.
210
page.goto(LIVE, wait_until="networkidle", timeout=20000)
211
page.wait_for_timeout(400)
212
if page.locator("#btn-online").is_visible():
213
page.locator("#btn-online").click()
214
page.wait_for_timeout(1200)
215
shot(page, "stage2-live-online-panel.png")
216
# Either unconfigured notice, login, or a live API error — solo is already confirmed.
217
panel = page.locator("#online-panel").is_visible()
218
check(panel, "live Online spelen opens the panel")
219
body = page.locator("#online-panel").inner_text()
220
print("live online panel text:", body[:400].replace("\n", " / "))
221
ctx.close()
222
except Exception as e:
223
check(False, f"live site check: {e}")
224
225
226
def main():
227
global URL
228
if not Path(PHP).is_file():
229
print("php not found at", PHP)
230
return 1
231
port = free_port()
232
URL = f"http://127.0.0.1:{port}/"
233
data = Path(tempfile.mkdtemp(prefix="meteors-pw-"))
234
print("PHP", PHP, "URL", URL, "data", data)
235
proc = start_php(port, data)
236
try:
237
with sync_playwright() as p:
238
browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)
239
run_two_contexts(browser)
240
run_live(browser)
241
browser.close()
242
finally:
243
proc.terminate()
244
try:
245
proc.wait(timeout=3)
246
except Exception:
247
proc.kill()
248
shutil.rmtree(data, ignore_errors=True)
249
250
print("\n======== summary ========")
251
if FAILURES:
252
print(f"{len(FAILURES)} failure(s):")
253
for f in FAILURES:
254
print(" -", f)
255
return 1
256
print("all stage-2 playwright checks passed")
257
return 0
258
259
260
if __name__ == "__main__":
261
sys.exit(main())
@@ -0,0 +1,261 @@1
#!/usr/bin/env python32
"""Stage-2 online flow: two Playwright contexts against a local PHP server.3
Also a live solo/online-panel check where the public site is reachable.4
"""5
from __future__ import annotations6
7
import json8
import os9
import shutil10
import socket11
import subprocess12
import sys13
import tempfile14
import time15
from pathlib import Path16
17
from playwright.sync_api import sync_playwright18
19
ROOT = Path("/workspace/meteors")20
OUT = Path("/workspace/meteors-shots")21
OUT.mkdir(parents=True, exist_ok=True)22
CHROME = "/usr/bin/google-chrome"23
CHROME_ARGS = [24
"--use-gl=angle",25
"--use-angle=swiftshader",26
"--no-sandbox",27
"--disable-dev-shm-usage",28
]29
LIVE = "https://projects.timfalken.com/meteors/"30
PHP = shutil.which("php") or str(Path.home() / ".local/bin/php")31
FAILURES = []32
33
34
def free_port():35
s = socket.socket()36
s.bind(("127.0.0.1", 0))37
port = s.getsockname()[1]38
s.close()39
return port40
41
42
def check(cond, msg):43
if not cond:44
FAILURES.append(msg)45
print("FAIL", msg)46
else:47
print("OK ", msg)48
return cond49
50
51
def shot(page, name):52
path = OUT / name53
page.screenshot(path=str(path), full_page=False)54
print(f"wrote {path} ({path.stat().st_size} bytes)")55
return path56
57
58
def 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 proc73
74
75
def 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
83
def wait_visible(page, sel, timeout=8000):84
page.locator(sel).wait_for(state="visible", timeout=timeout)85
86
87
def 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
break132
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 = False143
for _ in range(16):144
if start.is_visible() and start.is_enabled():145
enabled = True146
break147
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
193
def 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-play").click()205
page.wait_for_timeout(800)206
playing = page.evaluate("() => app && app.mode === 'playing'")207
check(playing, "live solo Play still starts a game")208
shot(page, "stage2-live-solo.png")209
# Back via evaluating return — game-over takes 2s+ after a full lock, so just reload.210
page.goto(LIVE, wait_until="networkidle", timeout=20000)211
page.wait_for_timeout(400)212
if page.locator("#btn-online").is_visible():213
page.locator("#btn-online").click()214
page.wait_for_timeout(1200)215
shot(page, "stage2-live-online-panel.png")216
# Either unconfigured notice, login, or a live API error — solo is already confirmed.217
panel = page.locator("#online-panel").is_visible()218
check(panel, "live Online spelen opens the panel")219
body = page.locator("#online-panel").inner_text()220
print("live online panel text:", body[:400].replace("\n", " / "))221
ctx.close()222
except Exception as e:223
check(False, f"live site check: {e}")224
225
226
def main():227
global URL228
if not Path(PHP).is_file():229
print("php not found at", PHP)230
return 1231
port = free_port()232
URL = f"http://127.0.0.1:{port}/"233
data = Path(tempfile.mkdtemp(prefix="meteors-pw-"))234
print("PHP", PHP, "URL", URL, "data", data)235
proc = start_php(port, data)236
try:237
with sync_playwright() as p:238
browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True)239
run_two_contexts(browser)240
run_live(browser)241
browser.close()242
finally:243
proc.terminate()244
try:245
proc.wait(timeout=3)246
except Exception:247
proc.kill()248
shutil.rmtree(data, ignore_errors=True)249
250
print("\n======== summary ========")251
if FAILURES:252
print(f"{len(FAILURES)} failure(s):")253
for f in FAILURES:254
print(" -", f)255
return 1256
print("all stage-2 playwright checks passed")257
return 0258
259
260
if __name__ == "__main__":261
sys.exit(main())