447 lines
26 KiB
TypeScript
447 lines
26 KiB
TypeScript
/**
|
|
* Stage 5~7 E2E (docs/10 5단계): three guests play 30 questions to the end in real browsers.
|
|
* Part A uses the fake player (localStorage mq:fakePlayer) so 30 questions run in about a minute without YouTube:
|
|
* start, synced play, answers by chat (정답 줄 + 5줄 블록 on every screen), scores, past questions, buffering pause for
|
|
* everyone, skip / hint / replay votes with Ctrl+K / Ctrl+I / Ctrl+R, a broken video swapped, typing indicator,
|
|
* reconnect mid-game, refresh while the music runs (catch up in sync), results with YouTube links, 이어풀기, 다시 하기, phone / dark screens, the last one out closes the room.
|
|
* Part B plays real YouTube Topic videos in two browsers: sound on after the entry click, same start, 3s clip stop.
|
|
* Run: bun run build && bun e2e/game.e2e.ts (needs /usr/bin/google-chrome; Part B needs internet, skip with E2E_NO_YT=1)
|
|
*/
|
|
import { chromium, type Browser, type Page } from 'playwright-core';
|
|
import { mkdirSync, mkdtempSync } 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 ?? 4621);
|
|
const ORIGIN = `http://localhost:${PORT}`;
|
|
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
|
|
mkdirSync(SHOTS, { recursive: true });
|
|
|
|
const config = loadConfig({
|
|
PORT: String(PORT),
|
|
DB_PATH: join(mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'mq-e2e-')), 'app.db'),
|
|
PUBLIC_ORIGIN: ORIGIN,
|
|
SUPERADMIN_DISCORD_IDS: '900000000000000001',
|
|
});
|
|
const app = startServer({
|
|
config,
|
|
log: () => {},
|
|
staticDir: join(import.meta.dir, '../apps/web/dist'),
|
|
stopWaitMs: 200,
|
|
gameTiming: { countdownMs: 700, revealMs: 700, resumeLeadMs: 300 },
|
|
});
|
|
|
|
// Catalog: 32 fake songs (3 by the same singer) + 3 real Topic videos for part B (another level, so part A never picks them).
|
|
const db = app.db;
|
|
{
|
|
const c = new Catalog(db);
|
|
for (let i = 1; i <= 32; i++) {
|
|
const [id] = c.upsert({ title: `곡${i}`, artists: [{ name: i <= 3 ? '같은가수' : `가수${i}` }], year: 1990 + (i % 30), genres: ['kpop', 'ballad'], source: 'e2e', ref: `f${i}` });
|
|
c.autoLevel(id!, 'all', 3);
|
|
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!);
|
|
if (i <= 2) db.query('INSERT INTO lyrics (song_id, text, source, fetched_at) VALUES (?, ?, ?, 0)').run(id!, `첫 소절 곡${i}\n둘째 줄 ${i}\n셋째 줄\n넷째 줄\n다섯째 줄\n여섯째 줄\n후렴 곡${i}\n후렴 곡${i}`, 'e2e');
|
|
}
|
|
const real: [string, string, string, number][] = [
|
|
['광 (狂)', 'SG워너비', 'VO88htcm09E', 237],
|
|
['가져가', '홍경민', 'Q7Q_qavUPdM', 221],
|
|
['Be Natural', '에스이에스', 'YWP5K88l9G0', 282],
|
|
];
|
|
for (const [title, artist, vid, dur] of real) {
|
|
const [id] = c.upsert({ title, artists: [{ name: artist }], year: 2000, genres: ['kpop'], source: 'e2e', ref: vid });
|
|
c.autoLevel(id!, 'all', 9);
|
|
db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = ?, duration_sec = ? WHERE id = ?").run(vid, dur, id!);
|
|
}
|
|
}
|
|
const titleOf = (vid: string) => db.query<{ title: string; artist: string }, [string]>('SELECT title, artist FROM songs WHERE youtube_id = ?').get(vid)!;
|
|
|
|
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>) => {
|
|
if (process.env.E2E_ONLY_YT && name.startsWith('A:')) return;
|
|
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 guestPage(name: string, opts: { fake?: boolean; width?: number; height?: number; dark?: boolean; mobile?: boolean } = {}): Promise<Page> {
|
|
const ctx = await browser.newContext({
|
|
viewport: { width: opts.width ?? 1440, height: opts.height ?? 900 },
|
|
locale: 'ko-KR',
|
|
colorScheme: opts.dark ? 'dark' : 'light',
|
|
isMobile: opts.mobile,
|
|
hasTouch: opts.mobile,
|
|
});
|
|
if (opts.fake !== false) await ctx.addInitScript(() => localStorage.setItem('mq:fakePlayer', '1'));
|
|
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;
|
|
}
|
|
|
|
async function makeRoom(p: Page, cfg: Record<string, unknown>): Promise<string> {
|
|
const code = await p.evaluate(async (config) => {
|
|
const r = await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ config }) });
|
|
return (await r.json()).code as string;
|
|
}, cfg);
|
|
await p.goto(`${ORIGIN}/r/${code}`);
|
|
await p.locator('.pool-banner').waitFor();
|
|
return code;
|
|
}
|
|
|
|
const video = (p: Page) => p.evaluate(() => (window as any).mqPlayer?.video() as string | null);
|
|
const qText = (p: Page) => p.locator('.gbar .q').innerText();
|
|
/** Wait until this page is on question n with the music running (after the 3·2·1). */
|
|
async function playing(p: Page, n: number, timeout = 15000) {
|
|
await p.locator('.gbar .q', { hasText: new RegExp(`^문제 ${n} `) }).waitFor({ timeout });
|
|
await p.locator('.stage .lp.spin').waitFor({ timeout });
|
|
}
|
|
async function say(p: Page, text: string) {
|
|
const input = p.getByLabel('채팅 입력');
|
|
await input.fill(text);
|
|
await input.press('Enter');
|
|
}
|
|
|
|
let failed = false;
|
|
let code = '';
|
|
try {
|
|
const a = await guestPage('방장');
|
|
const b = await guestPage('철수');
|
|
const c = await guestPage('영희');
|
|
const all = [a, b, c];
|
|
|
|
await step('A: 3명이 대기실에 모여 소리 켜기 → 방장이 시작, 모두 게임 화면 "문제 1 / 30"', async () => {
|
|
code = await makeRoom(a, { count: 30, listenSec: 3, hint: 'manual', hintVotes: '1', skipVotes: '2/3', replayVotes: '1' });
|
|
for (const p of [b, c]) {
|
|
await p.goto(`${ORIGIN}/r/${code}`);
|
|
await p.locator('.pool-banner').waitFor();
|
|
}
|
|
await a.locator('.pl', { hasText: '영희' }).waitFor();
|
|
for (const p of all) await p.getByRole('button', { name: '참가 (소리 켜기)' }).click();
|
|
await a.getByText('조건에 맞는 곡 32곡').waitFor();
|
|
await a.getByRole('button', { name: '게임 시작' }).click();
|
|
for (const p of all) await p.locator('.gbar .q', { hasText: '문제 1 / 30' }).waitFor({ timeout: 8000 });
|
|
await a.locator('.countdown').waitFor({ timeout: 4000 });
|
|
});
|
|
|
|
const answer = async (n: number, who: Page, opts: { wrongFirst?: boolean } = {}) => {
|
|
await playing(who, n);
|
|
const vid = await video(who);
|
|
expect(vid, `${n}번 영상 없음`);
|
|
const s = titleOf(vid!);
|
|
if (opts.wrongFirst) await say(who, '이거 뭐였지');
|
|
await say(who, s.title);
|
|
for (const p of all) await p.locator('.answer-item .ans-text', { hasText: `${s.title} - ${s.artist}` }).last().waitFor({ timeout: 5000 });
|
|
return s;
|
|
};
|
|
|
|
await step('A: 1번 — 3명 같은 곡·같은 시각 재생, 채팅 정답 → 모든 화면에 정답 줄(✔) + 5줄 블록, 점수판 +1, 지난 문제', async () => {
|
|
await Promise.all(all.map((p) => playing(p, 1)));
|
|
const vids = await Promise.all(all.map(video));
|
|
expect(new Set(vids).size === 1, `서로 다른 곡: ${vids.join(',')}`);
|
|
const pos = await Promise.all(all.map((p) => p.evaluate(() => (window as any).mqPlayer.pos() as number)));
|
|
expect(Math.max(...pos) - Math.min(...pos) < 0.3, `재생 위치 차이 ${pos.join(',')}`);
|
|
const s = await answer(1, b, { wrongFirst: true });
|
|
// the line right above the block is the answer line, with ✔
|
|
const item = c.locator('.answer-item').last();
|
|
expect((await item.locator('.chat-line.ok').innerText()).includes(s.title), '정답 줄이 블록 바로 위에 없음');
|
|
expect((await item.locator('.ans-gap').count()) === 4, '공백 줄 수가 다름');
|
|
await a.locator('.sb', { hasText: '철수' }).locator('.sc', { hasText: '1' }).waitFor();
|
|
await c.locator('.hist .h', { hasText: s.title }).waitFor();
|
|
await a.locator('.reveal .big', { hasText: s.title }).waitFor();
|
|
});
|
|
|
|
await step('A: 입력 중 표시 — 영희가 치는 동안 다른 사람 화면에 "영희님이 입력 중…"', async () => {
|
|
await playing(c, 2);
|
|
await c.getByLabel('채팅 입력').fill('음');
|
|
await a.getByText('영희님이 입력 중…').waitFor({ timeout: 4000 });
|
|
await c.getByLabel('채팅 입력').fill('');
|
|
await answer(2, a);
|
|
});
|
|
|
|
await step('A: 3번 — 철수 화면 버퍼링 → 모두 "잠시 멈춤 — 철수님 버퍼링 중", 같은 곳에서 다시 재생', async () => {
|
|
// set once question 3 is being prepared (the reveal of 2 also plays): 철수's next start buffers
|
|
await b.locator('.gbar .q', { hasText: /^문제 3 / }).waitFor({ timeout: 10000 });
|
|
// 철수 needs 2s to buffer again, so the pause is visible
|
|
await b.evaluate(() => Object.assign((window as any).mqFake, { stallNext: true, loadMs: 2000 }));
|
|
await a.getByText('잠시 멈춤 — 철수님 버퍼링 중').waitFor({ timeout: 10000 });
|
|
await c.getByText('잠시 멈춤 — 철수님 버퍼링 중').waitFor({ timeout: 3000 });
|
|
await b.evaluate(() => ((window as any).mqFake.loadMs = 40));
|
|
await answer(3, c);
|
|
});
|
|
|
|
await step('A: 4번 — Ctrl+K 2명(2/3) → 스킵, 회색 블록 "스킵했어요"', async () => {
|
|
await playing(a, 4);
|
|
await a.keyboard.press('Control+k');
|
|
await b.locator('.gbtn', { hasText: '스킵 1/2' }).waitFor();
|
|
await playing(b, 4);
|
|
await b.keyboard.press('Control+k');
|
|
for (const p of all) await p.locator('.answer-item.none', { hasText: '스킵했어요' }).last().waitFor({ timeout: 5000 });
|
|
});
|
|
|
|
await step('A: 5번 — Ctrl+I 힌트(직접선택, 1명) → 초성 공개, Ctrl+R 다시듣기 → "다 같이 다시 들어요"', async () => {
|
|
await playing(c, 5);
|
|
await c.keyboard.press('Control+i');
|
|
for (const p of all) await p.locator('.stage .hint').waitFor({ timeout: 4000 });
|
|
expect(/ㄱ\d+/.test(await a.locator('.stage .hint').innerText()), '초성 힌트 모양이 다름');
|
|
await a.keyboard.press('Control+r');
|
|
await b.locator('.chat-sys', { hasText: '다 같이 다시 들어요' }).waitFor({ timeout: 4000 });
|
|
await answer(5, a);
|
|
});
|
|
|
|
await step('A: 6번 — 한 명 화면에서 영상 오류 150 → 모두 다른 곡으로 바뀌고 번호는 그대로', async () => {
|
|
// the reveal of 5 is still showing: the next load fails on 영희's screen
|
|
await c.evaluate(() => ((window as any).mqFake.failNext = 150));
|
|
await a.locator('.chat-sys', { hasText: '다른 곡으로 바꿨어요' }).waitFor({ timeout: 8000 });
|
|
await a.locator('.gbar .q', { hasText: /^문제 6 \/ 30$/ }).waitFor();
|
|
await answer(6, b);
|
|
});
|
|
|
|
await step('A: 7~30번 — 돌아가며 정답, 15번에 영희 새로고침(다시 소리 켜기 → 그 문제부터 이어서)', async () => {
|
|
for (let n = 7; n <= 30; n++) {
|
|
const who = all[n % 3]!;
|
|
if (n === 15) {
|
|
await c.reload();
|
|
await c.getByRole('button', { name: /참가 \(소리 켜기\)|눌러서 소리 켜기/ }).click({ timeout: 10000 }).catch(() => {});
|
|
}
|
|
await answer(n, who === c && n === 15 ? a : who);
|
|
}
|
|
});
|
|
|
|
await step('A: 결과 화면 — 순위·점수·맞힌 곡·가장 빨리 맞힌 곡, 곡 목록 30개 + 유튜브 링크', async () => {
|
|
for (const p of all) await p.getByRole('heading', { name: '🏁 게임 결과' }).waitFor({ timeout: 10000 });
|
|
const rows = await a.locator('.rank tbody tr').count();
|
|
expect(rows === 3, `순위 줄 ${rows}`);
|
|
expect((await a.locator('.songlist li').count()) === 30, '곡 목록 30개 아님');
|
|
expect((await a.locator('.songlist a[href^="https://youtu.be/"]').count()) === 30, '유튜브 링크 30개 아님');
|
|
const total = await a.locator('.rank tbody td:nth-child(3)').allInnerTexts();
|
|
expect(total.map(Number).reduce((x, y) => x + y, 0) === 29, `점수 합 ${total.join(',')} (스킵 1문제 빼고 29)`);
|
|
await a.screenshot({ path: join(SHOTS, 'stage5-result.png'), fullPage: true });
|
|
expect(!(await b.getByRole('button', { name: /이어풀기/ }).isVisible()), '손님에게 이어풀기 버튼이 보임');
|
|
});
|
|
|
|
await step('A: 이어풀기 → 나온 곡을 뺀 남은 곡만, 점수 이어서 / 다시 하기 → 대기실', async () => {
|
|
await a.getByRole('button', { name: /이어풀기/ }).click();
|
|
await a.locator('.gbar .q', { hasText: /^문제 1 \/ [12]$/ }).waitFor({ timeout: 8000 });
|
|
const total = Number((await qText(a)).split('/')[1]);
|
|
for (let n = 1; n <= total; n++) await answer(n, a);
|
|
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor({ timeout: 10000 });
|
|
await a.getByRole('button', { name: /이어풀기/ }).isDisabled();
|
|
await a.getByRole('button', { name: '↺ 다시 하기' }).click();
|
|
for (const p of all) await p.locator('.pool-banner').waitFor({ timeout: 5000 });
|
|
});
|
|
|
|
await step('A: 게임 화면 휴대폰(390px)·다크 화면', async () => {
|
|
const m = await guestPage('폰손님', { width: 390, height: 844, mobile: true });
|
|
await m.goto(`${ORIGIN}/r/${code}`);
|
|
await m.locator('.pool-banner').waitFor();
|
|
await m.getByRole('button', { name: '참가 (소리 켜기)' }).click();
|
|
const d = await guestPage('다크손님', { dark: true });
|
|
await d.goto(`${ORIGIN}/r/${code}`);
|
|
await d.locator('.pool-banner').waitFor();
|
|
await d.getByRole('button', { name: '참가 (소리 켜기)' }).click();
|
|
await a.getByRole('button', { name: '게임 시작' }).click();
|
|
await playing(m, 1);
|
|
await say(b, '모바일 화면 확인용');
|
|
await m.screenshot({ path: join(SHOTS, 'stage5-game-mobile.png'), fullPage: true });
|
|
await d.screenshot({ path: join(SHOTS, 'stage5-game-dark.png'), fullPage: true });
|
|
await a.screenshot({ path: join(SHOTS, 'stage5-game.png'), fullPage: true });
|
|
const overflow = await m.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
|
|
expect(overflow <= 0, `휴대폰 화면이 가로로 ${overflow}px 넘침`);
|
|
await a.getByRole('button', { name: '⏹ 끝내기' }).click();
|
|
await a.getByRole('button', { name: '끝내기', exact: true }).click();
|
|
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
|
|
for (const p of [m, d]) {
|
|
await p.getByRole('link', { name: '← 방 목록' }).click();
|
|
await p.waitForURL(ORIGIN + '/');
|
|
await p.waitForTimeout(300);
|
|
await p.context().close();
|
|
}
|
|
});
|
|
|
|
await step('A: 모드 3종 — 가수노래(고른 가수 곡만, 위에 "선택한 가수"), 가사보고(음악 없이 가사 카드, 제목은 ○로 가림)', async () => {
|
|
// 가수노래: 같은가수 3곡 중에서만
|
|
await a.getByRole('button', { name: '↺ 다시 하기' }).click();
|
|
await a.locator('.pool-banner').waitFor();
|
|
await a.getByRole('radiogroup', { name: '모드' }).getByRole('radio', { name: /가수노래 맞추기/ }).click();
|
|
await a.getByLabel('가수 검색').fill('같은가수');
|
|
await a.getByRole('option', { name: /같은가수/ }).click();
|
|
await a.getByText('조건에 맞는 곡 3곡').waitFor({ timeout: 5000 });
|
|
await a.getByRole('button', { name: '게임 시작' }).click();
|
|
await a.getByRole('button', { name: '그대로 시작' }).click();
|
|
await playing(a, 1);
|
|
await a.getByText('선택한 가수: 같은가수').waitFor();
|
|
expect(/^곡[123]$/.test(titleOf((await video(a))!).title), '고른 가수 곡이 아님');
|
|
await answer(1, b);
|
|
await a.getByRole('button', { name: '⏹ 끝내기' }).click();
|
|
await a.getByRole('button', { name: '끝내기', exact: true }).click();
|
|
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
|
|
await a.getByRole('button', { name: '↺ 다시 하기' }).click();
|
|
await a.locator('.pool-banner').waitFor();
|
|
// 가사보고: 가사가 있는 2곡
|
|
await a.getByRole('radiogroup', { name: '모드' }).getByRole('radio', { name: /가사보고 맞추기/ }).click();
|
|
await a.getByText('조건에 맞는 곡 2곡').waitFor({ timeout: 5000 });
|
|
await a.getByRole('button', { name: '게임 시작' }).click();
|
|
await a.getByRole('button', { name: '그대로 시작' }).click();
|
|
await c.locator('.lyrics-card').waitFor({ timeout: 8000 });
|
|
const card = await c.locator('.lyrics-card').innerText();
|
|
expect(!/곡\d/.test(card), `가사 카드에 제목이 보임: ${card}`);
|
|
expect(!(await c.locator('.stage .lp').count()), '가사 모드에 LP가 보임');
|
|
const n = /둘째 줄 (\d)/.exec(card)?.[1];
|
|
expect(n, `가사 카드 ${card}`);
|
|
await c.locator('.countdown').waitFor({ state: 'detached', timeout: 4000 });
|
|
await say(c, `곡${n}`);
|
|
for (const p of all) await p.locator('.answer-item .ans-text', { hasText: `곡${n} - 같은가수` }).last().waitFor({ timeout: 5000 });
|
|
await a.getByRole('button', { name: '⏹ 끝내기' }).click();
|
|
await a.getByRole('button', { name: '끝내기', exact: true }).click();
|
|
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
|
|
});
|
|
|
|
await step('A: 노래 나오는 중 새로고침 → 소리 켜기 누르면 다른 사람과 같은 위치에서 이어 재생, 다른 사람은 안 멈춤, 바로 정답 가능', async () => {
|
|
await a.getByRole('button', { name: '↺ 다시 하기' }).click();
|
|
await a.locator('.pool-banner').waitFor();
|
|
await a.getByRole('radiogroup', { name: '모드' }).getByRole('radio', { name: /듣고맞추기/ }).click();
|
|
await a.getByRole('radiogroup', { name: '듣고맞출시간' }).getByRole('radio', { name: '끝까지' }).click();
|
|
await a.getByRole('radiogroup', { name: '듣고맞출시간' }).getByRole('radio', { name: '끝까지', checked: true }).waitFor();
|
|
await a.getByRole('button', { name: '게임 시작' }).click();
|
|
const fewer = a.getByRole('button', { name: '그대로 시작' });
|
|
if (await fewer.isVisible({ timeout: 1000 }).catch(() => false)) await fewer.click();
|
|
await Promise.all(all.map((p) => playing(p, 1)));
|
|
await a.waitForTimeout(1500);
|
|
const pauses = await a.evaluate(() => document.querySelectorAll('.chat-sys').length);
|
|
await c.reload();
|
|
await c.locator('.gbar .q', { hasText: /^문제 1 / }).waitFor({ timeout: 10000 });
|
|
// a fresh page may not play sound before a click: it waits muted for "참가 (소리 켜기)", the others keep playing
|
|
await c.getByRole('button', { name: '🔊 참가 (소리 켜기)' }).click({ timeout: 10000 });
|
|
await c.locator('.stage .lp.spin').waitFor({ timeout: 5000 });
|
|
await c.waitForTimeout(1200); // past one drift check
|
|
const [pa, pc, vidA, vidC] = await Promise.all([
|
|
a.evaluate(() => (window as any).mqPlayer.pos() as number),
|
|
c.evaluate(() => (window as any).mqPlayer.pos() as number),
|
|
video(a),
|
|
video(c),
|
|
]);
|
|
console.log(` 새로고침 뒤 위치 방장 ${pa.toFixed(3)} / 영희 ${pc.toFixed(3)}`);
|
|
expect(vidA === vidC, `다른 곡: ${vidA} / ${vidC}`);
|
|
expect(pa > 2.5 && Math.abs(pa - pc) < 0.4, `재생 위치가 다름: 방장 ${pa.toFixed(2)}s, 영희 ${pc.toFixed(2)}s`);
|
|
expect((await a.locator('.stage .lp.spin').count()) > 0, '방장 쪽 음악이 멈춤');
|
|
expect(!(await a.getByText(/잠시 멈춤/).count()), '다른 사람 화면이 잠시 멈춤');
|
|
expect((await a.evaluate(() => document.querySelectorAll('.chat-sys').length)) === pauses, '새로고침했는데 시스템 줄이 생김');
|
|
await answer(1, c);
|
|
await a.locator('.sb', { hasText: '영희' }).locator('.sc', { hasText: '1' }).waitFor();
|
|
await a.getByRole('button', { name: '⏹ 끝내기' }).click();
|
|
await a.getByRole('button', { name: '끝내기', exact: true }).click();
|
|
await a.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
|
|
});
|
|
|
|
await step('A: 모두 "← 방 목록"으로 나가면 방이 바로 사라짐', async () => {
|
|
for (const p of all) {
|
|
await p.getByRole('link', { name: '← 방 목록' }).click();
|
|
await p.waitForURL(ORIGIN + '/');
|
|
}
|
|
await a.waitForTimeout(300);
|
|
const r = await a.evaluate(async (cd) => (await fetch(`/api/rooms/${cd}`)).status, code);
|
|
const left = [...(app.rooms.get(code)?.players ?? new Map()).entries()].map(([id, pl]) => `${app.users.get(id)?.nickname}:${pl.conns.size}`);
|
|
expect(r === 404, `방이 남아 있음 (${r}) ${left.join(',')}`);
|
|
});
|
|
|
|
if (!process.env.E2E_NO_YT) {
|
|
await step('B: 실제 유튜브 — 소리 켜기 클릭 후 2명이 같은 순간 재생(소리 켜짐), 3초 클립은 재생 위치로 멈춤, 정답 공개', async () => {
|
|
const x = await guestPage('유튜브방장', { fake: false });
|
|
const y = await guestPage('유튜브손님', { fake: false });
|
|
const rc = await makeRoom(x, { count: 10, level: 9, listenSec: 3, startAt: 'highlight' }).catch(async (e) => {
|
|
console.log(' B room page:', (await x.locator('main').innerText().catch(() => '?')).slice(0, 300), x.url());
|
|
throw e;
|
|
});
|
|
await y.goto(`${ORIGIN}/r/${rc}`);
|
|
await y.locator('.pool-banner').waitFor();
|
|
for (const p of [x, y]) await p.getByRole('button', { name: '참가 (소리 켜기)' }).click();
|
|
await x.getByText('조건에 맞는 곡 3곡').waitFor({ timeout: 5000 }).catch(async (e) => {
|
|
console.log(' B pool:', await x.locator('.pool-banner').innerText());
|
|
throw e;
|
|
});
|
|
await x.getByRole('button', { name: '게임 시작' }).click();
|
|
await x.getByRole('button', { name: '그대로 시작' }).click();
|
|
await Promise.all([x, y].map((p) => playing(p, 1, 40000))).catch(async (e) => {
|
|
await x.screenshot({ path: join(SHOTS, 'stage5-youtube-fail-x.png') });
|
|
console.log(' debug', JSON.stringify(await Promise.all([x, y].map((p) => p.evaluate(() => ({ st: (window as any).mqPlayer?.state(), v: (window as any).mqPlayer?.video(), stage: document.querySelector('.stage')?.textContent }))))));
|
|
throw e;
|
|
});
|
|
await x.waitForTimeout(1200);
|
|
const st = await Promise.all([x, y].map((p) => p.evaluate(() => ({ pos: (window as any).mqPlayer.pos(), muted: (window as any).mqPlayer.muted(), state: (window as any).mqPlayer.state() }))));
|
|
expect(st.every((s) => s.state === 1 && !s.muted), `재생 상태 ${JSON.stringify(st)}`);
|
|
expect(Math.abs(st[0]!.pos - st[1]!.pos) < 0.3, `두 사람 위치 차이 ${JSON.stringify(st)}`);
|
|
console.log(` 위치 ${st.map((s) => s.pos.toFixed(3)).join(' / ')}`);
|
|
// 3s clip: stops by position
|
|
await x.locator('.stage .mode', { hasText: '재생이 끝났어요' }).waitFor({ timeout: 8000 });
|
|
const end = await Promise.all([x, y].map((p) => p.evaluate(() => ({ pos: (window as any).mqPlayer.pos(), state: (window as any).mqPlayer.state() }))));
|
|
console.log(` 멈춘 위치 ${end.map((s) => s.pos.toFixed(3)).join(' / ')}`);
|
|
expect(end.every((s) => s.state === 2), `클립 뒤 정지 안 됨 ${JSON.stringify(end)}`);
|
|
const s = titleOf((await video(x))!);
|
|
await say(y, s.title.replace(/\s*\(.*\)/, ''));
|
|
await x.locator('.reveal .big', { hasText: s.artist }).waitFor({ timeout: 5000 });
|
|
await x.screenshot({ path: join(SHOTS, 'stage5-youtube-reveal.png') });
|
|
await x.getByRole('button', { name: '⏹ 끝내기' }).click();
|
|
await x.getByRole('button', { name: '끝내기', exact: true }).click();
|
|
await x.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
|
|
await x.context().close();
|
|
await y.context().close();
|
|
});
|
|
|
|
await step('B: 실제 유튜브 — 노래 나오는 중 새로고침 → 소리 켜기 → 다른 사람과 같은 위치에서 소리 나게 이어 재생', async () => {
|
|
const x = await guestPage('유튜브방장2', { fake: false });
|
|
const y = await guestPage('유튜브손님2', { fake: false });
|
|
const rc = await makeRoom(x, { count: 10, level: 9, listenSec: 0, startAt: 'highlight' });
|
|
await y.goto(`${ORIGIN}/r/${rc}`);
|
|
await y.locator('.pool-banner').waitFor();
|
|
for (const p of [x, y]) await p.getByRole('button', { name: '참가 (소리 켜기)' }).click();
|
|
await x.getByText('조건에 맞는 곡 3곡').waitFor({ timeout: 5000 });
|
|
await x.getByRole('button', { name: '게임 시작' }).click();
|
|
await x.getByRole('button', { name: '그대로 시작' }).click();
|
|
await Promise.all([x, y].map((p) => playing(p, 1, 40000)));
|
|
await x.waitForTimeout(3000);
|
|
await y.reload();
|
|
await y.getByRole('button', { name: '🔊 참가 (소리 켜기)' }).click({ timeout: 30000 });
|
|
await y.locator('.stage .lp.spin').waitFor({ timeout: 15000 });
|
|
await y.waitForTimeout(2500);
|
|
const st = await Promise.all([x, y].map((p) => p.evaluate(() => ({ pos: (window as any).mqPlayer.pos(), muted: (window as any).mqPlayer.muted(), state: (window as any).mqPlayer.state(), v: (window as any).mqPlayer.video() }))));
|
|
console.log(` 새로고침 뒤 위치 ${st.map((s) => s.pos.toFixed(3)).join(' / ')}`);
|
|
expect(st[0]!.v === st[1]!.v, `다른 곡 ${JSON.stringify(st)}`);
|
|
expect(st.every((s) => s.state === 1 && !s.muted), `재생 상태 ${JSON.stringify(st)}`);
|
|
expect(Math.abs(st[0]!.pos - st[1]!.pos) < 0.4, `두 사람 위치 차이 ${JSON.stringify(st)}`);
|
|
expect(!(await x.getByText(/잠시 멈춤/).count()), '방장 화면이 멈춤');
|
|
await x.getByRole('button', { name: '⏹ 끝내기' }).click();
|
|
await x.getByRole('button', { name: '끝내기', exact: true }).click();
|
|
await x.getByRole('heading', { name: '🏁 게임 결과' }).waitFor();
|
|
await x.context().close();
|
|
await y.context().close();
|
|
});
|
|
}
|
|
|
|
expect(errors.length === 0, `페이지 오류: ${errors.join(' | ')}`);
|
|
} catch (e) {
|
|
console.log(e instanceof Error ? e.message.slice(0, 500) : e);
|
|
failed = true;
|
|
} finally {
|
|
await browser.close();
|
|
await app.stop();
|
|
}
|
|
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
|
|
process.exit(failed ? 1 : 0);
|