BlueGit

projects-timfalken-com microchess

Files

microchess / web / tests / browser.mjs

browser.mjs

effects
timfa Tim Falken · pushed by timfa · 2 months ago
d82deb2f History
browser.mjs 16.8 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','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);await b.goto(base);
23 await a.locator('#avatar-button').click();
24 await a.locator('[data-avatar-choice="blue-knight"]').waitFor();
25 await a.locator('[data-avatar-group="standard"]').click();
26 await a.locator('#avatar-color').selectOption('Blue');
27 assert.equal(await a.locator('.avatar-choice').count(),6,'Six blue standard chess pieces');
28 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-desktop.png')});
29 await a.locator('[data-avatar-choice="blue-knight"]').click();
30 await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();
31 await a.reload();await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();
32 await b.locator('#settings-button').click();await b.getByRole('button',{name:'Switch to test_user_2'}).click();
33 await b.locator('#account-summary').getByText('test_user_2',{exact:false}).waitFor();
34 await a.locator('#friend-link').click();await a.locator('#share-url').waitFor();
35 const friendLink=await a.locator('#share-url').inputValue();
36 await a.locator('#modal-close').click();
37 await b.goto(friendLink);await b.getByRole('button',{name:'Accept',exact:true}).click();
38 await a.locator('[data-friend="local:test_user_2"]').waitFor();
39 await b.locator('[data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor();
40 await a.locator('[data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click();
41 await b.getByRole('button',{name:'Accept',exact:true}).click();
42 await a.locator('.board').waitFor();await b.locator('.board').waitFor();
43 await b.locator('.card-header img[src$="blue-knight.png"]').waitFor();
44 async function state(p){return p.evaluate(async()=>{const r=await fetch('api.php');return r.json();});}
45 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});}
46 const initial=await state(a),id=initial.games[0].id;
47 const white=initial.games[0].color==='w'?a:b,black=white===a?b:a;
48 await white.locator(`[data-game="${id}"] [data-square="15"]`).click();
49 assert.equal(await white.locator(`[data-game="${id}"] .legal`).count(),1,'Pawn legal dot');
50 await white.locator(`[data-game="${id}"] [data-square="11"]`).click();
51 const held=white.locator(`#your-games [data-game="${id}"]`);
52 await held.locator('[data-square="11"]:disabled').waitFor();
53 const heldAt=Date.now(),heldRect=await held.boundingBox();
54 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting material gives 50/50');
55 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Material orientation is the same for Black');
56 assert.equal(await held.locator('.move-feedback').count(),0,'Quiet opening move receives no pulse');
57 assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board');
58 await white.waitForTimeout(2200);
59 assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause');
60 assert.equal(await held.locator('.move-feedback').count(),0,'Feedback stops after one event');
61 await white.evaluate(()=>renderGames());
62 assert.equal(await held.locator('.move-feedback').count(),0,'Rerender does not replay feedback');
63 assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position');
64 const relocated=white.locator(`#waiting-games [data-game="${id}"]`);
65 await relocated.waitFor({state:'attached'});
66 assert(Date.now()-heldAt>=2800,'Tile waits approximately three seconds before relocating');
67 assert(await relocated.evaluate(el=>el.getAnimations().length>0),'Tile animates to the waiting grid');
68 await relocated.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));
69 await black.locator(`[data-game="${id}"] [data-square="4"]:not([disabled])`).waitFor();
70 assert.equal(await white.locator('#waiting-games .square:not([disabled])').count(),0,'Waiting board inert');
71 // Actual pointer drag.
72 const from=await black.locator(`[data-game="${id}"] [data-square="4"]`).boundingBox();
73 const to=await black.locator(`[data-game="${id}"] [data-square="8"]`).boundingBox();
74 await black.mouse.move(from.x+from.width/2,from.y+from.height/2);await black.mouse.down();await black.mouse.move(to.x+to.width/2,to.y+to.height/2,{steps:8});await black.mouse.up();
75 await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor();
76 assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved');
77 // Real tactical evaluations, using board fixtures only in this disposable game database.
78 async function tacticalFixture(pieces){
79 const board=Array(20).fill('.');for(const [i,piece] of Object.entries(pieces))board[Number(i)]=piece;
80 const position={board,turn:'w',halfmove:0,ply:2,history:[board.join('')+'w'],last:null};
81 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(position),String(id)]);
82 await white.evaluate(()=>refresh(true));
83 }
84 for(const [quality,pieces,reduced] of [
85 ['good',{19:'K',3:'k',12:'R',8:'q'},false],
86 ['poor',{19:'K',1:'k',12:'Q',8:'p',0:'r'},false],
87 ['good',{19:'K',3:'k',12:'R',8:'q'},true],
88 ]){
89 await white.emulateMedia({reducedMotion:reduced?'reduce':'no-preference'});
90 await tacticalFixture(pieces);
91 await white.locator(`[data-game="${id}"] [data-square="12"]:not([disabled])`).click();
92 const started=Date.now();
93 await white.locator(`[data-game="${id}"] [data-square="8"]`).click();
94 const pulse=white.locator(`[data-game="${id}"] .move-feedback.${quality}`);
95 await pulse.waitFor({state:'attached'});
96 assert(Date.now()-started<3000,'Actual API feedback arrives within tile pause locally');
97 assert.equal(await black.locator('.move-feedback').count(),0,'Only the mover receives feedback');
98 const bar=white.locator(`[data-game="${id}"] .material-bar`),fill=bar.locator('.material-white');
99 assert.equal(await bar.getAttribute('aria-valuenow'),quality==='good'?'100':'64','Captured material updates the bar');
100 if(reduced){
101 assert.equal(await pulse.evaluate(el=>el.getAnimations().length),0,'Reduced motion shows static feedback');
102 assert.equal(await fill.evaluate(el=>el.getAnimations().length),0,'Reduced motion updates material without animation');
103 }
104 else{
105 await white.evaluate(()=>renderGames());
106 assert(await pulse.evaluate(el=>el.getAnimations()[0].currentTime>0),'Rerender continues pulse instead of restarting it');
107 assert(await fill.evaluate(el=>el.getAnimations().length>0),'Material fill interpolates through rerender');
108 await white.waitForTimeout(250);
109 await white.screenshot({path:path.join(web,`tests/artifacts/feedback-${quality}.png`)});
110 }
111 await pulse.waitFor({state:'detached'});
112 const expected=quality==='good'?1:9/14;
113 assert(Math.abs(await fill.evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a)-expected)<.001,'Material fill settles at correct proportion');
114 await black.evaluate(()=>refresh(true));
115 assert.equal(await black.locator(`[data-game="${id}"] .material-bar`).getAttribute('data-share'),await bar.getAttribute('data-share'),'Polling uses the same White-left ratio for Black');
116 await white.evaluate(()=>renderGames());
117 assert.equal(await white.locator('.move-feedback').count(),0,'Completed pulse is not replayed');
118 }
119 await white.emulateMedia({reducedMotion:'no-preference'});
120 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
121 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
122 // Fixture a legal promotion position in the isolated database.
123 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
124 fixture.history=[fixture.board.join('')+'w'];
125 execFileSync('php',['-r',`$db=new PDO('sqlite:'.$argv[1]);$q=$db->prepare('UPDATE games SET state=?,version=version+1 WHERE id=?');$q->execute([$argv[2],$argv[3]]);`,path.join(root,'data/microchess.sqlite'),JSON.stringify(fixture),String(id)]);
126 await white.waitForTimeout(3000);
127 await white.locator(`[data-game="${id}"] [data-square="5"]`).click();await white.locator(`[data-game="${id}"] [data-square="1"]`).click();
128 assert.equal(await white.locator('[data-promotion]').count(),4,'Four promotion options');
129 await white.locator('[data-promotion="n"]').click();
130 await white.getByRole('heading',{name:'A game well matched.'}).waitFor();
131 assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved');
132 for(const page of [white,black]){
133 await page.locator('.end-content').waitFor();
134 assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');
135 assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');
136 await page.mouse.move(0,0);
137 await page.waitForTimeout(250);
138 assert(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))<.3,'Result starts transparent');
139 await page.locator('.end-content').hover();await page.waitForTimeout(250);
140 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
141 }
142 await white.getByRole('button',{name:'Rematch',exact:true}).click();
143 await black.getByText(/wants a rematch/).waitFor();
144 await black.getByRole('button',{name:'Rematch',exact:true}).click();
145 await white.locator('.board').waitFor();
146 assert.equal((await state(white)).games[0].color,'b','Rematch flips colors');
147 // Three real game links for desktop layout coverage.
148 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')});}
149 await a.reload();await a.locator('.game-card').nth(3).waitFor();
150 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
151 assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load');
152 await a.setViewportSize({width:1440,height:640});
153 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
154 const sidebar=await a.locator('#sidebar').boundingBox();
155 assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`);
156 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
157 const staleId=(await state(a)).games[0].id;
158 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/microchess.sqlite'),String(staleId)]);
159 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
160 await a.getByText('De laatste zet was 8 dagen geleden. Wil je het spel stoppen?').waitFor();
161 await a.getByRole('button',{name:'Annuleren',exact:true}).click();
162 assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game');
163 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
164 await a.getByRole('button',{name:'Spel stoppen',exact:true}).click();
165 await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
166 await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
167 await a.setViewportSize({width:390,height:844});
168 assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'No mobile horizontal overflow');
169 assert.equal(await a.locator('#your-games').evaluate(e=>getComputedStyle(e).gridTemplateColumns.split(' ').length),1,'One tile column');
170 await a.locator('#friends-toggle').click();await a.locator('#sidebar.open').waitFor();await a.waitForTimeout(250);
171 await a.locator('#avatar-button').click();
172 await a.locator('[data-avatar-group="fairy"]').click();
173 await a.locator('#avatar-color').selectOption('Purple');
174 await a.locator('[data-avatar-choice="purple-elephant"]').waitFor();
175 await a.locator('.avatar-choice img').evaluateAll(imgs=>Promise.all(imgs.map(i=>i.decode())));
176 assert(await a.locator('.avatar-choice img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'Fairy avatars load');
177 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-mobile.png')});
178 await a.locator('[data-avatar-choice="purple-elephant"]').click();
179 await a.locator('#avatar-button img[src$="purple-elephant.png"]').waitFor();
180 await a.screenshot({path:path.join(web,'tests/artifacts/mobile-friends.png'),fullPage:false});
181 await a.locator('#friends-close').click();await a.waitForTimeout(250);await a.screenshot({path:path.join(web,'tests/artifacts/mobile.png'),fullPage:true});
182 // Touch events exercise the mobile pointer path, not mouse emulation.
183 const sa=await state(a),sb=await state(b);
184 const owner=sa.games.some(g=>g.yourTurn)?a:b;
185 const mobileContext=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,storageState:await owner.context().storageState()});
186 const touch=await mobileContext.newPage();await touch.goto(base);
187 const tg=(await state(touch)).games.find(g=>g.yourTurn),tm=tg.legal[0];
188 const fs=touch.locator(`[data-game="${tg.id}"] [data-square="${tm.from}"]`);
189 await fs.scrollIntoViewIfNeeded();const fb=await fs.boundingBox();
190 const tb=await touch.locator(`[data-game="${tg.id}"] [data-square="${tm.to}"]`).boundingBox();
191 const cdp=await mobileContext.newCDPSession(touch);
192 await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:fb.x+fb.width/2,y:fb.y+fb.height/2}]});
193 for(let i=1;i<=8;i++)await cdp.send('Input.dispatchTouchEvent',{type:'touchMove',touchPoints:[{x:fb.x+fb.width/2+(tb.x-fb.x)*i/8,y:fb.y+fb.height/2+(tb.y-fb.y)*i/8}]});
194 await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});
195 await touch.waitForTimeout(500);
196 assert.equal((await state(touch)).games.find(g=>g.id===tg.id).state.ply,tg.state.ply+1,'Mobile touch drag saved');
197 assert.equal(await touch.locator(`#your-games [data-game="${tg.id}"]`).count(),1,'Mobile move also stays in place');
198 const mobileWaiting=touch.locator(`#waiting-games [data-game="${tg.id}"]`);
199 await mobileWaiting.waitFor({state:'attached'});
200 assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid');
201 await mobileContext.close();
202 assert.deepEqual(errors,[],'No browser errors');
203 console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.');
204}finally{
205 await browser?.close();server.kill();await new Promise(r=>server.once('exit',r));await rm(root,{recursive:true,force:true});
206}