BlueGit

projects-timfalken-com allianties

Files

allianties / test / lobby-interaction-playwright.py

lobby-interaction-playwright.py

lobby-interaction-playwright.py 10.6 KiB Download Raw
1#!/usr/bin/env python3
2"""Real-browser checks for the lobby rules form (t1171/t1172).
3
4- Dragging on the cease-fire clock paints and adjusts ranges smoothly (same
5 SVG node throughout the drag; pointer capture survives polls).
6- Typing in time / number inputs keeps focus across several poll cycles
7 while other players join and leave (lobby version bumps).
8- Non-hosts get a read-only form; the API refuses their rule edits (403).
9- Times are shown in each player's local zone (host Amsterdam, guest Tokyo).
10Desktop (mouse) and mobile (touch). Usage: python3 test/lobby-interaction-playwright.py [BASE]
11"""
12import math
13import sys
14from pathlib import Path
15from urllib.parse import quote
16
17from playwright.sync_api import sync_playwright
18
19BASE = sys.argv[1] if len(sys.argv) > 1 else 'http://127.0.0.1:8080'
20OUT = Path('/workspace/allianties-shots')
21OUT.mkdir(parents=True, exist_ok=True)
22FAILS = []
23
24
25def check(cond, msg):
26 print((' ok ' if cond else ' FAIL ') + msg)
27 if not cond:
28 FAILS.append(msg)
29
30
31def shot(page, name):
32 page.screenshot(path=str(OUT / (name + '.png')), full_page=False)
33 print(' shot', OUT / (name + '.png'))
34
35
36def clock_point(page, minutes, radius_frac):
37 box = page.locator('#cf-clock svg').bounding_box()
38 scale = box['width'] / 320.0
39 ang = minutes / 1440.0 * 2 * math.pi - math.pi / 2
40 r = 128 * radius_frac * scale
41 return (box['x'] + 160 * scale + r * math.cos(ang), box['y'] + 160 * scale + r * math.sin(ang))
42
43
44def ranges(page):
45 return page.evaluate("() => (App.game.rules.ceasefire_ranges || []).map(r => r.start + '-' + r.end)")
46
47
48def mark_svg(page):
49 page.evaluate("() => { window.__cfSvg = document.querySelector('#cf-clock svg'); }")
50
51
52def same_svg(page):
53 return page.evaluate("() => document.querySelector('#cf-clock svg') === window.__cfSvg")
54
55
56def wait_saved(page):
57 page.wait_for_function("() => !App.rulesDirty && !App._rulesSaving", timeout=10000)
58
59
60def mouse_drag(page, m_from, m_to, frac, steps=16, poll_pause=False):
61 x, y = clock_point(page, m_from, frac)
62 page.mouse.move(x, y)
63 page.mouse.down()
64 ok = True
65 span = (m_to - m_from) % 1440
66 for i in range(1, steps + 1):
67 m = (m_from + span * i / steps) % 1440
68 px, py = clock_point(page, m, frac)
69 page.mouse.move(px, py)
70 page.wait_for_timeout(250 if poll_pause else 30)
71 ok = ok and same_svg(page) and page.evaluate("() => App._cfClock.active()")
72 page.mouse.up()
73 return ok
74
75
76def touch_drag(page, cdp, m_from, m_to, frac, steps=16, poll_pause=False):
77 def tp(m):
78 x, y = clock_point(page, m, frac)
79 return [{'x': x, 'y': y, 'id': 1}]
80 cdp.send('Input.dispatchTouchEvent', {'type': 'touchStart', 'touchPoints': tp(m_from)})
81 ok = True
82 span = (m_to - m_from) % 1440
83 for i in range(1, steps + 1):
84 m = (m_from + span * i / steps) % 1440
85 cdp.send('Input.dispatchTouchEvent', {'type': 'touchMove', 'touchPoints': tp(m)})
86 page.wait_for_timeout(250 if poll_pause else 30)
87 ok = ok and same_svg(page) and page.evaluate("() => App._cfClock.active()")
88 cdp.send('Input.dispatchTouchEvent', {'type': 'touchEnd', 'touchPoints': []})
89 return ok
90
91
92def churn(page3, code, times=1):
93 """Another player joins and leaves: bumps the lobby version → host polls see a change."""
94 for _ in range(times):
95 page3.goto(BASE + '/index.html?join=' + code, wait_until='domcontentloaded')
96 page3.wait_for_selector('#lobby:not([hidden])', timeout=10000)
97 page3.locator('#btn-leave').click()
98 page3.wait_for_timeout(300)
99
100
101def type_slowly(page, sel, keys, churn_fn, label):
102 page.locator(sel).focus()
103 page.keyboard.press('Control+A') # number input: replace; time input: first segment
104 page.wait_for_timeout(100)
105 kept = True
106 for k in keys:
107 if ':' in k:
108 # Mobile browsers set a time input through the native picker,
109 # not keystrokes: emulate that (value + input/change events).
110 page.locator(sel).evaluate(
111 "(el, v) => { el.value = v; el.dispatchEvent(new Event('input', {bubbles: true}));"
112 " el.dispatchEvent(new Event('change', {bubbles: true})); }", k)
113 else:
114 page.keyboard.type(k)
115 churn_fn()
116 page.wait_for_timeout(1600) # > one 3 s poll every two keys
117 active = page.evaluate("(s) => document.activeElement === document.querySelector(s)", sel)
118 kept = kept and active
119 check(kept, label + ': focus kept across polls while others join/leave')
120 print(' value after typing:', page.locator(sel).input_value())
121 return kept
122
123
124def run(p, mobile):
125 tag = 'mobile' if mobile else 'desktop'
126 print('== ' + tag)
127 browser = p.chromium.launch()
128 if mobile:
129 ctx_opts = dict(viewport={'width': 390, 'height': 844}, device_scale_factor=2, is_mobile=True, has_touch=True)
130 else:
131 ctx_opts = dict(viewport={'width': 1280, 'height': 900})
132 host_ctx = browser.new_context(locale='en-GB', timezone_id='Europe/Amsterdam', **ctx_opts)
133 guest_ctx = browser.new_context(locale='en-GB', timezone_id='Asia/Tokyo', **ctx_opts)
134 churn_ctx = browser.new_context(locale='en-GB', timezone_id='UTC')
135 page = host_ctx.new_page()
136 page.goto(BASE + '/auth.php?test=1', wait_until='networkidle')
137 page.wait_for_selector('#btn-create')
138 check('paranoia' in page.locator('.tagline').first.inner_text(), 'new tagline shown')
139 page.locator('#btn-create').click()
140 page.wait_for_selector('#lobby:not([hidden])')
141 code = page.locator('#lobby-code').inner_text().strip()
142 check(page.evaluate("() => App.game.rules.tz") == 'Europe/Amsterdam', 'lobby created with host zone')
143
144 guest = guest_ctx.new_page()
145 guest.goto(BASE + '/auth.php?test=2&next=' + quote('index.html?join=' + code, safe=''), wait_until='networkidle')
146 guest.wait_for_selector('#lobby:not([hidden])')
147 page3 = churn_ctx.new_page()
148 page3.goto(BASE + '/auth.php?test=3', wait_until='networkidle')
149
150 page.locator('#rule-ceasefire').check()
151 page.wait_for_selector('#ceasefire-editor:not([hidden])')
152 page.locator('#cf-clock').scroll_into_view_if_needed()
153 wait_saved(page)
154 mark_svg(page)
155
156 # 1. Paint 10:00 → 14:00 on the ring, slowly (so polls happen mid-drag).
157 cdp = host_ctx.new_cdp_session(page) if mobile else None
158 if mobile:
159 smooth = touch_drag(page, cdp, 600, 840, 0.8, steps=16, poll_pause=True)
160 else:
161 churn(page3, code)
162 smooth = mouse_drag(page, 600, 840, 0.8, steps=16, poll_pause=True)
163 check(smooth, 'paint drag: same SVG node and active drag on every move (%s)' % tag)
164 wait_saved(page)
165 check('10:00-14:00' in ranges(page), 'painted 10:00-14:00: %s' % ranges(page))
166 shot(page, tag + '-clock-painted')
167
168 # 2. Drag the end handle 14:00 → 16:00.
169 if mobile:
170 smooth = touch_drag(page, cdp, 840, 960, 1.0, steps=8)
171 else:
172 smooth = mouse_drag(page, 840, 960, 1.0, steps=8)
173 check(smooth, 'handle drag smooth (%s)' % tag)
174 wait_saved(page)
175 check(ranges(page) == ['10:00-16:00'], 'handle moved end to 16:00: %s' % ranges(page))
176 rows = page.evaluate("() => [...document.querySelectorAll('#cf-ranges li.cf-row input')].map(i => i.value)")
177 check(rows == ['10:00', '16:00'], 'time inputs follow the clock: %s' % rows)
178 # Snap: a drag that ends near 16:07 lands on 16:00 (15-minute grid).
179 page.wait_for_timeout(3500)
180 check(same_svg(page), 'clock SVG survives polls (patched in place)')
181
182 # 3. Typing keeps focus across polls (others join/leave meanwhile).
183 page.locator('#rule-ap-time').scroll_into_view_if_needed()
184 type_slowly(page, '#rule-ap-time', ['07:00', '07:15', '07:30'] if mobile else ['0', '7', '3', '0'],
185 lambda: churn(page3, code), 'AP time input')
186 page.locator('#lobby h1').click()
187 wait_saved(page)
188 page.wait_for_timeout(500)
189 check(page.evaluate("() => App.game.rules.ap_time") == '07:30', 'AP time saved 07:30')
190 shot(page, tag + '-lobby-host-edit')
191
192 page.locator('#cf-ranges li.cf-row input').first.scroll_into_view_if_needed()
193 type_slowly(page, '#cf-ranges li.cf-row input.cf-start', ['09:00', '09:30', '09:45'] if mobile else ['0', '9', '4', '5'],
194 lambda: churn(page3, code), 'cease-fire start input')
195 page.locator('#lobby h1').click()
196 wait_saved(page)
197 page.wait_for_timeout(500)
198 check(ranges(page) == ['09:45-16:00'], 'typed start saved: %s' % ranges(page))
199
200 type_slowly(page, '#rule-grid', ['1', '2'], lambda: churn(page3, code), 'grid size input')
201 page.locator('#lobby h1').click()
202 wait_saved(page)
203 check(page.evaluate("() => App.game.rules.grid") == 12, 'grid 12 saved')
204
205 # 4. Guest (Tokyo): read-only, converted to local time, API refuses (403).
206 guest.wait_for_timeout(3500)
207 guest.locator('#lobby-rules').scroll_into_view_if_needed()
208 check(guest.locator('#rules-host-only').is_visible(), 'guest sees "Only the host can change the rules."')
209 disabled = guest.evaluate("() => [...document.querySelectorAll('#lobby-rules input, #lobby-rules button')].every(e => e.disabled)")
210 check(disabled, 'guest: every rules input/button disabled')
211 g_ap = guest.locator('#rule-ap-time').input_value()
212 check(g_ap == '15:30', 'guest in Tokyo sees AP time 07:30 Amsterdam as 15:30: %s' % g_ap)
213 g_rows = guest.evaluate("() => [...document.querySelectorAll('#cf-ranges li.cf-row input')].map(i => i.value)")
214 check(g_rows == ['17:45', '00:00'], 'guest sees 09:45–16:00 Amsterdam as 17:45–00:00 Tokyo: %s' % g_rows)
215 check('Asia/Tokyo' in guest.locator('.tz-label').first.inner_text(), 'guest zone label: ' + guest.locator('.tz-label').first.inner_text())
216 status = guest.evaluate("""async () => {
217 const r = await fetch('api.php?action=lobby_rules', { method: 'POST', credentials: 'same-origin',
218 headers: { 'Content-Type': 'application/json', 'X-CSRF-TOKEN': Api.csrf },
219 body: JSON.stringify({ action: 'lobby_rules', game: App.game.id, rules: { jury: false } }) });
220 const d = await r.json();
221 return [r.status, d.error];
222 }""")
223 check(status == [403, 'not_host'], 'guest rule update refused with 403 not_host: %s' % status)
224 page.wait_for_timeout(3500)
225 check(page.evaluate("() => App.game.rules.jury") is True, 'rules unchanged after refused guest edit')
226 guest.locator('#ceasefire-editor').scroll_into_view_if_needed()
227 shot(guest, tag + '-lobby-guest-readonly-tokyo')
228 page.locator('#ceasefire-editor').scroll_into_view_if_needed()
229 shot(page, tag + '-lobby-host-clock')
230 browser.close()
231
232
233with sync_playwright() as p:
234 run(p, mobile=False)
235 run(p, mobile=True)
236
237print('\nFAILED: %d' % len(FAILS))
238for f in FAILS:
239 print(' - ' + f)
240sys.exit(1 if FAILS else 0)