Files
mtusi2026lab3/student-tests/ui_showcase.cjs
T

112 lines
8.7 KiB
JavaScript

// Integration test against the real cluster; includes a real, automatically restored container stop.
const { chromium, request } = require('playwright');
const assert = require('node:assert/strict');
const { randomUUID } = require('node:crypto');
const { spawn } = require('node:child_process');
const fs = require('node:fs/promises');
const path = require('node:path');
const baseURL = process.env.MESSENGER_TEST_URL || 'http://127.0.0.1:18080';
const evidence = path.resolve(__dirname, '../evidence');
const actors = [], errors = [], checks = [];
let api, browser, demo;
async function call(method, route, actor, data) {
const response = await api.fetch(route, {method, data,
headers:{...(actor ? {Authorization:'Bearer '+actor.token} : {}), ...(method==='POST' && route.endsWith('/messages') ? {'Idempotency-Key':randomUUID()} : {})}});
assert(response.ok(), `${method} ${route.split('?')[0]}: ${response.status()}`);
return response.status()===204 ? null : response.json();
}
async function actor(name) {
const username = 'show_' + randomUUID().replaceAll('-','').slice(0,16), password = randomUUID();
await call('POST','/api/v1/users',null,{username,password,display_name:name});
const response = await api.post('/api/v1/auth/sessions',{headers:{Authorization:'Basic '+Buffer.from(username+':'+password).toString('base64')}});
assert.equal(response.status(),201); const value=await response.json(); actors.push(value); return value;
}
async function pageFor(actor, chat) {
const page=await browser.newPage({viewport:{width:1440,height:1000}});
page.on('pageerror',error=>errors.push(error.message));
await page.addInitScript(session=>sessionStorage.setItem('n1k0der.session',JSON.stringify(session)),actor);
await page.goto(baseURL); await page.locator(`[data-chat-id="${chat.id}"]`).click();
await page.locator('article.message').first().waitFor(); return page;
}
const row=(page,id)=>page.locator(`article[data-message-id="${id}"]`);
(async()=>{
await fs.mkdir(evidence,{recursive:true});
api=await request.newContext({baseURL,timeout:15000});
browser=await chromium.launch({executablePath:process.env.MESSENGER_BROWSER_PATH || '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',headless:true});
const alice=await actor('Никита'), bob=await actor('Собеседник');
const chat=await call('POST','/api/v1/chats',alice,{title:'Защита · живой мессенджер',member_ids:[alice.user.id,bob.user.id]});
const message=await call('POST',`/api/v1/chats/${chat.id}/messages`,bob,{text:'Привет! Проверим реакции и работу двух API 🍄'});
await call('POST',`/api/v1/chats/${chat.id}/messages`,alice,{text:'Да! Сейчас отключим один экземпляр. Переписка продолжит работать.'});
const a=await pageFor(alice,chat), b=await pageFor(bob,chat);
await row(a,message.id).locator('.reaction-picker').click();
await row(a,message.id).getByRole('button',{name:'Гриб',exact:true}).click();
await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.getAttribute('aria-pressed')==='true',message.id);
await b.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.textContent==='🍄 1',message.id);
assert.equal(await row(b,message.id).locator('[data-reaction=mushroom]').getAttribute('aria-pressed'),'false');
await row(b,message.id).locator('[data-reaction=mushroom]').click();
await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=mushroom]`)?.textContent==='🍄 2',message.id);
checks.push('real two-window reactions: shared count, per-user mine state');
await a.locator('.sidebar-diagnostics').click();
await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2);
await a.locator('#cluster-probe').click();
await a.waitForFunction(()=>document.querySelector('#cluster-detail').textContent.includes('200'));
const liveResponse=await api.get('/health/ready');
assert.equal(liveResponse.status(),200);
const target=liveResponse.headers()['x-instance-id'];
await a.locator(`.cluster-api[data-instance-id="${target}"][data-state=up]`).waitFor();
assert.match(target,/^[a-f0-9]{32}$/);
checks.push('live diagram: actual Redis heartbeats, real X-Instance-Id response and counters');
await a.locator('.cluster-demo summary').click();
await a.screenshot({path:path.join(evidence,'ui-showcase-live.png')});
let output='';
demo=spawn('python3',['scripts/demo-failover.py','--instance',target,'--seconds','22','--base-url',baseURL],{cwd:path.resolve(__dirname,'..'),stdio:['ignore','pipe','pipe']});
demo.stdout.on('data',chunk=>{output+=chunk.toString()}); demo.stderr.on('data',chunk=>{output+=chunk.toString()});
const completion=new Promise((resolve,reject)=>{demo.on('error',reject); demo.on('close',code=>code===0 ? resolve() : reject(new Error('Failover demo failed: '+output)));});
// Attach a handler immediately so an early script failure is not an unhandled rejection.
completion.catch(()=>{});
await a.waitForFunction(id=>document.querySelector(`[data-instance-id="${id}"]`)?.dataset.state==='down',target,{timeout:25000});
await a.locator('#message-input').fill('Один API отключён, а сообщение всё равно доставлено ✓');
await a.locator('#send-message').click();
await b.locator('#message-list').getByText('Один API отключён, а сообщение всё равно доставлено ✓',{exact:true}).waitFor();
const during=await call('GET','/api/ui/cluster',alice);
assert.equal(during.instances.filter(node=>node.ready).length,1);
await row(b,message.id).locator('.reaction-picker').click();
await row(b,message.id).getByRole('button',{name:'Сердце',exact:true}).click();
await a.waitForFunction(id=>document.querySelector(`article[data-message-id="${id}"] [data-reaction=love]`)?.textContent==='❤️ 1',message.id);
assert.equal((await call('GET','/api/ui/cluster',alice)).instances.filter(node=>node.ready).length,1);
await a.screenshot({path:path.join(evidence,'ui-showcase-failover.png')});
await completion; demo=null;
await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2,{},{timeout:20000});
assert(output.includes('Восстанавливаем') && output.includes('Готово.'));
checks.push('real Docker stop: heartbeat disappears, browser sends message and reaction via surviving API, script restores replicas');
const cluster=await call('GET','/api/ui/cluster',alice);
assert(cluster.instances.some(node=>node.id===target && !node.ready));
assert(cluster.instances.filter(node=>node.ready).length>=2);
checks.push('restart is shown with new process ID; old missing heartbeat is not mislabelled as recovery');
await a.route('**/api/ui/cluster',route=>route.fulfill({status:200,contentType:'application/json',body:JSON.stringify({redis_available:false,postgres_available:true,checked_at:Date.now(),instances:[]})}));
await a.locator('#cluster-probe').click();
await a.waitForFunction(()=>document.querySelector('#cluster-status').textContent.includes('неизвестно'));
assert.equal(await a.locator('.cluster-api[data-state=down]').count(),0);
assert(await a.locator('#cluster-copy').isDisabled());
await a.unroute('**/api/ui/cluster');
await a.locator('#cluster-probe').click();
await a.waitForFunction(()=>document.querySelectorAll('.cluster-api[data-state=up]').length>=2);
checks.push('missing Redis telemetry is shown as unknown, rather than a false API outage');
await a.setViewportSize({width:390,height:844});
assert(await a.evaluate(()=>document.documentElement.scrollWidth<=document.documentElement.clientWidth));
assert(await a.locator('#diagnostics-panel').evaluate(e=>e.scrollWidth<=e.clientWidth));
await a.screenshot({path:path.join(evidence,'ui-showcase-mobile.png')});
await a.emulateMedia({reducedMotion:'reduce'});
assert.equal(await a.locator('.cluster-api').first().evaluate(e=>getComputedStyle(e).transitionDuration),'0s');
checks.push('390px diagram: no horizontal overflow; reduced motion supported');
assert.deepEqual(errors,[]);
await fs.writeFile(path.join(evidence,'ui-showcase.json'),JSON.stringify({checks,errors,failover:output},null,2)+'\n');
console.log(JSON.stringify({checks,errors},null,2));
})().catch(error=>{console.error(error.stack);process.exitCode=1;}).finally(async()=>{
if(demo && demo.exitCode===null && demo.signalCode===null){demo.kill('SIGTERM');await new Promise(resolve=>demo.once('close',resolve));}
for(const value of actors){try{await call('DELETE','/api/v1/auth/sessions/current',value)}catch{}}
await browser?.close();await api?.dispose();
});