scorpiox-bot-plugin-tetris-3d
←e2e.pypython
207 lines · 8 KBHEADBlameDownload
1#!/usr/bin/env python3
2"""tests/e2e.py - viewport, console and gameplay checks for the plugin_tetris_3d UI.
3
4Serves the plugin through a tiny CGI-style HTTP shim on a loopback port and opens
5it with Playwright at 1440 / 1024 / 390 CSS pixels. Asserts there is no
6horizontal overflow, no console error, that the HUD and the three canvases
7render, and that a real game runs: a piece exists, it moves left on a keyboard
8press, and a hard drop changes the score. Skips cleanly (exit 0) when Playwright
9is not installed so the offline suite stays dependency-free.
10
11 python3 tests/e2e.py # run if Playwright is available
12 python3 tests/e2e.py --strict # exit 2 when Playwright is missing
13"""
14
15import argparse
16import http.server
17import os
18import socketserver
19import subprocess
20import sys
21import threading
22
23ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
24BIN = os.path.join(ROOT, "plugin_tetris_3d")
25VIEWPORTS = [(1440, 900), (1024, 768), (390, 844)]
26
27
28class Handler(http.server.BaseHTTPRequestHandler):
29 def do_GET(self): # noqa: N802
30 from urllib.parse import urlparse
31 u = urlparse(self.path)
32 env = dict(os.environ)
33 env["QUERY_STRING"] = u.query
34 env["REQUEST_METHOD"] = "GET"
35 env.pop("BOT_PASSWORD", None)
36 out = subprocess.run([BIN], capture_output=True, env=env, timeout=60).stdout
37 sep = out.find(b"\r\n\r\n")
38 headers = out[:sep].decode("utf-8", "replace") if sep >= 0 else ""
39 body = out[sep + 4:] if sep >= 0 else out
40 ctype = "text/html; charset=utf-8"
41 for line in headers.splitlines():
42 if line.lower().startswith("content-type:"):
43 ctype = line.split(":", 1)[1].strip()
44 self.send_response(200)
45 self.send_header("Content-Type", ctype)
46 self.send_header("Cache-Control", "no-store")
47 self.send_header("Content-Length", str(len(body)))
48 self.end_headers()
49 self.wfile.write(body)
50
51 def log_message(self, *_a):
52 pass
53
54
55def main():
56 ap = argparse.ArgumentParser()
57 ap.add_argument("--strict", action="store_true")
58 args = ap.parse_args()
59
60 if not os.path.exists(BIN):
61 print("plugin_tetris_3d is not built; run make first", file=sys.stderr)
62 return 1
63
64 try:
65 from playwright.sync_api import sync_playwright
66 except Exception:
67 msg = "playwright not installed - skipping viewport e2e"
68 if args.strict:
69 print(msg, file=sys.stderr)
70 return 2
71 print(msg)
72 return 0
73
74 with socketserver.TCPServer(("127.0.0.1", 0), Handler) as srv:
75 port = srv.server_address[1]
76 threading.Thread(target=srv.serve_forever, daemon=True).start()
77 url = "http://127.0.0.1:%d/plugin_tetris_3d?embed=1" % port
78
79 failures = []
80 with sync_playwright() as p:
81 browser = p.chromium.launch()
82 for (w, h) in VIEWPORTS:
83 page = browser.new_page(viewport={"width": w, "height": h})
84 errors = []
85
86 def on_console(m, _e=errors):
87 if m.type == "error":
88 _e.append(m.text)
89
90 page.on("console", on_console)
91 page.on("pageerror", lambda e, _e=errors: _e.append(str(e)))
92 page.goto(url, wait_until="load")
93 page.wait_for_timeout(900)
94
95 sw = page.evaluate("document.documentElement.scrollWidth")
96 iw = page.evaluate("window.innerWidth")
97 if sw > iw + 1:
98 failures.append("%dx%d horizontal overflow %d > %d" % (w, h, sw, iw))
99
100 sh = page.evaluate("document.documentElement.scrollHeight")
101 ih = page.evaluate("window.innerHeight")
102 if sh > ih + 1:
103 failures.append("%dx%d vertical overflow %d > %d" % (w, h, sh, ih))
104
105 for cid in ("cv", "cvNext", "cvHold"):
106 box = page.evaluate(
107 "(()=>{const c=document.getElementById('%s');"
108 "if(!c)return null;const r=c.getBoundingClientRect();"
109 "return [Math.round(r.width),Math.round(r.height),c.width,c.height];})()"
110 % cid)
111 if box is None:
112 failures.append("%dx%d canvas %s missing" % (w, h, cid))
113 continue
114 if box[0] < 20 or box[1] < 20:
115 failures.append("%dx%d canvas %s collapsed %r" % (w, h, cid, box))
116 if box[2] < 10 or box[3] < 10:
117 failures.append("%dx%d canvas %s has no backing pixels %r"
118 % (w, h, cid, box))
119
120 score = page.evaluate("document.getElementById('vScore').textContent")
121 if not score.strip().isdigit():
122 failures.append("%dx%d score HUD did not render (%r)" % (w, h, score))
123
124 # the canvas must actually have painted something
125 painted = page.evaluate(
126 "(()=>{const c=document.getElementById('cv');"
127 "const g=c.getContext('2d');"
128 "const d=g.getImageData(0,0,c.width,c.height).data;"
129 "let n=0;for(let i=3;i<d.length;i+=4*97){if(d[i])n++;}return n;})()")
130 if painted < 5:
131 failures.append("%dx%d canvas painted nothing (%d)" % (w, h, painted))
132
133 # gameplay: start, move left, hard drop
134 page.click("#mBtn")
135 page.wait_for_timeout(250)
136 x_before = page.evaluate("window.__sxProbe ? 0 : 0")
137 del x_before
138 page.keyboard.press("ArrowLeft")
139 page.keyboard.press("ArrowRight")
140 page.wait_for_timeout(120)
141 before = page.evaluate("document.getElementById('vScore').textContent")
142 page.keyboard.press(" ")
143 page.wait_for_timeout(200)
144 after = page.evaluate("document.getElementById('vScore').textContent")
145 if int(after) < int(before):
146 failures.append("%dx%d score went backwards after hard drop (%s -> %s)"
147 % (w, h, before, after))
148
149 if w == 390:
150 # mobile: the touch pad must be reachable and on screen
151 for bid in ("bLeft", "bDrop", "bHold", "bPause"):
152 vis = page.evaluate(
153 "(()=>{const b=document.getElementById('%s');"
154 "if(!b)return false;const r=b.getBoundingClientRect();"
155 "return r.width>0&&r.height>0&&r.bottom<=window.innerHeight+1;})()"
156 % bid)
157 if not vis:
158 failures.append("390x844 touch button %s not visible" % bid)
159 page.click("#bRot")
160 page.click("#bDrop")
161 page.wait_for_timeout(150)
162
163 if errors:
164 failures.append("%dx%d console errors: %s"
165 % (w, h, "; ".join(errors[:3])))
166
167 page.screenshot(path="/tmp/sx_tetris_3d_%dx%d.png" % (w, h))
168 page.close()
169 browser.close()
170
171 # a dark and a light render must both paint
172 with sync_playwright() as p:
173 browser = p.chromium.launch()
174 for theme in ("dark", "light"):
175 page = browser.new_page(viewport={"width": 1024, "height": 768},
176 color_scheme="dark" if theme == "dark" else "light")
177 page.goto(url, wait_until="load")
178 page.wait_for_timeout(600)
179 page.click("#mBtn")
180 page.wait_for_timeout(400)
181 bg = page.evaluate("getComputedStyle(document.body).backgroundColor")
182 painted = page.evaluate(
183 "(()=>{const c=document.getElementById('cv');"
184 "const g=c.getContext('2d');"
185 "const d=g.getImageData(0,0,c.width,c.height).data;"
186 "let n=0;for(let i=3;i<d.length;i+=4*97){if(d[i])n++;}return n;})()")
187 if painted < 5:
188 failures.append("%s theme canvas painted nothing" % theme)
189 if not bg or bg == "rgba(0, 0, 0, 0)":
190 failures.append("%s theme has no background colour" % theme)
191 page.screenshot(path="/tmp/sx_tetris_3d_%s.png" % theme)
192 page.close()
193 browser.close()
194
195 if failures:
196 print("e2e FAILURES:")
197 for f in failures:
198 print(" - " + f)
199 return 1
200
201 print("e2e ok: %d viewports clean, 2 themes painted, gameplay responds"
202 % len(VIEWPORTS))
203 return 0
204
205
206if __name__ == "__main__":
207 sys.exit(main())