BlueGit

projects-timfalken-com microchess

Files

microchess / web / tests / browser.mjs

browser.mjs

browser.mjs 25.5 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="fairy"]').click();
26 assert.equal(await a.locator('.avatar-choice').count(),67,'Retained fairy collection is selectable');
27 await a.locator('#avatar-color').selectOption('Pink');
28 assert.equal(await a.locator('.avatar-choice').count(),3,'All pink fairy pieces are present');
29 await a.locator('[data-avatar-choice="pink-ferz"]').click();
30 await a.locator('#avatar-button img[src$="pink-ferz.png"]').waitFor();
31 await a.reload();
32 await a.locator('#avatar-button img[src$="pink-ferz.png"]').waitFor();
33 await a.locator('#avatar-button').click();
34 await a.locator('[data-avatar-choice="blue-knight"]').waitFor();
35
36 await a.locator('[data-avatar-group="standard"]').click();
37 await a.locator('#avatar-color').selectOption('Blue');
38 assert.equal(await a.locator('.avatar-choice').count(),6,'Six blue standard chess pieces');
39 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-desktop.png')});
40 await a.locator('[data-avatar-choice="blue-knight"]').click();
41 await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();
42 await a.reload();await a.locator('#avatar-button img[src$="blue-knight.png"]').waitFor();
43 await b.locator('#settings-button').click();await b.getByRole('button',{name:'Switch to test_user_2'}).click();
44 await b.locator('#account-summary').getByText('test_user_2',{exact:false}).waitFor();
45 await a.locator('#friend-link').click();await a.locator('#share-url').waitFor();
46 const friendLink=await a.locator('#share-url').inputValue();
47 await a.locator('#modal-close').click();
48 await b.goto(friendLink);await b.getByRole('button',{name:'Accept',exact:true}).click();
49 await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor();
50 await b.locator('#friend-list [data-friend="local:test_user_1"] img[src$="blue-knight.png"]').waitFor();
51 await a.locator('#friend-list [data-friend="local:test_user_2"]').click();await a.getByRole('button',{name:'Challenge to a game'}).click();
52 await b.getByRole('button',{name:'Accept',exact:true}).click();
53 await a.locator('.board').waitFor();await b.locator('.board').waitFor();
54 await b.locator('.card-header img[src$="blue-knight.png"]').waitFor();
55 async function state(p){return p.evaluate(async()=>{const r=await fetch('api.php');return r.json();});}
56 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});}
57 const initial=await state(a),id=initial.games[0].id;
58 const white=initial.games[0].color==='w'?a:b,black=white===a?b:a;
59 await white.locator(`[data-game="${id}"] [data-square="15"]`).click();
60 assert.equal(await white.locator(`[data-game="${id}"] .legal`).count(),1,'Pawn legal dot');
61 await white.locator(`[data-game="${id}"] [data-square="11"]`).click();
62 const held=white.locator(`#your-games [data-game="${id}"]`);
63 await held.locator('[data-square="11"]:disabled').waitFor();
64 const heldAt=Date.now(),heldRect=await held.boundingBox();
65 assert.equal(await white.locator('.material-bar').getAttribute('aria-valuenow'),'50','Equal starting material gives 50/50');
66 assert.equal(await black.locator('.material-bar').getAttribute('aria-valuenow'),'50','Material orientation is the same for Black');
67 assert.equal(await held.locator('.move-feedback').count(),0,'Quiet opening move receives no pulse');
68 assert.equal(await held.locator('.square:not([disabled])').count(),0,'Confirmed move immediately disables held board');
69 await white.waitForTimeout(2200);
70 assert.equal(await held.count(),1,'Moved tile stays in Your Turn during pause');
71 assert.equal(await held.locator('.move-feedback').count(),0,'Feedback stops after one event');
72 await white.evaluate(()=>renderGames());
73 assert.equal(await held.locator('.move-feedback').count(),0,'Rerender does not replay feedback');
74 assert(Math.abs((await held.boundingBox()).y-heldRect.y)<1,'Held tile stays in its original position');
75 const relocated=white.locator(`#waiting-games [data-game="${id}"]`);
76 await relocated.waitFor({state:'attached'});
77 assert(Date.now()-heldAt>=2800,'Tile waits approximately three seconds before relocating');
78 assert(await relocated.evaluate(el=>el.getAnimations().length>0),'Tile animates to the waiting grid');
79 await relocated.evaluate(el=>Promise.all(el.getAnimations().map(a=>a.finished)));
80 await black.locator(`[data-game="${id}"] [data-square="4"]:not([disabled])`).waitFor();
81 assert.equal(await white.locator('#waiting-games .square:not([disabled])').count(),0,'Waiting board inert');
82 // Actual pointer drag.
83 const from=await black.locator(`[data-game="${id}"] [data-square="4"]`).boundingBox();
84 const to=await black.locator(`[data-game="${id}"] [data-square="8"]`).boundingBox();
85 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();
86 await white.locator(`[data-game="${id}"] [data-square="11"]:not([disabled])`).waitFor();
87 assert.equal((await state(white)).games[0].state.ply,2,'Drag move saved');
88 // Real tactical evaluations, using board fixtures only in this disposable game database.
89 async function tacticalFixture(pieces){
90 const board=Array(20).fill('.');for(const [i,piece] of Object.entries(pieces))board[Number(i)]=piece;
91 const position={board,turn:'w',halfmove:0,ply:2,history:[board.join('')+'w'],last:null};
92 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)]);
93 await white.evaluate(()=>refresh(true));
94 }
95 for(const [quality,pieces,reduced] of [
96 ['good',{19:'K',3:'k',12:'R',8:'q'},false],
97 ['poor',{19:'K',1:'k',12:'Q',8:'p',0:'r'},false],
98 ['good',{19:'K',3:'k',12:'R',8:'q'},true],
99 ]){
100 await white.emulateMedia({reducedMotion:reduced?'reduce':'no-preference'});
101 await tacticalFixture(pieces);
102 await white.locator(`[data-game="${id}"] [data-square="12"]:not([disabled])`).click();
103 const started=Date.now();
104 await white.locator(`[data-game="${id}"] [data-square="8"]`).click();
105 const pulse=white.locator(`[data-game="${id}"] .move-feedback.${quality}`);
106 await pulse.waitFor({state:'attached'});
107 assert(Date.now()-started<3000,'Actual API feedback arrives within tile pause locally');
108 assert.equal(await black.locator('.move-feedback').count(),0,'Only the mover receives feedback');
109 const bar=white.locator(`[data-game="${id}"] .material-bar`),fill=bar.locator('.material-white');
110 assert.equal(await bar.getAttribute('aria-valuenow'),quality==='good'?'100':'64','Captured material updates the bar');
111 if(reduced){
112 assert.equal(await pulse.evaluate(el=>el.getAnimations().length),0,'Reduced motion shows static feedback');
113 assert.equal(await fill.evaluate(el=>el.getAnimations().length),0,'Reduced motion updates material without animation');
114 }
115 else{
116 await white.evaluate(()=>renderGames());
117 assert(await pulse.evaluate(el=>el.getAnimations()[0].currentTime>0),'Rerender continues pulse instead of restarting it');
118 assert(await fill.evaluate(el=>el.getAnimations().length>0),'Material fill interpolates through rerender');
119 await white.waitForTimeout(250);
120 await white.screenshot({path:path.join(web,`tests/artifacts/feedback-${quality}.png`)});
121 }
122 await pulse.waitFor({state:'detached'});
123 const expected=quality==='good'?1:9/14;
124 assert(Math.abs(await fill.evaluate(el=>new DOMMatrixReadOnly(getComputedStyle(el).transform).a)-expected)<.001,'Material fill settles at correct proportion');
125 await black.evaluate(()=>refresh(true));
126 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');
127 await white.evaluate(()=>renderGames());
128 assert.equal(await white.locator('.move-feedback').count(),0,'Completed pulse is not replayed');
129 }
130 await white.emulateMedia({reducedMotion:'no-preference'});
131 const kingsBar=await white.evaluate(()=>materialBar({color:'w',state:{board:['K','k',...Array(18).fill('.')]}}));
132 assert(kingsBar.includes('data-share="0.5"'),'Bare kings give a neutral material bar');
133 await white.evaluate(() => {
134 window.savedFlights = 0;
135 const original = Element.prototype.animate;
136 Element.prototype.animate = function (...args) { if (this.classList.contains('saved-hourglass')) window.savedFlights++; return original.apply(this, args); };
137 });
138 // Fixture a legal promotion position in the isolated database.
139 const fixture={board:['.','.','.','k','.','P','.','.','.','.','.','.','.','.','.','.','K','.','.','.'],turn:'w',halfmove:0,ply:2,history:[],last:null};
140 fixture.history=[fixture.board.join('')+'w'];
141 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)]);
142 await white.waitForTimeout(3000);
143 await white.locator(`[data-game="${id}"] [data-square="5"]`).click();await white.locator(`[data-game="${id}"] [data-square="1"]`).click();
144 assert.equal(await white.locator('[data-promotion]').count(),4,'Four promotion options');
145 await white.locator('[data-promotion="n"]').click();
146 await white.getByRole('heading',{name:'A game well matched.'}).waitFor();
147 assert.equal((await state(white)).games[0].state.board[1],'N','Underpromotion saved');
148 for(const page of [white,black]){
149 await page.locator('.end-content').waitFor();
150 assert.equal(await page.locator('.ended-board .square').count(),20,'Final board remains visible for both players');
151 assert.equal(await page.locator('.ended-board .square.last').count(),2,'Final move stays highlighted');
152 await page.mouse.move(0,0);
153 await page.waitForTimeout(850);
154 assert(Math.abs(Number(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity))-.72)<.01,'Result starts translucent');
155 await page.locator('.end-content').hover();await page.waitForTimeout(850);
156 assert.equal(await page.locator('.end-content').evaluate(e=>getComputedStyle(e).opacity),'1','Hover reveals result controls');
157 }
158 assert.equal(await white.evaluate(()=>window.savedFlights),1,'Finished game animates to history once');
159 await white.locator('#history-button').click();
160 await white.locator('.history-entry').waitFor();
161 await white.locator('.history-entry').first().click();
162 await white.locator('#replay-card .board').waitFor();
163 assert.equal(await white.locator('#replay-card [data-square="5"] img').count(),1,'Replay starts before promotion');
164 await white.locator('[data-replay-control="next"]').dblclick();
165 assert.match(await white.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Replay preserves underpromotion');
166 await white.locator('[data-replay-control="back"]').dblclick();
167 assert.match(await white.locator('#replay-progress').innerText(),/^0 \/ 1/,'Double back returns to beginning');
168 await white.locator('[data-replay-control="play"]').click();
169 assert.equal(await white.locator('[data-replay-control="play"]').getAttribute('aria-label'),'Pause','Play becomes pause');
170 await white.waitForTimeout(600);
171 assert.match(await white.locator('#replay-progress').innerText(),/^1 \/ 1/,'Autoplay advances to end');
172 assert.equal(await white.locator('[data-replay-control="play"]').getAttribute('aria-label'),'Play','Autoplay stops at end');
173 assert.equal(await white.locator('#replay-card .material-bar').count(),0,'Replay replaces opponent header and material bar');
174 assert.equal(await white.locator('.replay-players img[alt="White"]').count(),1,'White king identifies white player');
175 assert.equal(await white.locator('.replay-players img[alt="Black"]').count(),1,'Black king identifies black player');
176 await white.context().grantPermissions(['clipboard-read','clipboard-write']);
177 await white.locator('#replay-share').click();
178 const replayUrl=await white.evaluate(()=>navigator.clipboard.readText());
179 assert.match(replayUrl,/\?replay=[a-f0-9]{48}$/,'Chain button copies a share URL');
180 const guestContext=await browser.newContext(),guest=await guestContext.newPage();
181 guest.on('pageerror',e=>errors.push(e.message));
182 await guest.goto(replayUrl);
183 await guest.locator('#replay-card .board').waitFor();
184 assert.equal(await guest.locator('.replay-players').innerText(),await white.locator('.replay-players').innerText(),'Shared page identifies both players');
185 assert.equal(await guest.locator('#history-return').count(),0,'Public replay has no private history navigation');
186 assert.equal(await guest.locator('dialog, #modal-close, .topbar, .login, #sidebar').count(),0,'Standalone replay has no dialog, close button or background UI');
187 await guest.keyboard.press('Escape');
188 await guest.locator('#replay-card .board').waitFor();
189 await guest.locator('body').click({position:{x:4,y:4}});
190 await guest.locator('#replay-card .board').waitFor();
191 await guest.setViewportSize({width:390,height:844});
192 assert(await guest.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'Standalone replay fits mobile width');
193 await guest.screenshot({path:path.join(web,'tests/artifacts/shared-replay-mobile.png')});
194 await guest.reload();
195 await guest.locator('#replay-card .board').waitFor();
196
197 await guest.locator('[data-replay-control="next"]').dblclick();
198 assert.match(await guest.locator('#replay-card [data-square="1"] img').getAttribute('src'),/nlt/,'Shared replay plays the same promotion');
199 await guestContext.close();
200 await white.screenshot({path:path.join(web,'tests/artifacts/game-replay.png')});
201 await white.locator('#modal-close').click();
202 await white.evaluate(()=>refresh(true));
203 assert.equal(await white.locator('.saved-hourglass').count(),0,'Saved animation does not repeat');
204 await white.getByRole('button',{name:'Rematch',exact:true}).click();
205 await black.getByText(/wants a rematch/).waitFor();
206 await black.getByRole('button',{name:'Rematch',exact:true}).click();
207 await white.locator('.board').waitFor();
208 assert.equal((await state(white)).games[0].color,'b','Rematch flips colors');
209 // Three real game links for desktop layout coverage.
210 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')});}
211 await a.reload();await a.locator('.game-card').nth(3).waitFor();
212 await a.screenshot({path:path.join(web,'tests/artifacts/desktop.png'),fullPage:true});
213 assert(await a.locator('.square img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'All SVG pieces load');
214 await a.setViewportSize({width:1440,height:640});
215 await a.evaluate(()=>scrollTo(0,document.body.scrollHeight));
216 const sidebar=await a.locator('#sidebar').boundingBox();
217 assert(sidebar.y>=-1&&sidebar.y+sidebar.height<=641,`Desktop sidebar fits viewport while scrolling: ${JSON.stringify(sidebar)}`);
218 assert.equal(await a.locator('#sidebar').evaluate(e=>getComputedStyle(e).position),'sticky');
219 const staleId=(await state(a)).games[0].id;
220 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)]);
221 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
222 await a.getByText('This game has been inactive for 8 days. Would you like to stop it?').waitFor();
223 await a.getByRole('button',{name:'Cancel',exact:true}).click();
224 assert((await state(a)).games.some(g=>g.id===staleId),'Cancel retains game');
225 await a.locator(`[data-game="${staleId}"] .stop-inactive`).click();
226 await a.getByRole('button',{name:'Stop game',exact:true}).click();
227 await a.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
228 await b.locator(`[data-game="${staleId}"]`).waitFor({state:'detached'});
229 await a.setViewportSize({width:390,height:844});
230 assert(await a.evaluate(()=>document.documentElement.scrollWidth<=innerWidth),'No mobile horizontal overflow');
231 assert.equal(await a.locator('#your-games').evaluate(e=>getComputedStyle(e).gridTemplateColumns.split(' ').length),1,'One tile column');
232 await a.locator('#friends-toggle').click();await a.locator('#sidebar.open').waitFor();await a.waitForTimeout(250);
233 await a.locator('#avatar-button').click();
234 await a.locator('[data-avatar-group="fairy"]').click();
235 await a.locator('#avatar-color').selectOption('Purple');
236 await a.locator('[data-avatar-choice="purple-elephant"]').waitFor();
237 await a.locator('.avatar-choice img').evaluateAll(imgs=>Promise.all(imgs.map(i=>i.decode())));
238 assert(await a.locator('.avatar-choice img').evaluateAll(imgs=>imgs.every(i=>i.complete&&i.naturalWidth>0)),'Fairy avatars load');
239 await a.screenshot({path:path.join(web,'tests/artifacts/avatar-picker-mobile.png')});
240 await a.locator('[data-avatar-choice="purple-elephant"]').click();
241 await a.locator('#avatar-button img[src$="purple-elephant.png"]').waitFor();
242 await a.screenshot({path:path.join(web,'tests/artifacts/mobile-friends.png'),fullPage:false});
243 await a.locator('#friends-close').click();await a.waitForTimeout(250);await a.screenshot({path:path.join(web,'tests/artifacts/mobile.png'),fullPage:true});
244 // Touch events exercise the mobile pointer path, not mouse emulation.
245 const sa=await state(a),sb=await state(b);
246 const owner=sa.games.some(g=>g.yourTurn)?a:b;
247 const mobileContext=await browser.newContext({viewport:{width:390,height:844},hasTouch:true,isMobile:true,storageState:await owner.context().storageState()});
248 const touch=await mobileContext.newPage();await touch.goto(base);
249 const tg=(await state(touch)).games.find(g=>g.yourTurn),tm=tg.legal[0];
250 const fs=touch.locator(`[data-game="${tg.id}"] [data-square="${tm.from}"]`);
251 await fs.scrollIntoViewIfNeeded();const fb=await fs.boundingBox();
252 const tb=await touch.locator(`[data-game="${tg.id}"] [data-square="${tm.to}"]`).boundingBox();
253 const cdp=await mobileContext.newCDPSession(touch);
254 await cdp.send('Input.dispatchTouchEvent',{type:'touchStart',touchPoints:[{x:fb.x+fb.width/2,y:fb.y+fb.height/2}]});
255 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}]});
256 await cdp.send('Input.dispatchTouchEvent',{type:'touchEnd',touchPoints:[]});
257 await touch.waitForTimeout(500);
258 assert.equal((await state(touch)).games.find(g=>g.id===tg.id).state.ply,tg.state.ply+1,'Mobile touch drag saved');
259 assert.equal(await touch.locator(`#your-games [data-game="${tg.id}"]`).count(),1,'Mobile move also stays in place');
260 const mobileWaiting=touch.locator(`#waiting-games [data-game="${tg.id}"]`);
261 await mobileWaiting.waitFor({state:'attached'});
262 assert(await mobileWaiting.evaluate(el=>el.getAnimations().length>0),'Mobile tile also slides to waiting grid');
263 await mobileContext.close();
264 // New game offers matchmaking below the link, with persistent cancellation.
265 await a.setViewportSize({width:1440,height:1080});
266 await a.locator('#match-link').click();
267 await a.getByRole('button',{name:'Challenge a random player',exact:true}).waitFor();
268 const linkBox=await a.locator('#share-url').boundingBox();
269 const matchBox=await a.getByRole('button',{name:'Challenge a random player',exact:true}).boundingBox();
270 assert(matchBox.y>linkBox.y,'Random challenge is below invite link');
271 await a.getByRole('button',{name:'Challenge a random player',exact:true}).click();
272 await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor();
273 await a.reload();
274 await a.getByRole('button',{name:'Cancel search',exact:true}).waitFor();
275 await a.locator('#match-link').click();
276 await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).waitFor();
277 await a.locator('#matchmaking-actions').getByRole('button',{name:'Cancel search'}).click();
278 await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'});
279 await a.locator('#match-link').click();
280 await a.getByRole('button',{name:'Challenge a random player',exact:true}).click();
281 await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor();
282 const priorIds=new Set((await state(a)).games.map(g=>g.id));
283 await b.locator('#match-link').click();
284 await b.getByRole('button',{name:'Challenge a random player',exact:true}).click();
285 await a.getByRole('heading',{name:'Finding an opponent…'}).waitFor({state:'detached'});
286 const randomGame=(await state(a)).games.find(g=>!priorIds.has(g.id));
287 assert(randomGame,'Matchmaking creates a new game');
288 for(const p of[a,b]) await p.locator(`[data-game="${randomGame.id}"] .board`).waitFor();
289 assert.match(await a.locator('#account-summary').innerText(),/\d+ Elo/,'Own rating is visible');
290 assert.equal(await a.locator(`[data-game="${randomGame.id}"] .rating`).innerText(),String(randomGame.opponentRating),'Opponent rating is visible');
291 // The same rivalry modal is available from a game and the friends list.
292 await post(a,'remove_friend',{friend:'local:test_user_2'});
293 await a.reload();
294 await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
295 const rivalryStats=await a.locator('.stats').innerText();
296 await a.getByRole('button',{name:'Send friend request',exact:true}).click();
297 await a.locator('#modal').waitFor({state:'hidden'});
298 await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
299 assert(await a.getByRole('button',{name:'Friend request sent',exact:true}).isDisabled(),'Sender sees pending status');
300 await a.locator('#modal-close').click();
301 await b.locator('#friend-requests').getByRole('button',{name:'Reject',exact:true}).click();
302 await b.locator('.friend-request').waitFor({state:'detached'});
303 await a.reload();
304 await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
305 await a.getByRole('button',{name:'Send friend request',exact:true}).click();
306 await b.reload();
307 await b.setViewportSize({width:390,height:844});
308 await b.locator('#friends-toggle').click();
309 await b.locator('#friend-requests').getByRole('button',{name:'Accept',exact:true}).click();
310 await b.locator('#friend-list [data-friend="local:test_user_1"]').waitFor();
311 await b.locator('.friend-request').waitFor({state:'detached'});
312 await a.locator('#friend-list [data-friend="local:test_user_2"]').waitFor();
313 await a.locator(`[data-game="${randomGame.id}"] .opponent-name`).click();
314 assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Game modal retains rivalry history');
315 await a.getByRole('button',{name:'Challenge to a game'}).waitFor();
316 await a.locator('#modal-close').click();
317 await a.locator('#friend-list [data-friend="local:test_user_2"]').click();
318 assert.equal(await a.locator('.stats').innerText(),rivalryStats,'Friend and game modals show identical statistics');
319 await a.locator('#modal-close').click();
320 assert.deepEqual(errors,[],'No browser errors');
321 console.log('Browser: friendship, challenge, click/drag moves, promotion, rematch, SVGs, desktop and mobile checks passed.');
322}finally{
323 await browser?.close();server.kill();await new Promise(r=>server.once('exit',r));await rm(root,{recursive:true,force:true});
324}