/** * Проверка визуальных требований на живом экране: * крупный счёт, крупный ответ, баннер «Отвечает» и настоящая картинка. * * Запуск против тестового сервера: * $env:PORT='3100'; $env:QUIZ_ROOM='TEST'; $env:QUIZ_HOST_TOKEN='smoke-token'; npm start * $env:QUIZ_URL='http://127.0.0.1:3100'; node scripts/check-visuals.mjs */ import { writeFileSync, rmSync } from 'node:fs' import { fileURLToPath } from 'node:url' import puppeteer from 'puppeteer-core' import { io } from 'socket.io-client' const BASE = process.env.QUIZ_URL ?? 'http://127.0.0.1:3100' const TOKEN = process.env.QUIZ_HOST_TOKEN ?? 'smoke-token' const ROOM = process.env.QUIZ_ROOM ?? 'TEST' const ROOT = fileURLToPath(new URL('../', import.meta.url)) const PACK_ID = 'visual-check' const PACK_FILE = `${ROOT}content/packs/${PACK_ID}.json` const CHROME = process.env.CHROME_PATH ?? 'C:/Program Files/Google/Chrome/Application/chrome.exe' const pack = { id: PACK_ID, title: 'Проверка картинки', settings: { wrongPenalty: 'value', buzzers: true, finalEnabled: false, defaultTimeLimit: 40, answerTimeLimit: 20, auctionTimeLimit: 30, betTimeLimit: 20, }, rounds: [ { id: 'r1', title: 'Раунд с картинкой', themes: [ { id: 't1', title: 'Кадр', cells: [ { value: 100, kind: 'normal', question: { text: 'Что за кадр на экране?', media: { kind: 'image', src: '/media/demo/frame.svg' }, answer: 'Один дома', }, }, ], }, ], }, ], } writeFileSync(PACK_FILE, JSON.stringify(pack, null, 2), 'utf8') /** Соединение с ролью ведущего: нужно, чтобы вернуть комнату в лобби. */ async function connectAs(auth) { const socket = io(BASE, { auth, transports: ['websocket'], reconnection: false }) await new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error('не подключился')), 10000) socket.once('hello', () => { clearTimeout(timer) resolve() }) socket.once('connect_error', (error) => { clearTimeout(timer) reject(error) }) }) return socket } // Прошлый прогон мог оставить партию на середине — тогда пак не подменить. const hostSocket = await connectAs({ room: ROOM, role: 'host', token: TOKEN }) hostSocket.emit('cmd', { cmdId: 'visual-reset', command: { type: 'resetGame' } }) await new Promise((resolve) => setTimeout(resolve, 400)) hostSocket.disconnect() const applied = await fetch(`${BASE}/api/packs/apply?token=${TOKEN}&id=${PACK_ID}`, { method: 'POST', }) const appliedBody = await applied.json() if (!appliedBody.ok) { // Чаще всего партия уже идёт: сервер не меняет пак посреди игры. throw new Error(`не удалось применить временный пак: ${appliedBody.error}`) } // Игрок нужен, чтобы ведущий мог начать партию: в пустом лобби кнопка мертва. const player = io(BASE, { auth: { room: ROOM, role: 'player', name: 'Тест' }, transports: ['websocket'], reconnection: false, }) await new Promise((resolve, reject) => { const timer = setTimeout(() => reject(new Error('игрок не подключился')), 10000) player.once('hello', () => { clearTimeout(timer) resolve() }) player.once('connect_error', (error) => { clearTimeout(timer) reject(error) }) }) const browser = await puppeteer.launch({ executablePath: CHROME, headless: 'new', args: ['--disable-gpu', '--no-first-run'], defaultViewport: { width: 1600, height: 900 }, }) const problems = [] try { const board = await browser.newPage() board.on('pageerror', (error) => problems.push(`board: ${error.message}`)) await board.goto(`${BASE}/board`, { waitUntil: 'networkidle0' }) await board.waitForSelector('.lobby-join', { timeout: 15000 }) const host = await browser.newPage() host.on('pageerror', (error) => problems.push(`host: ${error.message}`)) host.on('dialog', (dialog) => dialog.accept()) await host.goto(`${BASE}/host/${TOKEN}`, { waitUntil: 'networkidle0' }) await host.waitForSelector('.topbar', { timeout: 15000 }) // Сбрасываем прошлую партию, если она осталась от предыдущего прогона. await host.evaluate(() => { const button = Array.from(document.querySelectorAll('button')).find((node) => node.textContent?.includes('Заново'), ) button?.click() }) await new Promise((resolve) => setTimeout(resolve, 400)) console.log('1. старт партии') await host.evaluate(() => { const button = Array.from(document.querySelectorAll('button.primary.big')).find((node) => node.textContent?.includes('Начать игру'), ) button?.click() }) await host.waitForSelector('.round-title', { timeout: 10000 }) await host.evaluate(() => { const button = Array.from(document.querySelectorAll('button.primary.big')).find((node) => node.textContent?.includes('К табло'), ) button?.click() }) await host.waitForSelector('.board', { timeout: 10000 }) console.log('2. открываю клетку с картинкой') await host.click('.cell:not(.closed)') await board.waitForSelector('.media-board img', { timeout: 15000 }) const image = await board.$eval('.media-board img', (node) => ({ width: node.naturalWidth, height: node.naturalHeight, rendered: Math.round(node.getBoundingClientRect().height), viewport: window.innerHeight, })) console.log(` картинка: ${image.width}×${image.height}, на экране ${image.rendered}px`) if (image.width === 0) throw new Error('картинка не загрузилась') if (image.rendered < image.viewport * 0.3) { throw new Error(`картинка слишком мелкая: ${image.rendered}px при экране ${image.viewport}px`) } console.log('3. счёт и номинал крупные') const sizes = await board.evaluate(() => { const box = (selector) => { const node = document.querySelector(selector) if (!node) return 0 return parseFloat(getComputedStyle(node).fontSize) } return { badge: box('.badge'), score: box('.scorebar.large .score-value'), question: box('.question-text'), } }) console.log(` номинал ${sizes.badge}px, счёт ${sizes.score}px, вопрос ${sizes.question}px`) if (sizes.badge < 28) throw new Error(`номинал мелкий: ${sizes.badge}px`) if (sizes.score < 24) throw new Error(`счёт мелкий: ${sizes.score}px`) console.log('4. игрок нажимает — табло крупно показывает, кто отвечает') player.emit('cmd', { cmdId: 'visual-buzz', command: { type: 'buzz' } }) await board.waitForSelector('.answerer-name', { timeout: 15000 }) const answerer = await board.$eval('.answerer-name', (node) => ({ text: node.textContent?.trim(), size: parseFloat(getComputedStyle(node).fontSize), })) console.log(` отвечает: ${answerer.text}, ${answerer.size}px`) if (answerer.text !== 'Тест') throw new Error(`не то имя: ${answerer.text}`) if (answerer.size < 40) throw new Error(`имя мелкое: ${answerer.size}px`) console.log('5. вскрытие ответа') await host.waitForSelector('.actions .ok', { timeout: 10000 }) await host.click('.actions .ok') await board.waitForSelector('.answer-hero', { timeout: 10000 }) const revealed = await board.$eval('.answer-hero', (node) => ({ text: node.textContent?.trim(), size: parseFloat(getComputedStyle(node).fontSize), })) console.log(` ответ: «${revealed.text}», ${revealed.size}px`) if (revealed.size < 32) throw new Error(`ответ мелкий: ${revealed.size}px`) if (problems.length > 0) { console.error('\nОшибки на страницах:') for (const problem of problems) console.error(` - ${problem}`) process.exitCode = 1 } else { console.log('\nOK: картинка крупная, счёт и ответ читаются, анимации на месте') } } finally { player.disconnect() await browser.close() await fetch(`${BASE}/api/packs/apply?token=${TOKEN}&id=novy-god-2027`, { method: 'POST' }) rmSync(PACK_FILE, { force: true }) }