#!/usr/bin/env python3 """t1143: custom-planet solo after ?online=1 login, WebGL start failure, lifetime points.""" from __future__ import annotations import os import socket import subprocess import sys import tempfile import time from pathlib import Path from playwright.sync_api import sync_playwright ROOT = Path("/workspace/meteors") SHOTS = Path("/workspace/meteors-shots") SHOTS.mkdir(parents=True, exist_ok=True) PHP = os.environ.get("PHP", "/home/box/.local/bin/php") CHROME = "/usr/bin/google-chrome" CHROME_ARGS = [ "--use-gl=angle", "--use-angle=swiftshader", "--no-sandbox", "--disable-dev-shm-usage", ] FAILURES = [] URL = None def check(cond, msg): print(("OK " if cond else "FAIL") + " " + msg) if not cond: FAILURES.append(msg) return cond def shot(page, name): path = SHOTS / name page.screenshot(path=str(path), full_page=False) print(f"wrote {path} ({path.stat().st_size})") def free_port(): s = socket.socket() s.bind(("127.0.0.1", 0)) port = s.getsockname()[1] s.close() return port def start_php(port, data, log_path): env = os.environ.copy() env["METEORS_DATA_DIR"] = str(data) log = open(log_path, "w") proc = subprocess.Popen( [PHP, "-S", f"127.0.0.1:{port}", "-t", str(ROOT / "build"), str(ROOT / "build" / "router.php")], cwd=str(ROOT / "build"), env=env, stdout=log, stderr=log, ) time.sleep(0.5) if proc.poll() is not None: raise RuntimeError("php failed: " + Path(log_path).read_text(errors="replace")) return proc def login(page, next_url="index.html?online=1"): page.goto(f"{URL}auth.php?test=1&next={next_url}", wait_until="domcontentloaded", timeout=20000) page.wait_for_function("() => typeof Online !== 'undefined' && Online.me", timeout=15000) page.wait_for_timeout(400) def back_to_menu(page): vis = page.locator("#online-home [data-back-menu]") if vis.count() and vis.first.is_visible(): vis.first.click() else: page.evaluate( """() => { document.getElementById('online-panel').hidden = true; document.getElementById('menu').hidden = false; if (window.app) { app.mode = 'menu'; app.online = false; } if (typeof Online !== 'undefined' && Online.stopPolling) Online.stopPolling(); }""" ) page.wait_for_selector("#btn-play", timeout=8000) page.wait_for_timeout(200) def set_lang(page, loc): page.locator("#lang-current").click() page.wait_for_selector("#lang-list:not([hidden])", timeout=4000) page.locator(f'#lang-list .lang-option[data-locale="{loc}"]').click() page.wait_for_timeout(250) def field_ok(page): return page.evaluate( """() => { const c = document.querySelector('body > canvas'); const r = c ? c.getBoundingClientRect() : null; return { mode: window.app && app.mode, cells: window.app && app.cells && app.cells.length, canvasW: r && r.width, canvasH: r && r.height, planetHud: (document.getElementById('planet-name')||{}).textContent, planetId: window.app && app.planet && app.planet.id, planetName: window.app && app.planet && app.planet.name, hudHidden: document.getElementById('hud') && document.getElementById('hud').hidden, menuHidden: document.getElementById('menu') && document.getElementById('menu').hidden, token: window.app && app.playToken, }; }""" ) def test_custom_and_points(page): login(page, "index.html?online=1") check("online=1" in page.url, f"landed with ?online=1 ({page.url})") back_to_menu(page) set_lang(page, "nl") check(page.locator("#btn-designer").is_visible(), "designer visible") page.locator("#btn-designer").click() page.locator("#designer").wait_for(state="visible", timeout=8000) page.locator("#btn-designer-new").click() page.locator("#designer-edit").wait_for(state="visible", timeout=8000) page.locator("#des-name").fill("Testplaneet Ada") page.locator("#des-people").fill("Adanen") page.locator("#btn-designer-save").click() page.wait_for_function( "() => (document.getElementById('designer-list')||{}).innerText.includes('Ada')", timeout=10000, ) page.locator("#btn-designer-back").click() page.wait_for_selector("#btn-play", timeout=8000) page.locator("#btn-play").click() page.wait_for_selector("#planet-select:not([hidden])", timeout=8000) custom = page.locator("#planet-grid .planet-card.custom") check(custom.count() >= 1, "custom planet in Spelen picker") custom.first.scroll_into_view_if_needed() custom.first.click() page.wait_for_timeout(200) page.locator("#btn-planet-go").click() page.wait_for_timeout(1500) st = field_ok(page) print("custom play", st) check(st["mode"] == "playing", f"mode playing, got {st['mode']}") check((st["cells"] or 0) >= 130, f"field cells {st['cells']}") check((st["canvasW"] or 0) > 100 and (st["canvasH"] or 0) > 100, f"canvas {st['canvasW']}x{st['canvasH']}") check("Testplaneet Ada" in (st["planetHud"] or ""), f"HUD is custom planet, got {st['planetHud']!r}") check("Terra" not in (st["planetHud"] or "").replace("Testplaneet", ""), f"HUD is not Terra: {st['planetHud']!r}") shot(page, "t1143-local-custom-solo-field.png") # Lifetime points: wait for play_begin token, min 3s, then force game over. page.wait_for_function("() => window.app && app.playToken", timeout=8000) page.wait_for_timeout(3500) page.evaluate( """() => { app.core.score = 12; app.core.state = 'gameover'; app.core.gameOverTime = 0; }""" ) # finishPlaySession runs on first gameover tick; then returnToMenu after 2s page.wait_for_function( "() => document.getElementById('menu') && !document.getElementById('menu').hidden", timeout=8000, ) page.wait_for_timeout(800) pts = page.locator("#menu-points").inner_text().strip() print("lifetime after game over", pts) check(int(pts) >= 12, f"solo game-over awards lifetime points, got {pts}") shot(page, "t1143-local-points-after-gameover.png") def test_webgl_failure(page): # Fresh logged-out (or stay logged in — doesn't matter). Reload menu. page.goto(f"{URL}index.html", wait_until="networkidle", timeout=20000) page.wait_for_selector("#btn-play", timeout=10000) page.wait_for_timeout(400) page.evaluate( """() => { // ES6 `class Scene` is lexical, not window.Scene — hook getContext // so GLContext throws the same 'WebGL is not supported' as a GPU blocklist. const proto = HTMLCanvasElement.prototype; if (!window.__OrigGetContext) window.__OrigGetContext = proto.getContext; proto.getContext = function (type) { const t = String(type || ''); if (t.indexOf('webgl') !== -1 || t === 'experimental-webgl') { return null; } return window.__OrigGetContext.apply(this, arguments); }; }""" ) page.locator("#btn-play").click() page.wait_for_selector("#planet-select:not([hidden])", timeout=8000) page.locator("#btn-planet-go").click() page.wait_for_timeout(600) info = page.evaluate( """() => ({ menuHidden: document.getElementById('menu').hidden, menuDisplay: getComputedStyle(document.getElementById('menu')).display, hudHidden: document.getElementById('hud').hidden, hudPlanet: document.getElementById('planet-name').textContent, err: (document.getElementById('start-error')||{}).textContent, errHidden: document.getElementById('start-error').hidden, orphan: !!document.getElementById('canvas_orphan_t1143'), bodyCanvas: document.querySelectorAll('body > canvas').length, mode: window.app && app.mode, })""" ) print("webgl fail state", info) check(info["menuHidden"] is False and info["menuDisplay"] != "none", "returned to menu on WebGL fail") check(info["hudHidden"] is True, "HUD not left visible with default Terra") check(info["errHidden"] is False and "WebGL" in (info["err"] or ""), f"WebGL error shown: {info['err']!r}") check(info["bodyCanvas"] == 0, f"orphan canvas removed, body canvases={info['bodyCanvas']}") check(info["mode"] == "menu", f"app.mode menu, got {info['mode']}") shot(page, "t1143-local-webgl-error.png") page.evaluate("""() => { if (window.__OrigGetContext) { HTMLCanvasElement.prototype.getContext = window.__OrigGetContext; } }""") def main(): global URL port = free_port() URL = f"http://127.0.0.1:{port}/" data = Path(tempfile.mkdtemp(prefix="meteors-t1143-")) proc = start_php(port, data, "/tmp/t1143-test-php.log") print("PHP", URL, data) try: with sync_playwright() as p: browser = p.chromium.launch(executable_path=CHROME, args=CHROME_ARGS, headless=True) ctx = browser.new_context(viewport={"width": 1280, "height": 800}) page = ctx.new_page() errs = [] page.on("pageerror", lambda e: errs.append(str(e))) test_custom_and_points(page) test_webgl_failure(page) print("pageerrors", errs) # WebGL mock throws — startPlay catches it, should not be an unhandled? # abortStartPlay console.errors but the throw is caught. Good. ctx.close() browser.close() finally: proc.terminate() try: proc.wait(timeout=3) except Exception: proc.kill() if FAILURES: print("FAILURES:") for f in FAILURES: print(" -", f) return 1 print("ALL OK") return 0 if __name__ == "__main__": sys.exit(main())