BlueGit

projects-timfalken-com microchess

Files

microchess / web / tests / browser.mjs

browser.mjs

feat: scaffold Synhex hex tactics on the Microchess lobby shell
timfa project_86226080_bot_b6e0858ac0a12dc6d49a8d25b3b0be9b · pushed by timfa · 2 months ago
24f20754 History
browser.mjs 23.4 KiB Download Raw
1// Optional browser regression test; see README for setup. Uses an isolated app copy.
2import { chromium } from './artifacts/node_modules/playwright/index.mjs';
3import { mkdtemp, cp, mkdir, rm } from 'node:fs/promises';
4import { spawn, execFileSync } from 'node:child_process';
5import { fileURLToPath } from 'node:url';
6import path from 'node:path';
7import assert from 'node:assert/strict';
8const web=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
9const root=await mkdtemp(path.join(web,'tests/artifacts/browser-'));
10for(const f of ['api.php','index.php','auth.php','callback.php','router.php','sw.js','manifest.webmanifest','lib','assets'])await cp(path.join(web,f),path.join(root,f),{recursive:true,filter:source=>path.basename(source)!=='tablebase'});
11await mkdir(path.join(root,'data'));
12const port=18081;
13const server=spawn('php',['-S',`127.0.0.1:${port}`,'-t',root,path.join(root,'router.php')],{stdio:'ignore'});
14const base=`http://127.0.0.1:${port}`;
15let browser;
16try{
17 for(let i=0;i<100;i++){try{await fetch(base);break;}catch{await new Promise(r=>setTimeout(r,50));}}
18 browser=await chromium.launch({headless:true,args:['--no-sandbox']});
19 const ca=await browser.newContext({viewport:{width:1440,height:1080}}),cb=await browser.newContext({viewport:{width:1440,height:1080}});
20 const a=await ca.newPage(),b=await cb.newPage(),errors=[];
21 for(const p of[a,b]){p.on('pageerror',e=>errors.push(e.message));p.on('console',m=>{if(m.type()==='error')errors.push(m.text());});}
22 await a.goto(base);
23 const intro=a.locator('#notification-dialog');
24 await intro.waitFor({state:'visible'});
25 assert.equal(await intro.locator('p').innerText(),"Do you want to be notified when it's your turn? Enable the Notification setting in the Account Settings panel at the top right of the page.",'Exact once-only notification introduction');
26 await intro.getByRole('button',{name:'Got it',exact:true}).click();
27 await a.reload();await a.locator('#avatar-button').waitFor();
28 assert.equal(await intro.isVisible(),false,'Introduction stays dismissed after reload');
29 await b.goto(base);await b.locator('#avatar-button').waitFor();
30 assert.equal(await b.locator('#notification-dialog').isVisible(),false,'Introduction is remembered across browser profiles');
31 await a.evaluate(()=>{
32 const request=Notification.requestPermission,subscribe=PushManager.prototype.subscribe,permission=Object.getOwnPropertyDescriptor(Notification,'permission');
33 window.restoreNotificationMocks=()=>{Notification.requestPermission=request;PushManager.prototype.subscribe=subscribe;Object.defineProperty(Notification,'permission',permission);delete navigator.brave;};
34 Object.defineProperty(Notification,'permission',{get:()=>'granted',configurable:true});
35 Notification.requestPermission=async()=>'granted';
36 PushManager.prototype.subscribe=async()=>{throw new DOMException('Registration failed - push service error','AbortError');};
37 Object.defineProperty(navigator,'brave',{value:{isBrave:async()=>true},configurable:true});
38 });
39 await a.locator('#settings-button').click();
40 await a.locator('[data-toggle-push]').click();
41 await intro.getByRole('heading',{name:'Enabling notifications failed'}).waitFor();
42 assert((await intro.innerText()).includes('This may be due to Brave'),'Brave advice does not assert an unproven cause');
43 assert.equal(await intro.locator('#push-settings-page').inputValue(),'brave://settings/privacy','Concrete Brave settings page');
44 assert((await intro.innerText()).includes('Use Google services for push messaging'),'Concrete Brave setting');
45 assert(await a.locator('#modal').evaluate(el=>el.open),'Account dialog remains open underneath error');
46 await a.screenshot({path:path.join(web,'tests/artifacts/notification-error-desktop.png')});
47 await a.keyboard.press('Escape');
48 await intro.waitFor({state:'hidden'});
49 assert(await a.locator('#modal').evaluate(el=>el.open),'Escape only closes the top dialog');
50 assert(await a.locator('[data-toggle-push]').evaluate(el=>el===document.activeElement),'Focus returns to notification setting');
51 await a.evaluate(()=>{navigator.brave.isBrave=async()=>false;});
52 await a.locator('[data-toggle-push]').click();
53 await intro.getByRole('heading',{name:'Enabling notifications failed'}).waitFor();
54 assert((await intro.innerText()).includes('If you use Brave'),'Other browsers get conditional Brave advice');
55 await a.setViewportSize({width:390,height:844});
56 assert(await intro.evaluate(el=>el.getBoundingClientRect().width<=innerWidth),'Error fits a mobile viewport');
57 await a.screenshot({path:path.join(web,'tests/artifacts/notification-error-mobile.png')});
58 await intro.getByRole('button',{name:'Got it',exact:true}).click();
59 await a.setViewportSize({width:1440,height:1080});
60 await a.evaluate(()=>window.restoreNotificationMocks());
61 await a.locator('#modal-close').click();
62 await a.locator('#avatar-button').click();
63 await a.locator('[data-avatar-choice="blue-knight"]').waitFor();
64 await a.locator('[data-avatar-group="fairy"]').click();
65 assert.equal(await a.locator('.avatar-choice').count(),67,'Retained fairy collection is selectable');
66 await a.locator('#avatar-color').selectOption('Pink');
67 assert.equal(await a.locator('.avatar-choice').count(),3,'All pink fairy pieces are present');
68 await a.locator('[data-avatar-choice="pink-ferz"]').click();
69 await a.locator('#avatar-button img[src$="pink-ferz.png"]').waitFor();
70 await a.reload();
71 await a.locator('#avatar-button img[src$="pink-ferz.png"]').waitFor();
72 await a.locator('#avatar-button').click();
73 await a.locator('[data-avatar-choice="blue-knight"]').waitFor();
74
75 await a.locator('[data-avatar-group="standard"]').click();
76 await a.locator('#avatar-color').selectOption('White');
77 assert.equal(await a.locator('.avatar-choice').count(),6,'Six white standard chess pieces');
78 await a.locator('#avatar-color').selectOption('Black');
79 assert.equal(await a.locator('.avatar-choice').count(),6,'Six black standard chess pieces');
80 await a.locator('#avatar-color').selectOption('Blue');
81 assert.equal(await a.locator('.avatar-choice').count(),6,'Six blue standard chess pieces');
82 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-desktop.png')});
83 await a.locator('[data-avatar-choice="blue-knight"]').click();
84 await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();
85 await a.reload();await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();
86 await b.locator('#settings-button').click();await b.getByRole('button',{name:'Switch to test_user_2'}).click();
87 await b.locator('#account-summary').getByText('test_user_2',{exact:false}).waitFor();
88 await b.locator('#notification-dialog').getByRole('button',{name:'Got it',exact:true}).click();
89 await a.locator('#friend-link').click();await a.locator('#share-url').waitFor();
90 const friendLink=await a.locator('#share-url').inputValue();
91 await a.locator('#modal-close').click();
92 await b.goto(friendLink);await b.getByRole('button',{name:'Accept',exact:true}).click();
93 await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor();
94 await b.locator('#friend-list [data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor();
95 await a.locator('#friend-list [data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click();
96 await b.getByRole('button',{name:'Accept',exact:true}).click();
97 await a.locator('.board').waitFor();await b.locator('.board').waitFor();
98 await b.locator('.card-header img[src$="blue-knight.png"]').waitFor();
99 async function state(p){return p.evaluate(async()=>{const r=await fetch('api.php');return r.json();});}
100 async function post(p,action,fields={}){return p.evaluate(async({action,fields})=>{const s=await(await fetch('api.php')).json();const r=await fetch('api.php',{method:'POST',headers:{'Content-Type':'application/json','X-CSRF-Token':s.csrf},body:JSON.stringify({action,...fields})});const out=await r.json();if(!r.ok)throw Error(out.error);return out;},{action,fields});}
101 const initial=await state(a),id=initial.games[0].id;
102 await a.goto(`${base}/?game=${id}`);
103 await a.locator(`[data-game="${id}"] .notification-highlight`).waitFor();
104 assert.equal(new URL(a.url()).searchParams.has('game'),false,'Notification link is consumed after loading games');
105 assert.equal(await a.locator('#modal').evaluate(el=>el.open),false,'Notification opens the home screen');
106 await a.evaluate(()=>renderGames());
107 assert.equal(await a.locator('.notification-highlight').count(),1,'Highlight survives rerender');
108 await a.locator('.notification-highlight').waitFor({state:'detached'});
109 await a.evaluate(()=>renderGames());
110 assert.equal(await a.locator('.notification-highlight').count(),0,'Highlight does not repeat on polling');
111 await a.emulateMedia({reducedMotion:'reduce'});
112 await a.goto(`${base}/?game=${id}`);
113 await a.locator('.notification-highlight-static').waitFor();
114 await a.emulateMedia({reducedMotion:'no-preference'});
115 await a.locator('.notification-highlight').waitFor({state:'detached'});
116 const manifest=await (await fetch(`${base}/manifest.webmanifest`)).json();
117 assert.equal(manifest.start_url,'./','Manifest supports deployment in a subdirectory');
118 assert.equal(manifest.name,'Synhex','PWA is branded Synhex');
119 assert(await a.evaluate(async()=>!!(await navigator.serviceWorker.ready).active),'Service worker activates');
120 const white=initial.games[0].color==='w'?a:b,black=white===a?b:a;
121 await white.locator(`[data-game="${id}"] .hex-board`).waitFor();
122 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting strength gives 50/50');
123 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Strength orientation is the same for Black');
124 await white.locator(`[data-game="${id}"] [data-game-action="commit"]`).click();
125 await white.locator(`#waiting-games [data-game="${id}"]`).waitFor();
126 assert.equal(await black.locator(`[data-game="${id}"] [data-game-action="commit"]`).count(),1,'Opponent can still lock after the first plan');
127 await black.locator(`[data-game="${id}"] [data-game-action="commit"]`).click();
128 await white.locator(`[data-game="${id}"] [data-game-action="play"]`).waitFor();
129 await black.locator(`[data-game="${id}"] [data-game-action="play"]`).waitFor();
130 await white.locator(`[data-game="${id}"] [data-game-action="play"]`).click();
131 await black.locator(`[data-game="${id}"] [data-game-action="play"]`).click();
132 await white.evaluate(() => {
133 window.savedFlights = 0;
134 const original = Element.prototype.animate;
135 Element.prototype.animate = function (...args) { if (this.classList.contains('saved-hourglass')) window.savedFlights++; return original.apply(this, args); };
136 });
137 await white.locator(`[data-game="${id}"] [data-game-action="options"]`).click();
138 await white.getByRole('button',{name:'Resign…'}).click();
139 await white.getByRole('button',{name:'Resign',exact:true}).click();
140 await white.getByRole('heading',{name:/You won|You lost|A game well matched/}).waitFor();
141 for(const page of [white,black]){
142 await page.locator('.end-content').waitFor();
143 assert.equal(await page.locator('.ended-board .hex-board').count(),1,'Final hex board remains visible for both players');
144 }
145 await white.locator('#history-button').click();
146 await white.locator('.history-entry').waitFor();
147 await white.locator('.history-entry').first().click();
148 await white.locator('#replay-card .board').waitFor();
149 assert.equal(await white.locator('.replay-controls button').count(),5,'Replay has start, step, play, step and end controls');
150 await white.locator('[data-replay-control="end"]').click();
151 await white.locator('[data-replay-control="start"]').click();
152 assert.match(await white.locator('#replay-progress').innerText(),/^0 \//,'Jump to start returns to beginning');
153 assert.equal(await white.locator('#replay-card .material-bar').count(),0,'Replay replaces opponent header and material bar');
154 assert.equal(await white.locator('.replay-players img[alt="White"]').count(),1,'White king identifies white player');
155 assert.equal(await white.locator('.replay-players img[alt="Black"]').count(),1,'Black king identifies black player');
156 await white.context().grantPermissions(['clipboard-read','clipboard-write']);
157 await white.locator('#replay-share').click();
158 const replayUrl=await white.evaluate(()=>navigator.clipboard.readText());
159 assert.match(replayUrl,/\?replay=[a-f0-9]{48}$/,'Chain button copies a share URL');
160 const guestContext=await browser.newContext(),guest=await guestContext.newPage();
161 guest.on('pageerror',e=>errors.push(e.message));
162 await guest.goto(replayUrl);
163 await guest.locator('#replay-card .board').waitFor();
164 assert.equal(await guest.locator('.replay-players').innerText(),await white.locator('.replay-players').innerText(),'Shared page identifies both players');
165 assert.equal(await guest.locator('#history-return').count(),0,'Public replay has no private history navigation');
166 assert.equal(await guest.locator('.replay-bottom a[href="./"]').innerText(),'Synhex ↗','Public replay links to the home page');
167 assert.equal(await guest.locator('dialog, #modal-close, .topbar, .login, #sidebar').count(),0,'Standalone replay has no dialog, close button or background UI');
168 await guest.keyboard.press('Escape');
169 await guest.locator('#replay-card .board').waitFor();
170 await guest.locator('body').click({position:{x:4,y:4}});
171 await guest.locator('#replay-card .board').waitFor();
172 await guest.setViewportSize({width:390,height:844});
173 assert(await guest.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'Standalone replay fits mobile width');
174 await guest.screenshot({path:path.join(web,'tests/artifacts/shared-replay-mobile.png')});
175 await guest.reload();
176 await guest.locator('#replay-card .board').waitFor();
177 await guestContext.close();
178 await black.goto(replayUrl);
179 await black.locator('#replay-card .board').waitFor();
180 assert.equal(await black.locator('#replay-page').count(),1,'Signed-in visitor sees the standalone shared replay');
181 assert.equal(await black.locator('.topbar, .login, #sidebar, #your-games').count(),0,'Signed-in shared replay has no account chrome');
182 await black.goto(base);
183 await black.locator('#your-games').waitFor();
184 await white.screenshot({path:path.join(web,'tests/artifacts/game-replay.png')});
185 await white.locator('#modal-close').click();
186 await white.evaluate(()=>refresh(true));
187 await white.getByRole('button',{name:'Rematch',exact:true}).click();
188 await white.locator(`#waiting-games [data-game="${id}"]`).waitFor();
189 assert.equal(await white.locator(`#your-games [data-game="${id}"]`).count(),0,'Requested rematch leaves Your Turn');
190 await black.getByText(/wants a rematch/).waitFor();
191 assert.equal(await black.locator(`#your-games [data-game="${id}"]`).count(),1,'Opponent rematch offer stays in Your Turn');
192 await black.getByRole('button',{name:'Rematch',exact:true}).click();
193 await white.locator('.board').waitFor();
194 assert.equal((await state(white)).games[0].color,'b','Rematch flips colors');
195 // Three real game links for desktop layout coverage.
196 for(let i=0;i<3;i++){const link=await post(a,'create_link',{kind:'match'});await post(b,'accept_link',{token:new URL(link.url).searchParams.get('invite')});}
197 await a.reload();await a.locator('.game-card').nth(3).waitFor();
198 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
199 assert(await a.locator('.hex-board image').count()>0,'Hex units render');
200 await a.setViewportSize({width:1440,height:640});
201 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
202 const sidebar=await a.locator('#sidebar').boundingBox();
203 assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`);
204 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
205 const staleId=(await state(a)).games[0].id;
206 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$db->exec('UPDATE games SET activity_at=unixepoch()-8*86400 WHERE id='.(int)$argv[2]);`,path.join(root,'data/synhex.sqlite'),String(staleId)]);
207 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
208 await a.getByText('This game has been inactive for 8 days. Would you like to stop it?').waitFor();
209 await a.getByRole('button',{name:'Cancel',exact:true}).click();
210 assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game');
211 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
212 await a.getByRole('button',{name:'Stop game',exact:true}).click();
213 await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
214 await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
215 await a.setViewportSize({width:390,height:844});
216 assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'No mobile horizontal overflow');
217 assert.equal(await a.locator('#your-games').evaluate(e=>getComputedStyle(e).gridTemplateColumns.split(' ').length),1,'One tile column');
218 await a.locator('#friends-toggle').click();await a.locator('#sidebar.open').waitFor();await a.waitForTimeout(250);
219 await a.locator('#avatar-button').click();
220 await a.locator('[data-avatar-group="fairy"]').click();
221 await a.locator('#avatar-color').selectOption('Purple');
222 await a.locator('[data-avatar-choice="purple-elephant"]').waitFor();
223 await a.locator('.avatar-choice img').evaluateAll(imgs=>Promise.all(imgs.map(i=>i.decode())));
224 assert(await a.locator('.avatar-choice img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'Fairy avatars load');
225 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-mobile.png')});
226 await a.locator('[data-avatar-choice="purple-elephant"]').click();
227 await a.locator('#avatar-button img[src$="purple-elephant.png"]').waitFor();
228 await a.screenshot({path:path.join(web,'tests/artifacts/mobile-friends.png'),fullPage:false});
229 await a.locator('#friends-close').click();await a.waitForTimeout(250);await a.screenshot({path:path.join(web,'tests/artifacts/mobile.png'),fullPage:true});
230 // Touch events exercise the mobile pointer path, not mouse emulation.
231 const sa=await state(a),sb=await state(b);
232 const owner=sa.games.some(g=>g.yourTurn)?a:b;
233 const mobileContext=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,storageState:await owner.context().storageState()});
234 const touch=await mobileContext.newPage();await touch.goto(base);
235 const tg=(await state(touch)).games.find(g=>g.yourTurn);
236 await touch.locator(`[data-game="${tg.id}"] [data-game-action="commit"]`).click();
237 await touch.locator(`#waiting-games [data-game="${tg.id}"]`).waitFor();
238 await mobileContext.close();
239 // New game offers matchmaking below the link, with persistent cancellation.
240 await a.setViewportSize({width:1440,height:1080});
241 await a.locator('#match-link').click();
242 await a.getByRole('button',{name:'Challenge a random player',exact:true}).waitFor();
243 const linkBox=await a.locator('#share-url').boundingBox();
244 const matchBox=await a.getByRole('button',{name:'Challenge a random player',exact:true}).boundingBox();
245 assert(matchBox.y>linkBox.y,'Random challenge is below invite link');
246 await a.getByRole('button',{name:'Challenge a random player',exact:true}).click();
247 await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor();
248 await a.reload();
249 await a.getByRole('button',{name:'Cancel search',exact:true}).waitFor();
250 await a.locator('#match-link').click();
251 await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).waitFor();
252 await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).click();
253 await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'});
254 await a.locator('#match-link').click();
255 await a.getByRole('button',{name:'Challenge a random player',exact:true}).click();
256 await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor();
257 const priorIds=new Set((await state(a)).games.map(g=>g.id));
258 await b.locator('#match-link').click();
259 await b.getByRole('button',{name:'Challenge a random player',exact:true}).click();
260 await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'});
261 const randomGame=(await state(a)).games.find(g=>!priorIds.has(g.id));
262 assert(randomGame,'Matchmaking creates a new game');
263 for(const p of[a,b]) await p.locator(`[data-game="${randomGame.id}"] .board`).waitFor();
264 assert.match(await a.locator('#account-summary').innerText(),/\d+ Elo/,'Own rating is visible');
265 assert.equal(await a.locator(`[data-game="${randomGame.id}"] .rating`).innerText(),String(randomGame.opponentRating),'Opponent rating is visible');
266 // The same rivalry modal is available from a game and the friends list.
267 await post(a,'remove_friend',{friend:'local:test_user_2'});
268 await a.reload();
269 await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
270 const rivalryStats=await a.locator('.stats').innerText();
271 await a.getByRole('button',{name:'Send friend request',exact:true}).click();
272 await a.locator('#modal').waitFor({state:'hidden'});
273 await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
274 assert(await a.getByRole('button',{name:'Friend request sent',exact:true}).isDisabled(),'Sender sees pending status');
275 await a.locator('#modal-close').click();
276 await b.locator('#friend-requests').getByRole('button',{name:'Reject',exact:true}).click();
277 await b.locator('.friend-request').waitFor({state:'detached'});
278 await a.reload();
279 await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
280 await a.getByRole('button',{name:'Send friend request',exact:true}).click();
281 await b.reload();
282 await b.setViewportSize({width:390,height:844});
283 await b.locator('#friends-toggle').click();
284 await b.locator('#friend-requests').getByRole('button',{name:'Accept',exact:true}).click();
285 await b.locator('#friend-list [data-friend="local:test_user_1"]').waitFor();
286 await b.locator('.friend-request').waitFor({state:'detached'});
287 await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor();
288 await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
289 assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Game modal retains rivalry history');
290 await a.getByRole('button',{name:'Challenge to a game'}).waitFor();
291 await a.locator('#modal-close').click();
292 await a.locator('#friend-list [data-friend="local:test_user_2"]').click();
293 assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Friend and game modals show identical statistics');
294 await a.locator('#modal-close').click();
295 assert.deepEqual(errors,[],'No browser errors');
296 console.log('Browser: friendship, challenge, hex plan/playback, rematch, desktop and mobile checks passed.');
297}finally{
298 await browser?.close();if(server.exitCode===null && server.signalCode===null){const exited=new Promise(r=>server.once('exit',r));server.kill();await exited;}await rm(root,{recursive:true,force:true});
299}