Files
music_quiz/e2e/quiz.e2e.ts

127 lines
6.9 KiB
TypeScript

/**
* 관리자 → 퀴즈 editor in a real browser:
* - a DB song added from the search shows (and, with 자동 off, keeps) the DB highlight, not the 30% guess
* - an edit made while 저장 is on its way stays and stays unsaved
* Run: bun run build && bun e2e/quiz.e2e.ts (needs /usr/bin/google-chrome)
*/
import { chromium, type Browser, type BrowserContext } 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 ?? 4627);
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 }),
checkEmbed: async () => ({ state: 'ok', author: 'IU - Topic', title: 'Official Audio' }),
quizAdmin: { searchYoutube: async () => [], lavalink: null },
});
const db = app.db;
{
const [id] = new Catalog(db).upsert({ title: '좋은 날', artists: [{ name: '아이유' }], year: 2010, durationSec: 236, genres: ['kpop'], source: 'e2e', ref: '1' });
db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'jeqdYqsrsA0', highlight_sec = 95 WHERE id = ?").run(id!);
}
const browser: Browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
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>` });
});
}
let failed = false;
try {
const ctx = await browser.newContext({ viewport: { width: 1500, height: 950 }, locale: 'ko-KR' });
await fakeDiscord(ctx, SUPER);
const p = await ctx.newPage();
p.on('pageerror', (e) => errors.push(e.message));
await p.goto(`${ORIGIN}/api/auth/discord/start`);
await p.waitForURL(`${ORIGIN}/**`);
await step('퀴즈 추가 → 서버 DB 곡 추가 → 패널의 하이라이트는 DB 값(1:35), 자동 끄고 저장해도 95초', async () => {
await p.goto(`${ORIGIN}/admin/quizzes`);
await p.getByRole('button', { name: '퀴즈 추가' }).click();
await p.getByPlaceholder('예) 2000년대').fill('e2e 퀴즈');
await p.getByRole('button', { name: '확인' }).click();
await p.getByRole('button', { name: '✋ 직접 하나씩 추가' }).click();
await p.getByLabel('곡 추가 검색').fill('좋은 날');
await p.getByRole('button', { name: '찾기', exact: true }).click();
await p.locator('.cand', { hasText: '좋은 날' }).getByRole('button', { name: '추가' }).click();
await p.locator('.quiz-songs tbody tr').first().click();
const hl = p.locator('.pos-row', { hasText: '하이라이트' }).locator('.mono');
await p.waitForFunction(() => document.querySelector('.pos-editor .toggle:not([disabled])'));
expect((await hl.innerText()) === '1:35.0', `하이라이트가 DB 값이 아님: ${await hl.innerText()}`);
await p.locator('.pos-editor .toggle').click();
expect((await hl.innerText()) === '1:35.0', `자동을 끈 뒤 하이라이트: ${await hl.innerText()}`);
await p.keyboard.press('Control+s');
await p.getByText('저장됨').waitFor();
const it = db.query<{ auto: number; highlight_sec: number }, []>('SELECT auto, highlight_sec FROM custom_quiz_items').get()!;
expect(it.auto === 0 && it.highlight_sec === 95, `저장된 값: ${JSON.stringify(it)}`);
});
await step('저장 중에 바꾼 이름이 응답 뒤에도 남고 "저장 안 됨"으로 보임', async () => {
await p.getByRole('tab', { name: '설정' }).click();
const name = p.getByLabel('퀴즈 이름');
await name.fill('이름 1');
// hold the save request so an edit can happen while it is on its way
let release!: () => void;
const held = new Promise<void>((r) => (release = r));
await p.route(`${ORIGIN}/api/admin/quizzes/*`, async (route) => {
if (route.request().method() === 'PUT') await held;
await route.continue();
});
await p.keyboard.press('Control+s');
await p.getByText('저장 중…').waitFor();
await name.fill('이름 2');
release();
await p.locator('.toast', { hasText: '저장했어요' }).first().waitFor();
await p.waitForTimeout(200);
expect((await name.inputValue()) === '이름 2', `입력이 사라짐: ${await name.inputValue()}`);
expect(await p.getByText('저장하지 않은 변경이 있어요').isVisible(), '저장 안 됨 표시가 없음');
expect((await p.title()).startsWith('● 저장 안 됨'), `탭 제목: ${await p.title()}`);
expect(db.query<{ name: string }, []>('SELECT name FROM custom_quizzes').get()!.name === '이름 1', '서버에는 보낸 값(이름 1)');
await p.unroute(`${ORIGIN}/api/admin/quizzes/*`);
await p.keyboard.press('Control+s');
await p.getByText('저장됨').waitFor();
expect(db.query<{ name: string }, []>('SELECT name FROM custom_quizzes').get()!.name === '이름 2', '두 번째 저장');
});
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, `quiz-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);