Files
music_quiz/e2e/a11y.e2e.ts

137 lines
7.2 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Stage 10 accessibility (docs/03 접근성, docs/10 다듬기): axe-core on 첫 화면 · 대기실 · 게임 · 정답 공개 · 결과 · 관리자 노래,
* PC and phone, light and dark. Any violation (any impact) fails. Run: bun run build && bun e2e/a11y.e2e.ts
*/
import { chromium, type BrowserContext, type Page } from 'playwright-core';
import { mkdtempSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { loadConfig } from '../apps/server/src/config';
import { startServer } from '../apps/server/src/server';
import { Catalog } from '../apps/server/src/collector/catalog';
const PORT = Number(process.env.E2E_PORT ?? 4625);
const ORIGIN = `http://localhost:${PORT}`;
const AXE = readFileSync(require.resolve('axe-core/axe.min.js'), 'utf8');
const SUPER = '900000000000000001';
const app = startServer({
config: loadConfig({
PORT: String(PORT),
DB_PATH: join(mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-a11y-')), 'app.db'),
PUBLIC_ORIGIN: ORIGIN,
SUPERADMIN_DISCORD_IDS: SUPER,
DISCORD_CLIENT_ID: '1561284577564037140',
DISCORD_CLIENT_SECRET: 'e2e',
}),
log: () => {},
staticDir: join(import.meta.dir, '../apps/web/dist'),
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '검사관리자', avatar: null }),
gameTiming: { countdownMs: 300, revealMs: 4000 },
});
{
const c = new Catalog(app.db);
for (let i = 1; i <= 4; i++) {
const [id] = c.upsert({ title: `검사곡${i}`, artists: [{ name: `검사가수${i}` }], year: 2000 + i, genres: ['kpop'], source: 'e2e', ref: String(i) });
c.autoLevel(id!, 'all', 3);
app.db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = 200 WHERE id = ?").run(`fake${String(i).padStart(7, '0')}`, id!);
}
}
const titleOf = (vid: string) => app.db.query<{ title: string }, [string]>('SELECT title FROM songs WHERE youtube_id = ?').get(vid)!.title;
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
let bad = 0;
async function audit(page: Page, name: string) {
await page.addScriptTag({ content: AXE });
const res = await page.evaluate(async () => (window as any).axe.run(document, { resultTypes: ['violations'] }));
if (res.violations.length) {
bad += res.violations.length;
console.log(`✗ ${name}: ${res.violations.map((v: any) => `${v.id}[${v.impact}](${v.nodes.length}) ${v.nodes[0]?.target?.join(' ')}`).join('; ')}`);
} else console.log(`✓ ${name}`);
}
async function guest(ctx: BrowserContext, name: string): Promise<Page> {
await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1'));
const p = await ctx.newPage();
await p.goto(ORIGIN + '/');
await p.getByLabel('게스트 닉네임 (2~12자)').fill(name);
await p.getByRole('button', { name: '게스트로 시작' }).click();
await p.getByRole('button', { name: `내 계정: ${name}` }).waitFor();
return p;
}
try {
let n = 0;
for (const [label, ctxOpts] of [
['PC', { viewport: { width: 1440, height: 900 } }],
['phone', { viewport: { width: 390, height: 844 }, isMobile: true, hasTouch: true }],
] as const) {
for (const theme of ['light', 'dark'] as const) {
const ctx = await browser.newContext({ ...ctxOpts, locale: 'ko-KR', colorScheme: theme });
const first = await ctx.newPage();
await first.goto(ORIGIN + '/');
await first.getByRole('button', { name: '게스트로 시작' }).waitFor();
await audit(first, `${label}/${theme} 첫 화면`);
await first.close();
const p = await guest(ctx, `검사${++n}`);
await p.getByRole('button', { name: '+ 방 만들기' }).click();
await p.waitForURL(/\/r\/\d{6}$/);
await p.locator('.pool-banner').waitFor();
await audit(p, `${label}/${theme} 대기실`);
await p.getByRole('button', { name: '참가 (소리 켜기)' }).click();
await p.getByRole('button', { name: '게임 시작' }).click();
await p.getByRole('button', { name: '그대로 시작' }).click();
await p.locator('.stage .lp.spin').waitFor({ timeout: 10000 });
await p.getByLabel('채팅 입력').fill('모르겠다');
await p.getByLabel('채팅 입력').press('Enter');
await audit(p, `${label}/${theme} 게임 화면`);
const vid = await p.evaluate(() => (window as any).mqPlayer.video() as string);
await p.getByLabel('채팅 입력').fill(titleOf(vid));
await p.getByLabel('채팅 입력').press('Enter');
await p.locator('.reveal').waitFor();
await audit(p, `${label}/${theme} 정답 공개`);
// 다음 문제까지 N초, and 다음 문제 (1명 방: 1/3 → 1) moves on before the 4s reveal ends
if (!/다음 문제까지 \d초/.test(await p.locator('.reveal .next-in').innerText())) throw new Error('다음 문제까지 표시 없음');
await p.locator('.gbtn', { hasText: '다음 문제' }).click();
await p.locator('.gbar .q', { hasText: '문제 2' }).waitFor({ timeout: 2500 });
await p.getByRole('button', { name: '⏹ 끝내기' }).click();
await p.getByRole('button', { name: '끝내기', exact: true }).click();
await p.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
await audit(p, `${label}/${theme} 결과`);
await p.getByRole('link', { name: '← 방 목록' }).click();
await ctx.close();
}
}
// 관리자 노래 화면 (PC, light / dark)
for (const theme of ['light', 'dark'] as const) {
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR', colorScheme: theme });
await ctx.route(`${ORIGIN}/api/auth/discord/start*`, async (route) => {
const res = await fetch(route.request().url(), { redirect: 'manual', headers: { cookie: (await route.request().headerValue('cookie')) ?? '' } });
const consent = new URL(res.headers.get('location')!);
const back = `${ORIGIN}/api/auth/discord/callback?code=${SUPER}&state=${consent.searchParams.get('state')}`;
await route.fulfill({ status: 200, headers: { 'content-type': 'text/html', 'set-cookie': res.headers.get('set-cookie') ?? '' }, body: `<script>location.replace(${JSON.stringify(back)})</script>` });
});
const p = await ctx.newPage();
await p.goto(ORIGIN + '/');
await p.getByRole('link', { name: '디스코드로 로그인' }).click();
await p.getByRole('button', { name: '내 계정: 검사관리자' }).waitFor();
await p.goto(ORIGIN + '/admin/songs');
await p.locator('.data-table tbody tr').first().waitFor();
await audit(p, `PC/${theme} 관리자 노래`);
await p.goto(ORIGIN + '/admin/youtube');
await p.getByRole('button', { name: /^확정 \d/ }).click();
await p.locator('.data-table tbody tr', { hasText: '검사곡1' }).waitFor();
await audit(p, `PC/${theme} 관리자 원곡 찾기`);
await p.goto(ORIGIN + '/admin/stats');
await p.getByRole('heading', { name: '통계' }).waitFor();
await audit(p, `PC/${theme} 관리자 통계`);
await ctx.close();
}
} catch (e) {
console.log(e instanceof Error ? e.message.slice(0, 400) : e);
bad++;
} finally {
await browser.close();
await app.stop();
}
console.log(bad ? `A11Y FAILED (${bad})` : 'A11Y PASSED');
process.exit(bad ? 1 : 0);