BlueGit

projects-timfalken-com allianties

Files

allianties / test / avatar-layout-playwright.py

avatar-layout-playwright.py

avatar-layout-playwright.py 9.7 KiB Download Raw
1#!/usr/bin/env python3
2"""t1179/t1180 real-browser checks.
3
4- Players without a profile picture (null avatar) and with a picture URL that
5 404s are visible on the board as a coloured circle with initials, stay
6 visible across several 3 s polls and after taps; also in the lobby list
7 and the menu.
8- The game view fits the viewport on mobile (412x915, 390x844, 460x1000)
9 and desktop: no page scroll, the header does not overlap the HUD, the
10 timeline is fully on screen and not covered by the language button.
11Usage: python3 test/avatar-layout-playwright.py [BASE]
12"""
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 / ('t1179-' + name + '.png')), full_page=False)
33 print(' shot', OUT / ('t1179-' + name + '.png'))
34
35
36TOKENS_JS = """() => Array.from(document.querySelectorAll('#board .cell .piece')).map(el => {
37 const r = el.getBoundingClientRect(); const cs = getComputedStyle(el);
38 const ini = el.querySelector('.piece-initials');
39 const img = el.querySelector('img');
40 return { w: r.width, h: r.height, vis: cs.visibility, op: parseFloat(cs.opacity), disp: cs.display,
41 bg: cs.backgroundColor, ini: ini ? ini.textContent : null,
42 iniVis: ini ? getComputedStyle(ini).visibility : null,
43 img: !!img, hasImg: el.classList.contains('has-img'), label: el.getAttribute('aria-label') };
44})"""
45
46LAYOUT_JS = """() => {
47 const se = document.scrollingElement;
48 const before = se.scrollTop; window.scrollTo(0, 400); const after = se.scrollTop; window.scrollTo(0, 0);
49 const rb = id => { const e = document.getElementById(id); if (!e || e.hidden) return null; const r = e.getBoundingClientRect(); return {t: r.top, b: r.bottom, l: r.left, r: r.right}; };
50 return { vh: innerHeight, vw: innerWidth, sh: se.scrollHeight, sw: se.scrollWidth, scrolled: after - before,
51 top: rb('top-bar'), hud: rb('game-hud'), board: rb('board'), tl: rb('timeline'),
52 live: rb('tl-live'), lang: rb('lang-current') };
53}"""
54
55
56def visible_tokens(page, label):
57 toks = page.evaluate(TOKENS_JS)
58 ok = [t for t in toks if t['w'] > 16 and t['h'] > 16 and t['vis'] == 'visible' and t['op'] > 0.5 and t['disp'] != 'none'
59 and (t['hasImg'] or (t['ini'] and t['iniVis'] == 'visible'))]
60 check(len(toks) == 3 and len(ok) == 3, '%s: 3 visible tokens (%d/%d) %s' % (label, len(ok), len(toks),
61 [(t['label'], t['ini'], t['hasImg'], round(t['w'])) for t in toks]))
62 return toks
63
64
65def check_layout(page, label):
66 L = page.evaluate(LAYOUT_JS)
67 check(L['sh'] <= L['vh'] + 1 and L['scrolled'] == 0, '%s: no vertical page scroll (scrollHeight %d, viewport %d)' % (label, L['sh'], L['vh']))
68 check(L['sw'] <= L['vw'] + 1, '%s: no horizontal overflow (%d > %d)' % (label, L['sw'], L['vw']))
69 check(L['top']['b'] <= L['hud']['t'] + 0.5, '%s: header (bottom %.0f) above HUD (top %.0f)' % (label, L['top']['b'], L['hud']['t']))
70 check(L['tl']['b'] <= L['vh'] + 0.5, '%s: timeline on screen (bottom %.0f / %d)' % (label, L['tl']['b'], L['vh']))
71 lv, lg = L['live'], L['lang']
72 overlap = lg and not (lv['r'] <= lg['l'] or lv['l'] >= lg['r'] or lv['b'] <= lg['t'] or lv['t'] >= lg['b'])
73 check(not overlap, '%s: Live button not covered by the language button' % label)
74 tb = L['top']
75 hits = page.evaluate("""() => { const r = document.getElementById('lang-current').getBoundingClientRect();
76 const ids = ['top-title', 'ap-hms', 'day-label', 'game-hud'];
77 return ids.filter(id => { const e = document.getElementById(id); if (!e) return false; let q = e.getBoundingClientRect();
78 if (id === 'game-hud') { return !(q.top >= r.bottom); }
79 const rg = document.createRange(); rg.selectNodeContents(e); q = rg.getBoundingClientRect(); return [e].some(k => !(q.right <= r.left || q.left >= r.right || q.bottom <= r.top || q.top >= r.bottom)); }); }""")
80 check(not hits, '%s: language button overlaps nothing (%s)' % (label, hits))
81 tr = page.evaluate("() => document.getElementById('tl-track').getBoundingClientRect().width")
82 check(tr >= 100, '%s: timeline track usable width (%.0f px)' % (label, tr))
83 check(L['board']['b'] - L['board']['t'] > 150, '%s: board has a usable size (%.0f px)' % (label, L['board']['b'] - L['board']['t']))
84 return L
85
86
87VIEWPORTS = [
88 ('mobile-412x915', dict(viewport={'width': 412, 'height': 915}, device_scale_factor=2.6, is_mobile=True, has_touch=True)),
89 ('mobile-390x844', dict(viewport={'width': 390, 'height': 844}, device_scale_factor=3, is_mobile=True, has_touch=True)),
90 ('mobile-460x1000', dict(viewport={'width': 460, 'height': 1000}, device_scale_factor=2.35, is_mobile=True, has_touch=True)),
91 ('desktop-1280x800', dict(viewport={'width': 1280, 'height': 800})),
92]
93
94
95def main():
96 with sync_playwright() as p:
97 browser = p.chromium.launch()
98 host_ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **VIEWPORTS[0][1])
99 host = host_ctx.new_page()
100 host.goto(BASE + '/auth.php?test=1', wait_until='networkidle')
101 host.wait_for_selector('#btn-create')
102 host.locator('#btn-create').click()
103 host.wait_for_selector('#lobby:not([hidden])')
104 code = host.locator('#lobby-code').inner_text().strip()
105 guests = []
106 for n, mode in ((5, "none"), (6, "broken")):
107 ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **VIEWPORTS[1][1])
108 g = ctx.new_page()
109 g.goto(BASE + '/auth.php?test=%d&avatar=%s&next=%s' % (n, mode, quote('index.html?join=' + code, safe='')), wait_until='networkidle')
110 g.wait_for_selector('#lobby:not([hidden])')
111 guests.append(g)
112 host.wait_for_function("() => App.game && App.game.players.length === 3", timeout=10000)
113 host.wait_for_timeout(500)
114 lobby_toks = host.evaluate("""() => Array.from(document.querySelectorAll('#lobby-players .piece')).map(el => {
115 const r = el.getBoundingClientRect(); const i = el.querySelector('.piece-initials');
116 return { w: r.width, ini: i && i.textContent, iniVis: i && getComputedStyle(i).visibility, hasImg: el.classList.contains('has-img') }; })""")
117 check(len(lobby_toks) == 3 and all(abs(t['w'] - 40) < 1 and (t['hasImg'] or t['iniVis'] == 'visible') for t in lobby_toks),
118 'lobby list: all 3 players visible %s' % lobby_toks)
119 shot(host, 'lobby-list-host')
120 g9 = guests[0]
121 mv = g9.evaluate("() => { const e = document.querySelector('#menu-avatar .piece'); return e ? e.getBoundingClientRect().width : 0; }")
122 check(True, 'guest without avatar in lobby (menu avatar width %s, menu hidden on lobby)' % mv)
123 host.locator('#btn-start').click()
124 host.wait_for_selector('#game:not([hidden])')
125 host.wait_for_timeout(800)
126 gid = host.evaluate("() => App.game.id")
127
128 # Host view on each viewport (resize the same page, plus a fresh context per viewport).
129 for name, opts in VIEWPORTS:
130 ctx = browser.new_context(locale='nl-NL', timezone_id='Europe/Amsterdam', **opts)
131 pg = ctx.new_page()
132 pg.goto(BASE + '/auth.php?test=1&next=' + quote('index.html', safe=''), wait_until='networkidle')
133 pg.wait_for_selector('#btn-create')
134 pg.evaluate("(id) => App.openGame(id, 'running')", gid)
135 pg.wait_for_selector('#game:not([hidden])')
136 pg.wait_for_timeout(800)
137 visible_tokens(pg, name + ' initial')
138 check_layout(pg, name)
139 shot(pg, name + '-game')
140 # Survive polls (3 s each).
141 pg.wait_for_timeout(7000)
142 visible_tokens(pg, name + ' after 2 polls')
143 # Tap / click an opponent, close the sheet, still visible.
144 opp = pg.locator('#board .cell:has(.piece:not(.has-img))').first
145 opp.click()
146 pg.wait_for_timeout(300)
147 if pg.locator('#sheet:not([hidden])').count():
148 shot(pg, name + '-opponent-menu')
149 pg.locator('#sheet-close').click()
150 pg.wait_for_timeout(3500)
151 visible_tokens(pg, name + ' after tap + poll')
152 check_layout(pg, name + ' after interaction')
153 ctx.close()
154
155 # Avatar-less players' own views (null avatar, broken avatar URL) on mobile.
156 for g, label in ((guests[0], 'no-avatar-player'), (guests[1], 'broken-avatar-player')):
157 g.reload(wait_until='networkidle')
158 if g.locator('#game:not([hidden])').count() == 0:
159 g.wait_for_selector('#game:not([hidden])', timeout=10000)
160 g.wait_for_timeout(800)
161 visible_tokens(g, label + ' own view')
162 check_layout(g, label + ' 390x844')
163 shot(g, label + '-390x844')
164 # Menu avatar for the no-avatar user.
165 g9.locator('#btn-settings').click()
166 g9.locator('#btn-to-menu').click()
167 g9.wait_for_selector('#menu:not([hidden])')
168 mt = g9.evaluate("() => { const e = document.querySelector('#menu-avatar .piece'); if (!e) return null; const r = e.getBoundingClientRect(); return { w: r.width, ini: e.querySelector('.piece-initials').textContent }; }")
169 check(mt and abs(mt['w'] - 32) < 1 and mt['ini'], 'menu shows initials avatar for no-avatar user: %s' % mt)
170 shot(g9, 'menu-no-avatar')
171 browser.close()
172 print('FAILED:', len(FAILS))
173 for f in FAILS:
174 print(' -', f)
175 sys.exit(1 if FAILS else 0)
176
177
178if __name__ == '__main__':
179 main()