Files
music_quiz/e2e/duel.e2e.ts

332 lines
23 KiB
TypeScript

/**
* 이지선다 in real browsers (fake player, no YouTube):
* - 관리자 → 퀴즈 → 파일로 만들기: a CSV with a 조회수 column is taken as 이지선다 (numbers used as written, bad ones left out), 엑셀로 내보내기
* - 이지선다 양식 without 조회수: the server fetches 토픽 + MV (fake YouTube Music), the editor shows them and the 비고
* - 방 설정 → 이지선다 → only 이지선다 퀴즈 are listed; 2 questions from 4 songs
* - three players: tapping a card plays it and picks it, picks move, avatars show under the cards, the views come at
* the end, alone on the higher card against two = 역배 +2; results with the 역배 column (phone screen too)
* - real YouTube: tapping A plays it with sound, B stops A and plays, A again goes on where it stopped
* Run: bun run build && bun e2e/duel.e2e.ts (needs /usr/bin/google-chrome; the YouTube step needs internet, skip with E2E_NO_YT=1)
*/
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright-core';
import { mkdirSync, 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 { readXlsx } from '../packages/shared/src/sheet';
const PORT = Number(process.env.E2E_PORT ?? 4629);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
const TMP = mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-e2e-'));
const SUPER = '900000000000000001';
const app = startServer({
config: loadConfig({ PORT: String(PORT), DB_PATH: join(TMP, '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'),
stopWaitMs: 200,
discordExchange: async (code) => ({ id: code, username: 'u', global_name: '사금향', avatar: null }),
gameTiming: { limitMs: 9000, revealMs: 6000 },
// 조회수 자동: duelvid0006 has 토픽 + MV, duelvid0007 only a 토픽
quizAdmin: {
viewsDelayMs: 300,
viewsSource: async () => ({
songPair: async (id) =>
id === 'duelvid0006'
? { type: 'MUSIC_VIDEO_TYPE_ATV', other: { videoId: 'duelmv00006', type: 'MUSIC_VIDEO_TYPE_OMV' } }
: { type: 'MUSIC_VIDEO_TYPE_ATV', other: null },
viewCount: async (id) => ({ duelvid0006: 153_021_540, duelmv00006: 120_456_643, duelvid0007: 4_321 })[id] ?? 0,
}),
},
});
const db = app.db;
const VIEWS: Record<string, number> = { '노래1': 120_000_000, '노래2': 34_000_000, '노래3': 5_000_000, '노래4': 12_345 };
const browser: Browser = await chromium.launch({
executablePath: process.env.CHROME ?? '/usr/bin/google-chrome',
headless: true,
args: ['--autoplay-policy=document-user-activation-required'],
});
const errors: string[] = [];
const step = async (name: string, fn: () => Promise<void>) => {
const t0 = performance.now();
try {
await fn();
console.log(`✓ ${name} (${Math.round(performance.now() - t0)}ms)`);
} catch (e) {
console.log(`✗ ${name}: ${(e as Error).message.split('\n')[0]}`);
throw e;
}
};
const expect = (ok: unknown, msg: string) => {
if (!ok) throw new Error(msg);
};
async function fakeDiscord(ctx: BrowserContext, discordId: string) {
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=${discordId}&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>` });
});
}
async function guestPage(name: string, opts: { width?: number; height?: number; mobile?: boolean; fake?: boolean; initMs?: number } = {}): Promise<Page> {
const ctx = await browser.newContext({ viewport: { width: opts.width ?? 1440, height: opts.height ?? 900 }, locale: 'ko-KR', isMobile: opts.mobile, hasTouch: opts.mobile });
if (opts.fake !== false) await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1'));
if (opts.initMs) await ctx.addInitScript((ms) => localStorage.setItem('mq:fakeInitMs', String(ms)), opts.initMs);
const p = await ctx.newPage();
p.on('pageerror', (e) => errors.push(`${name}: ${e.message}`));
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;
}
const AXE = readFileSync(require.resolve('axe-core/axe.min.js'), 'utf8');
/** axe-core on this screen (docs/03 접근성): no violations allowed. */
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'] }));
const v = res.violations as { id: string; impact: string; nodes: { target: string[] }[] }[];
expect(v.length === 0, `접근성 ${name}: ${v.map((x) => `${x.id}[${x.impact}](${x.nodes.length}) ${x.nodes[0]?.target?.join(' ')}`).join('; ')}`);
}
const card = (p: Page, side: 'A' | 'B') => p.locator('.duel-card').nth(side === 'A' ? 0 : 1);
const cardTitle = async (p: Page, side: 'A' | 'B') => (await card(p, side).locator('.duel-title').innerText()).trim();
let failed = false;
try {
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1'));
await fakeDiscord(ctx, SUPER);
const host = await ctx.newPage();
host.on('pageerror', (e) => errors.push(`host: ${e.message}`));
await host.goto(`${ORIGIN}/api/auth/discord/start`);
await host.waitForURL(`${ORIGIN}/**`);
let quizId = 0;
await step('파일로 만들기: 조회수 열이 있는 CSV → 이지선다로 골라짐, 읽을 수 없는 조회수 줄은 빠짐 → 4곡으로 만들기 → 내보내기', async () => {
const csv = ['유튜브 링크,제목,가수,조회수', 'https://youtu.be/duelvid0001,노래1,가수1,1.2억', 'duelvid0002,노래2,가수2,"34,000,000"', 'https://youtu.be/duelvid0003,노래3,가수3,500만', 'https://youtu.be/duelvid0004,노래4,가수4,12345회', 'https://youtu.be/duelvid0005,노래5,가수5,많음'].join('\n');
await host.goto(`${ORIGIN}/admin/quizzes`);
await host.getByRole('button', { name: /^파일로 만들기/ }).click();
await host.getByLabel('퀴즈 파일').setInputFiles({ name: '조회수 대결.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) });
await host.getByText('빠지는 줄 1개').waitFor();
expect((await host.getByRole('radio', { name: /이지선다/ }).getAttribute('aria-checked')) === 'true', '조회수 열이 있는데 이지선다로 골라지지 않음');
await host.getByText('조회수를 읽을 수 없어요 (많음)').waitFor();
await host.locator('td', { hasText: '1.2억회' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-file-preview.png'), fullPage: true });
await host.getByRole('button', { name: '4곡으로 이지선다 만들기' }).click();
await host.waitForURL(/\/admin\/quizzes\/\d+$/);
quizId = Number(new URL(host.url()).pathname.split('/').pop());
await host.locator('.quiz-songs tbody tr').nth(3).waitFor();
const q = db.query<{ kind: string }, [number]>('SELECT kind FROM custom_quizzes WHERE id = ?').get(quizId)!;
const views = db.query<{ title: string; views: number }, [number]>('SELECT title, views FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos').all(quizId);
expect(q.kind === 'duel', `퀴즈 종류: ${q.kind}`);
expect(JSON.stringify(views) === JSON.stringify(Object.entries(VIEWS).map(([title, v]) => ({ title, views: v }))), `저장된 조회수: ${JSON.stringify(views)}`);
await host.getByText('🆚 이지선다').first().waitFor();
const [dl] = await Promise.all([host.waitForEvent('download'), host.getByRole('button', { name: /엑셀로 내보내기/ }).click()]);
const back = (await readXlsx(new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer())))[0]!.rows;
expect(back[0]!.includes('조회수') && back[1]![4] === '120000000', `내보낸 내용: ${JSON.stringify(back.slice(0, 2))}`);
});
await step('이지선다 양식(조회수 열 없음) → 자동: 올린 뒤 토픽 + MV 조회수를 불러오고, 토픽만 있는 곡은 비고로 표시', async () => {
await host.goto(`${ORIGIN}/admin/quizzes`);
await host.getByRole('button', { name: /^파일로 만들기/ }).click();
await host.getByRole('radio', { name: /이지선다/ }).click();
const [dl] = await Promise.all([host.waitForEvent('download'), host.getByRole('button', { name: /빈 양식 받기/ }).click()]);
const template = (await readXlsx(new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer())))[0]!.rows;
expect(!template[0]!.includes('조회수'), `양식 열: ${JSON.stringify(template[0])}`);
const csv = [template[0]!.join(','), '1,https://youtu.be/duelvid0006,라일락,아이유,,', '2,https://youtu.be/duelvid0007,토픽만,누구,,'].join('\n');
await host.getByLabel('퀴즈 파일').setInputFiles({ name: '자동 조회수.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) });
// no 조회수 column: the 이지선다 picked above stays
await host.locator('td', { hasText: '토픽만' }).waitFor();
expect((await host.getByRole('radio', { name: /이지선다/ }).getAttribute('aria-checked')) === 'true', '조회수 열이 없는 파일에서 이지선다 선택이 풀림');
expect((await host.locator('td', { hasText: /^자동$/ }).count()) === 2, '미리보기의 조회수가 자동으로 안 보임');
await host.getByRole('button', { name: '2곡으로 이지선다 만들기' }).click();
await host.waitForURL(/\/admin\/quizzes\/\d+$/);
const rows = host.locator('.quiz-songs tbody tr');
await rows.nth(0).getByText('2.7억회').waitFor();
await rows.nth(0).getByText('토픽 1.5억 · MV 1.2억').waitFor();
await rows.nth(1).getByText('MV 없음 (토픽 조회수만)').waitFor();
// taking in the fetched numbers is not an unsaved change
await host.getByText('저장됨').waitFor();
await rows.nth(0).click();
await host.getByText(/273,478,183회.*= 토픽 153,021,540회 \+ MV 120,456,643회/).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-views-auto.png'), fullPage: true });
const id = Number(new URL(host.url()).pathname.split('/').pop());
const saved = db.query<{ title: string; views: number }, [number]>('SELECT title, views FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos').all(id);
expect(JSON.stringify(saved) === JSON.stringify([{ title: '라일락', views: 273_478_183 }, { title: '토픽만', views: 4_321 }]), `저장된 조회수: ${JSON.stringify(saved)}`);
});
let code = '';
const g1 = await guestPage('철수');
const g2 = await guestPage('영희', { width: 390, height: 844, mobile: true });
const all = [host, g1, g2];
await step('방 설정 → 이지선다: 이지선다 퀴즈만 보이고 고르면 "퀴즈 곡 4곡 · 2문제", 손님 2명 입장', async () => {
code = await host.evaluate(async () => (await (await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })).json()).code as string);
await host.goto(`${ORIGIN}/r/${code}`);
await host.locator('.pool-banner').waitFor();
await host.getByRole('radio', { name: '🆚 이지선다' }).click();
await host.getByText('방 설정에서 이지선다 퀴즈를 골라 주세요.').waitFor();
const list = host.getByRole('listbox', { name: '이지선다 퀴즈 목록' });
await list.getByRole('option').first().waitFor();
// the two 이지선다 quizzes made above, no 일반 퀴즈
const names = await list.getByRole('option').allInnerTexts();
expect(names.length === 2 && names.some((n) => n.includes('조회수 대결')) && names.some((n) => n.includes('자동 조회수')), `이지선다 퀴즈 목록: ${JSON.stringify(names)}`);
await list.getByRole('option', { name: /조회수 대결/ }).click();
await host.getByText('퀴즈 곡 4곡').waitFor();
await host.locator('.pool-banner', { hasText: '2문제' }).waitFor();
expect((await host.getByRole('radiogroup', { name: '제한 시간' }).getByRole('radio', { name: '30초' }).getAttribute('aria-checked')) === 'true', '제한 시간 기본값이 30초가 아님');
for (const p of [g1, g2]) {
await p.goto(`${ORIGIN}/r/${code}`);
await p.locator('.pool-banner').waitFor();
}
await host.locator('.pl', { hasText: '영희' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-room.png'), fullPage: true });
});
await step('1번: 카드를 누르면 그 곡이 나오고 고른 게 됨, 바꾸기, 고른 사람 프로필이 카드 밑에', async () => {
await host.getByRole('button', { name: '게임 시작' }).click();
for (const p of all) await p.locator('.duel-card').nth(1).waitFor({ timeout: 8000 });
const a = await cardTitle(host, 'A');
const b = await cardTitle(host, 'B');
expect(VIEWS[a] && VIEWS[b], `모르는 곡: ${a}, ${b}`);
expect((await card(host, 'A').locator('.duel-views').innerText()).includes('?'), '시간 전에 조회수가 보임');
const high = VIEWS[a]! > VIEWS[b]! ? 'A' : 'B';
const low = high === 'A' ? 'B' : 'A';
// 철수 goes high first, then changes to low; 영희 picks low; the host alone on high
await card(g1, high).click();
await card(host, high).locator('.duel-pick').first().waitFor();
await card(g1, low).click();
await card(g2, low).click();
await card(host, high).click();
await host.waitForFunction(([h, l]) => {
const cards = document.querySelectorAll('.duel-card');
const n = (i: number) => cards[i]?.querySelectorAll('.duel-pick').length;
return n(h as number) === 1 && n(l as number) === 2;
}, [high === 'A' ? 0 : 1, low === 'A' ? 0 : 1]);
expect(await card(host, high).getAttribute('aria-pressed') === 'true', '방장이 고른 카드 표시가 없음');
await card(host, high).locator('.duel-state', { hasText: '재생 중' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-play.png'), fullPage: true });
await g2.screenshot({ path: join(SHOTS, 'duel-play-phone.png'), fullPage: true });
await audit(host, 'PC 카드 고르기');
await audit(g2, '폰 카드 고르기');
await host.locator('.duel-card.won').waitFor({ timeout: 15000 });
expect((await card(host, high).getAttribute('class'))!.includes('won'), '높은 카드가 이긴 걸로 안 보임');
await host.getByText('역배 성공').first().waitFor();
const views = await card(host, high).locator('.duel-views').innerText();
expect(views.includes('조회수') && !views.includes('?'), `결과 때 조회수가 안 보임: ${views}`);
await card(host, high).locator('.gain', { hasText: '+2' }).waitFor();
await host.locator('.sb.me .sc', { hasText: '2' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-reveal.png'), fullPage: true });
await g2.screenshot({ path: join(SHOTS, 'duel-reveal-phone.png'), fullPage: true });
await audit(host, 'PC 결과 공개');
await g1.emulateMedia({ colorScheme: 'dark' });
await audit(g1, 'PC 다크 결과 공개');
await g1.screenshot({ path: join(SHOTS, 'duel-reveal-dark.png'), fullPage: true });
});
await step('2번: 새 두 곡, 아무도 안 고르면 0점 → 결과 화면에 역배 성공 1', async () => {
await host.locator('.gbar .q', { hasText: '문제 2 / 2' }).waitFor({ timeout: 12000 });
const titles = [await cardTitle(host, 'A'), await cardTitle(host, 'B')];
expect(titles.every((t) => VIEWS[t]), `2번 곡: ${titles}`);
await host.getByRole('heading', { name: '🏁 게임 결과' }).waitFor({ timeout: 25000 });
const row = host.locator('.data-table.rank tbody tr').first();
const cells = await row.locator('td').allInnerTexts();
expect(cells[1] === '사금향' && cells[2] === '2' && cells[3] === '1' && cells[4] === '1', `결과 첫 줄: ${cells}`);
await host.locator('.songlist li', { hasText: '역배' }).waitFor();
await host.screenshot({ path: join(SHOTS, 'duel-result.png'), fullPage: true });
await audit(host, 'PC 게임 결과');
});
await step('플레이어 준비 전에 누르기: A→B면 B만 나오고 A는 안 나옴, A→A(멈춤)면 둘 다 안 나옴', async () => {
db.query("UPDATE custom_quizzes SET visibility = 'public' WHERE id = ?").run(quizId);
// players that get ready 5s late, so both taps land before
const x = await guestPage('늦은준비1', { initMs: 5000 });
const y = await guestPage('늦은준비2', { initMs: 5000 });
const rc = await x.evaluate(async () => (await (await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })).json()).code as string);
await x.goto(`${ORIGIN}/r/${rc}`);
await x.getByRole('radio', { name: '🆚 이지선다' }).click();
await x.getByRole('listbox', { name: '이지선다 퀴즈 목록' }).getByRole('option', { name: /조회수 대결/ }).click();
await x.getByText('퀴즈 곡 4곡').waitFor();
await y.goto(`${ORIGIN}/r/${rc}`);
await x.locator('.pl', { hasText: '늦은준비2' }).waitFor();
await x.getByRole('button', { name: '게임 시작' }).click();
await Promise.all([x, y].map((p) => p.locator('.duel-card').nth(1).waitFor({ timeout: 8000 })));
await card(x, 'A').click();
await card(x, 'B').click();
await card(y, 'A').click();
await card(y, 'A').click();
// nothing has loaded yet (state 1 = playing; the fake's pause shows 2)
const before = await x.evaluate(() => [(window as any).mqDuel.state('a'), (window as any).mqDuel.state('b')]);
expect(!before.includes(1) && !before.includes(3), `준비 전이 아님 (상태 ${before})`);
await x.waitForFunction(() => (window as any).mqDuel.state('b') === 1, null, { timeout: 8000 });
await x.waitForTimeout(500);
const st = (p: Page) => p.evaluate(() => ({ a: (window as any).mqDuel.state('a'), b: (window as any).mqDuel.state('b') }));
const sx = await st(x);
const sy = await st(y);
expect(sx.a !== 1 && sx.b === 1, `A→B: B만 나와야 함 ${JSON.stringify(sx)}`);
expect(sy.a !== 1 && sy.b !== 1, `A→A: 둘 다 멈춰야 함 ${JSON.stringify(sy)}`);
expect((await x.locator('.duel-card.playing').count()) === 1 && (await card(x, 'B').getAttribute('class'))!.includes('playing'), 'A→B 화면 표시가 B가 아님');
expect((await y.locator('.duel-card.playing').count()) === 0, 'A→A 화면에 재생 중 표시가 남음');
await x.context().close();
await y.context().close();
});
if (!process.env.E2E_NO_YT) {
await step('실제 유튜브: A를 누르면 소리 나게 재생, B를 누르면 A가 멈추고 B 재생, 다시 A는 멈춘 곳부터 이어서', async () => {
const r = await host.evaluate(async () => {
const item = (videoId: string, title: string, views: number) => ({ songId: null, videoId, title, artist: '가수', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views });
const res = await fetch('/api/admin/quizzes/file', {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name: '유튜브 대결', kind: 'duel', items: [item('VO88htcm09E', '광', 10), item('Q7Q_qavUPdM', '가져가', 20)] }),
});
return (await res.json()).id as number;
});
db.query("UPDATE custom_quizzes SET visibility = 'public' WHERE id = ?").run(r);
const x = await guestPage('유튜브손님', { fake: false });
const rc = await x.evaluate(async () => (await (await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })).json()).code as string);
await x.goto(`${ORIGIN}/r/${rc}`);
await x.getByRole('radio', { name: '🆚 이지선다' }).click();
await x.getByRole('listbox', { name: '이지선다 퀴즈 목록' }).getByRole('option', { name: /유튜브 대결/ }).click();
await x.getByText('퀴즈 곡 2곡').waitFor();
await x.getByRole('button', { name: '게임 시작' }).click();
await x.locator('.duel-card').nth(1).waitFor({ timeout: 8000 });
const st = (side: 'a' | 'b') => x.evaluate((sd) => ({ state: (window as any).mqDuel.state(sd), time: (window as any).mqDuel.time(sd), muted: (window as any).mqDuel.muted(sd) }), side);
// both cards load muted first
await x.waitForFunction(() => (window as any).mqDuel?.state('a') === 2 && (window as any).mqDuel?.state('b') === 2, null, { timeout: 20000 });
await card(x, 'A').click();
await x.waitForFunction(() => (window as any).mqDuel.state('a') === 1 && (window as any).mqDuel.time('a') > 1.2, null, { timeout: 8000 });
const a1 = await st('a');
expect(!a1.muted, `A가 소리 없이 재생 ${JSON.stringify(a1)}`);
await card(x, 'B').click();
await x.waitForFunction(() => (window as any).mqDuel.state('b') === 1 && (window as any).mqDuel.state('a') === 2, null, { timeout: 8000 });
const aStop = (await st('a')).time;
const b1 = await st('b');
expect(!b1.muted, `B가 소리 없이 재생 ${JSON.stringify(b1)}`);
await x.waitForTimeout(600);
await card(x, 'A').click();
await x.waitForFunction(() => (window as any).mqDuel.state('a') === 1 && (window as any).mqDuel.state('b') === 2, null, { timeout: 8000 });
const a2 = await st('a');
console.log(` A 멈춘 위치 ${aStop.toFixed(2)}초 → 다시 눌렀을 때 ${a2.time.toFixed(2)}초`);
expect(a2.time >= aStop - 0.3 && !a2.muted, `A가 이어서 나오지 않음 ${JSON.stringify({ aStop, a2 })}`);
await card(x, 'A').locator('.duel-state', { hasText: '재생 중' }).waitFor();
await x.screenshot({ path: join(SHOTS, 'duel-youtube.png') });
await x.context().close();
});
}
expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`);
} catch (e) {
console.log(e instanceof Error ? e.message.slice(0, 400) : e);
for (const pg of browser.contexts().flatMap((c) => c.pages())) await pg.screenshot({ path: join(SHOTS, `duel-fail-${Math.random().toString(36).slice(2, 6)}.png`) }).catch(() => {});
failed = true;
} finally {
await browser.close();
await app.stop();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);