Files
mtusi2026lab3/student-tests/ui_rendering.cjs
T

297 lines
18 KiB
JavaScript

// Optional browser regression test. The application itself has no npm dependencies.
const { chromium, request } = require('playwright');
const assert = require('node:assert/strict');
const fs = require('node:fs/promises');
const path = require('node:path');
const { randomUUID } = require('node:crypto');
const baseURL = process.env.MESSENGER_TEST_URL || 'http://localhost:18080';
const evidence = path.resolve(__dirname, '../evidence');
const results = { verified_at: new Date().toISOString(), checks: [] };
let browser, api;
const sessions = [];
async function call(method, route, body, actor) {
const response = await api.fetch(route, {
method, data: body,
headers: { ...(actor ? { Authorization: 'Bearer ' + actor.token } : {}), ...(method === 'POST' && route.endsWith('/messages') ? { 'Idempotency-Key': randomUUID() } : {}) }
});
assert(response.ok(), `${method} ${route}: HTTP ${response.status()}`);
return response.status() === 204 ? null : response.json();
}
async function account(suffix, name) {
const username = 'ui_' + suffix + '_' + randomUUID().slice(0, 8);
const password = randomUUID();
await call('POST', '/api/v1/users', { username, display_name: name, password });
const response = await api.post('/api/v1/auth/sessions', {
headers: { Authorization: 'Basic ' + Buffer.from(username + ':' + password).toString('base64') }
});
assert.equal(response.status(), 201);
const actor = await response.json();
sessions.push(actor);
return { ...actor, username, password };
}
async function login(page, actor) {
await page.goto(baseURL);
await page.locator('#login-username').fill(actor.username);
await page.locator('#login-password').fill(actor.password);
await page.locator('#login-form button[type=submit]').click();
await page.locator('#app-screen').waitFor({ state: 'visible' });
}
async function decodeVisibleImage(page, selector) {
await page.waitForFunction(selector => {
const img = document.querySelector(selector);
return img?.complete && img.naturalWidth > 0;
}, selector);
await page.locator(selector).evaluate(img => img.decode());
}
async function openHistory(page, chat) {
await page.getByRole('button', { name: new RegExp(chat.title) }).click();
await page.waitForFunction(() => document.querySelectorAll('article.message').length === 50);
await page.waitForFunction(() => [...document.querySelectorAll('.message-author')].some(e => e.textContent === 'Собеседник'));
await page.locator('#older-messages').click();
await page.waitForFunction(() => document.querySelectorAll('article.message').length === 75);
}
async function pollOnce(page, chat) {
await page.waitForResponse(r => r.url().includes(`/api/ui/chats/${chat.id}/messages?limit=50`) && r.status() === 200);
await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))));
}
async function observeList(page) {
await page.evaluate(() => {
const list = document.querySelector('#message-list');
const first = list.querySelector('article');
const text = first.querySelector('.message-text').firstChild;
const selection = getSelection();
const range = document.createRange();
range.setStart(text, 0); range.setEnd(text, Math.min(10, text.length));
selection.removeAllRanges(); selection.addRange(range);
window.uiAudit = { first, selection: selection.toString(), added: 0, removed: 0, records: 0 };
window.uiAudit.observer = new MutationObserver(records => {
window.uiAudit.records += records.length;
for (const record of records) {
window.uiAudit.added += record.addedNodes.length;
window.uiAudit.removed += record.removedNodes.length;
}
});
window.uiAudit.observer.observe(list, { childList: true, subtree: true, characterData: true });
});
}
async function audit(page) {
return page.evaluate(() => ({
added: window.uiAudit.added, removed: window.uiAudit.removed, records: window.uiAudit.records,
sameNode: window.uiAudit.first === document.querySelector('#message-list article'),
selectionPreserved: getSelection().toString() === window.uiAudit.selection
}));
}
(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 page = await browser.newPage({ viewport: { width: 1280, height: 850 }, deviceScaleFactor: 1 });
const errors = [];
page.on('pageerror', error => errors.push(error.message));
await page.goto(baseURL);
await page.locator('.spirit-svg').waitFor();
await page.screenshot({ path: path.join(evidence, 'ui-kolovertysh-login.png') });
await page.locator('#login-username').fill('mascot_preview');
await page.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'looking');
await page.mouse.move(850, 400);
await page.waitForFunction(() => document.querySelector('#mascot-stage').style.getPropertyValue('--gaze-x') !== '');
await page.route('**/api/v1/auth/sessions', route => route.fulfill({ status: 401, contentType: 'application/json', body: JSON.stringify({error:{message:'Invalid credentials'}}) }));
await page.locator('#login-password').fill('invalid_preview');
await page.locator('#login-form button[type=submit]').click();
await page.locator('#auth-error-art').waitFor({ state: 'visible' });
assert.equal(await page.locator('#mascot-stage').getAttribute('data-mood'), 'error');
await page.unroute('**/api/v1/auth/sessions');
results.checks.push('mascot: input reaction, event-driven gaze, authentication-error illustration');
const mobile = await browser.newPage({ viewport: { width: 320, height: 844 }, deviceScaleFactor: 1 });
mobile.on('pageerror', error => errors.push(error.message));
await mobile.goto(baseURL);
await mobile.locator('#login-password').fill('preview_password');
await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'private');
await mobile.waitForFunction(() => {
const m = getComputedStyle(document.querySelector('.spirit-hand-left')).transform;
return m !== 'none' && Number(m.match(/matrix\((.*)\)/)?.[1].split(',')[4]) > 20;
});
assert(await mobile.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth));
await mobile.screenshot({ path: path.join(evidence, 'ui-kolovertysh-mobile.png'), fullPage: true });
await mobile.locator('[data-password-toggle=login-password]').click();
assert.equal(await mobile.locator('#login-password').getAttribute('type'), 'text');
await mobile.emulateMedia({ reducedMotion: 'reduce' });
assert.equal(await mobile.locator('.spirit-motion').evaluate(e => getComputedStyle(e).animationName), 'none');
results.checks.push('mobile 320px: no horizontal overflow, private/revealed password, reduced motion');
await mobile.locator('#tab-register').click();
await mobile.locator('#register-password').fill('short');
await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'short');
await mobile.locator('#register-password').fill('long_preview_password');
await mobile.waitForFunction(() => document.querySelector('#mascot-stage').dataset.mood === 'private');
await mobile.setViewportSize({ width: 390, height: 844 });
assert(await mobile.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth));
results.checks.push('registration: short-password/private states, 390px without overflow');
await mobile.close();
const alice = await account('alice', 'Проверка интерфейса');
const bob = await account('bob', 'Собеседник');
const chat = await call('POST', '/api/v1/chats', {
title: 'Проверка интерфейса ' + randomUUID().slice(0, 4), member_ids: [alice.user.id, bob.user.id]
}, alice);
const seeded = [];
const phrases = ['Привет! Проверяю обновлённый чат.', 'Теперь сообщения собраны аккуратнее.', 'Старую историю можно читать без скачков.', 'Да, и выделенный текст сохраняется.', 'Новые сообщения появляются внизу.', 'К ним можно перейти отдельной кнопкой.'];
for (let n = 0; n < 75; n++) {
seeded.push(await call('POST', `/api/v1/chats/${chat.id}/messages`, {
text: phrases[n % phrases.length] + (n % 10 === 0 ? ' Проверка длинного сообщения: строка должна переноситься внутри пузырька и оставаться читаемой на телефоне.' : '')
}, Math.floor(n / 3) % 2 ? bob : alice));
}
if (process.env.MESSENGER_BASELINE_APP) {
const baseline = await browser.newPage({ viewport: { width: 1280, height: 850 } });
await baseline.route('**/app.js', route => route.fulfill({ contentType: 'text/javascript', path: process.env.MESSENGER_BASELINE_APP }));
await login(baseline, alice); await openHistory(baseline, chat);
await observeList(baseline); await pollOnce(baseline, chat);
results.before = await audit(baseline);
assert(results.before.removed > 0 && !results.before.sameNode);
await baseline.locator("#logout").click();
await baseline.locator("#auth-screen").waitFor({ state: "visible" });
await baseline.close();
}
await page.route('**/api/ui/chats?limit=100', route => route.fulfill({ status: 503, contentType: 'application/json', body: JSON.stringify({error:{message:'Сервис временно недоступен'}}) }));
await login(page, alice);
await page.locator('#workspace-error').waitFor({state:'visible'});
await decodeVisibleImage(page, '#workspace-error img');
await page.screenshot({path:path.join(evidence,'ui-kolovertysh-error.png')});
await page.unroute('**/api/ui/chats?limit=100');
await page.locator('#retry-chats').click();
await page.locator('#welcome').waitFor({state:'visible'});
const chatRow = page.locator(`[data-chat-id="${chat.id}"]`);
await chatRow.waitFor();
assert.equal(await chatRow.locator('.chat-preview').textContent(), 'Вы: ' + seeded.at(-1).text);
assert.equal(await chatRow.locator('time').getAttribute('datetime'), seeded.at(-1).created_at);
const avatar = await chatRow.locator('.avatar svg').evaluate(e => e.outerHTML);
await page.locator('#refresh-chats').click();
await page.waitForFunction(() => !document.querySelector('#refresh-chats').classList.contains('is-loading'));
assert.equal(await chatRow.locator('.avatar svg').evaluate(e => e.outerHTML), avatar);
assert.equal(await chatRow.locator('.avatar svg').evaluate(e => getComputedStyle(e).stroke), 'none');
results.checks.push('chat previews: latest text and timestamp, deterministic SVG avatar survives refresh without inherited icon stroke');
assert(await page.locator('#workspace-error').isHidden());
assert.equal(await page.locator('#mascot-stage').evaluate(e => e.classList.contains('is-visible')), false);
results.checks.push('initial chat-list failure: illustrated retry state, successful recovery, hidden mascot paused');
const emptyChat = await call('POST', '/api/v1/chats', {title:'Пустой разговор ' + randomUUID().slice(0,4), member_ids:[alice.user.id]}, alice);
await page.locator('#refresh-chats').click();
await page.getByRole('button', {name:new RegExp(emptyChat.title)}).waitFor();
const messageRoute = `**/api/ui/chats/${emptyChat.id}/messages?limit=50`;
await page.route(messageRoute, route => route.fulfill({status:503,contentType:'application/json',body:JSON.stringify({error:{message:'Сервис временно недоступен'}})}));
await page.getByRole('button', {name:new RegExp(emptyChat.title)}).click();
await page.locator('#conversation-error').waitFor({state:'visible'});
assert(await page.locator('#empty-conversation').isHidden());
await page.unroute(messageRoute);
await page.locator('#retry-messages').click();
await page.locator('#empty-conversation').waitFor({state:'visible'});
assert(await page.locator('#conversation-error').isHidden());
await decodeVisibleImage(page, '#empty-conversation img');
await page.screenshot({path:path.join(evidence,'ui-kolovertysh-empty.png')});
results.checks.push('message-load failure does not look empty; retry recovers to illustrated empty conversation');
await page.reload();
await page.locator('#welcome').waitFor({state:'visible'});
await decodeVisibleImage(page, '.welcome-illustration');
await page.screenshot({ path: path.join(evidence, 'ui-illustration-welcome.png') });
await openHistory(page, chat);
const expected = [...seeded].sort((a, b) => a.created_at.localeCompare(b.created_at) || a.id.localeCompare(b.id)).map(m => m.id);
assert.deepEqual(await page.locator('article.message').evaluateAll(nodes => nodes.map(n => n.dataset.messageId)), expected);
assert(await page.locator('article.message.grouped').count() > 0);
await observeList(page); await pollOnce(page, chat);
results.after = await audit(page);
assert.equal(results.after.records, 0, 'unchanged poll mutated message list');
assert(results.after.sameNode && results.after.selectionPreserved);
results.checks.push('75 messages across two pages: order, unique IDs, grouping');
results.checks.push('unchanged poll: zero message-list mutations, original node and selection preserved');
await page.locator('#message-scroll').evaluate(e => { e.scrollTop = 0; });
const beforeScroll = await page.locator('#message-scroll').evaluate(e => e.scrollTop);
const arrival = await call('POST', `/api/v1/chats/${chat.id}/messages`, { text: 'Новое сообщение пришло, пока вы читали историю.' }, bob);
await page.locator(`article[data-message-id="${arrival.id}"]`).waitFor();
assert.equal(await page.locator('#message-scroll').evaluate(e => e.scrollTop), beforeScroll);
await page.waitForFunction(() => document.querySelector('#jump-latest').textContent.includes('Новые сообщения: 1'));
assert((await audit(page)).sameNode && (await audit(page)).selectionPreserved);
await page.locator('#jump-latest').click();
await page.waitForFunction(() => document.querySelector('#jump-latest').hidden);
results.checks.push('incoming message: original nodes/selection/scroll preserved, new-message button returns to bottom');
await page.locator('#message-input').fill('Сообщение отправлено из браузера.');
await page.locator('#send-message').click();
await page.waitForFunction(() => document.querySelectorAll('article.message').length === 77);
assert.equal(await chatRow.locator('.chat-preview').textContent(), 'Вы: Сообщение отправлено из браузера.');
const ids = await page.locator('article.message').evaluateAll(nodes => nodes.map(n => n.dataset.messageId));
assert.equal(new Set(ids).size, ids.length);
await pollOnce(page, chat);
assert.equal(await page.locator('article.message').count(), 77);
results.checks.push('own send followed by poll: no duplicate messages');
const retryKeys = [];
const retryRoute = `**/api/v1/chats/${chat.id}/messages`;
await page.route(retryRoute, async route => {
retryKeys.push(route.request().headers()['idempotency-key']);
if (retryKeys.length === 1) {
const committed = await route.fetch();
assert.equal(committed.status(), 201);
await route.abort('failed');
} else await route.continue();
});
await page.locator('#message-input').fill('Повтор после потерянного ответа.');
await page.locator('#send-message').click();
await page.getByText('Ответ не получен. Повторите отправку: сообщение не продублируется.', {exact:true}).waitFor();
await page.locator('#send-message').click();
await page.waitForFunction(() => document.querySelector('#message-input').value === '');
await pollOnce(page, chat);
assert.equal(retryKeys.length, 2);
assert(retryKeys[0] && retryKeys[0] === retryKeys[1]);
assert.equal(await page.locator('article.message').count(), 78);
await page.unroute(retryRoute);
results.checks.push('lost response after COMMIT: manual retry preserves key and creates one message');
await page.locator('#toast').waitFor({ state: 'hidden' });
await page.locator('#message-scroll').evaluate(e => { e.scrollTop = e.scrollHeight; });
await page.locator('#conversation').evaluate(e => Promise.all(e.getAnimations({ subtree: true }).map(a => a.finished)));
await page.screenshot({ path: path.join(evidence, 'ui-optimized-chat.png') });
await page.setViewportSize({ width: 390, height: 844 });
await page.waitForFunction(() => document.documentElement.clientWidth === 390);
await page.locator('#message-scroll').evaluate(e => { e.scrollTop = e.scrollHeight; });
assert(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth));
await page.screenshot({ path: path.join(evidence, 'ui-optimized-chat-mobile.png') });
await page.locator('#show-members').click();
assert.equal(await page.locator('#members-list .avatar svg').count(), 2);
assert(await page.locator('#members-dialog').evaluate(e => e.scrollWidth <= e.clientWidth));
await page.locator('#members-dialog [data-close-dialog]').click();
results.checks.push('mobile conversation 390px: no horizontal overflow');
await page.locator('#back-to-chats').click();
await page.locator('#logout').click();
await page.locator('#auth-screen').waitFor({ state: 'visible' });
results.checks.push('welcome, empty-conversation and error illustrations decoded when shown');
assert.deepEqual(errors, []);
results.checks.push('no uncaught browser errors');
results.fixture = { chat_id: chat.id, messages: 78 };
await fs.writeFile(path.join(evidence, 'ui-optimization.json'), JSON.stringify(results, null, 2) + '\n');
console.log(JSON.stringify(results, null, 2));
})().catch(error => {
console.error(error.stack || error.message);
process.exitCode = 1;
}).finally(async () => {
for (const actor of sessions) {
try { await call('DELETE', '/api/v1/auth/sessions/current', undefined, actor); } catch {}
}
await browser?.close(); await api?.dispose();
});