/** * 관리자 → 퀴즈 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 * - 파일로 만들기 from an Excel-style (deflated) .xlsx, 엑셀로 내보내기 reads back, 파일에서 가져오기 a CP949 .csv * - 재생목록으로 엑셀 만들기 → the file goes back into 파일로 만들기 (빈 시작·하이라이트: 자동 / 처음부터) * 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'; import { readXlsx } from '../packages/shared/src/sheet'; import { deflatedZip } from '../packages/shared/src/zip-fixture'; 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: { url: 'http://lavalink.e2e', password: 'x' }, importDelayMs: 0, lavalinkFetch: (async () => Response.json({ loadType: 'playlist', data: { info: { name: '내 재생목록' }, tracks: [ { info: { identifier: 'jeqdYqsrsA0', title: '아이유 - 좋은 날 (Official MV)', author: 'LOEN', length: 236000, sourceName: 'youtube' } }, { info: { identifier: 'iIIjS6yDMQo', title: '밤편지 (Official MV)', author: '아이유 공식', length: 260000, sourceName: 'youtube' } }, { info: { identifier: 'jeqdYqsrsA0', title: '아이유 - 좋은 날', author: 'LOEN', length: 236000, sourceName: 'youtube' } }, ], }, })) as unknown as typeof fetch, }, }); 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) => { 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: `` }); }); } 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((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', '두 번째 저장'); }); await step('파일로 만들기: 엑셀(.xlsx) → 순번 순서·힌트, 빠지는 줄 표시 → 만들기; 내보내기가 같은 곡으로 읽힘; CSV(CP949) 뒤에 추가', async () => { const cell = (ref: string, v: string) => `${v}`; const head = ['번호', '유튜브 영상 링크', '게임 제목(한글)', '노래 제목', '힌트(게임장르)', '재생목록 순번']; const data = [ ['1', 'https://youtu.be/iIIjS6yDMQo', '감옥탈출(구토할배)', '트레일러', '방탈출(플래시)', '3'], ['2', 'https://youtu.be/x0-xFqvJ-U8', '갓 오브 워 2', 'The End Begins', '액션', '1'], ['3', 'https://example.com/x', '잘못된 링크', '', '', '4'], ['4', 'https://youtu.be/x0-xFqvJ-U8', '같은 영상', '', '', '5'], ['5', 'https://youtu.be/Yz-Af4p_Vv8', '건파이어 리본', 'Desert Theme', '확인필요', '2'], ]; const sheetXml = `${[head, ...data].map((r, i) => `${r.map((v, k) => cell(`${'ABCDEF'[k]}${i + 1}`, v)).join('')}`).join('')}`; const xlsx = deflatedZip({ 'xl/workbook.xml': '', 'xl/_rels/workbook.xml.rels': '', 'xl/worksheets/sheet1.xml': sheetXml, 'xl/worksheets/sheet2.xml': `${cell('A1', '메모')}`, }); await p.goto(`${ORIGIN}/admin/quizzes`); await p.getByRole('button', { name: /^파일로 만들기/ }).click(); await p.getByLabel('퀴즈 파일').setInputFiles({ name: '게임 BGM.xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', buffer: Buffer.from(xlsx) }); await p.getByText('빠지는 줄 2개').waitFor(); expect((await p.getByLabel('시트').inputValue()) === '0', '곡이 있는 시트를 먼저 고르지 않음'); expect((await p.getByLabel('퀴즈 이름').inputValue()) === '게임 BGM', '이름이 파일 이름이 아님'); await p.screenshot({ path: join(SHOTS, 'quiz-file-preview.png'), fullPage: true }); await p.getByRole('button', { name: '3곡으로 만들기' }).click(); await p.waitForURL(/\/admin\/quizzes\/\d+$/); await p.locator('.quiz-songs tbody tr').nth(2).waitFor(); const quizId = Number(new URL(p.url()).pathname.split('/').pop()); const rows = db .query<{ title: string; artist: string; hints: string; from_file: number; song_id: number | null }, [number]>('SELECT title, artist, hints, from_file, song_id FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos') .all(quizId); expect( JSON.stringify(rows) === JSON.stringify([ { title: '갓 오브 워 2', artist: 'The End Begins', hints: '["액션"]', from_file: 1, song_id: null }, { title: '건파이어 리본', artist: 'Desert Theme', hints: '["확인필요"]', from_file: 1, song_id: null }, { title: '감옥탈출', artist: '트레일러', hints: '["방탈출(플래시)"]', from_file: 1, song_id: null }, ]), `저장된 곡: ${JSON.stringify(rows)}`, ); expect(JSON.parse(db.query<{ s: string }, [number]>('SELECT settings_json s FROM custom_quizzes WHERE id = ?').get(quizId)!.s).hint === 'manual', '힌트가 투표로 켜지지 않음'); await p.screenshot({ path: join(SHOTS, 'quiz-file-editor.png'), fullPage: true }); // 엑셀로 내보내기 → the same songs come back const [dl] = await Promise.all([p.waitForEvent('download'), p.getByRole('button', { name: /엑셀로 내보내기/ }).click()]); expect(dl.suggestedFilename() === '게임 BGM.xlsx', `내보낸 파일 이름: ${dl.suggestedFilename()}`); const back = (await readXlsx(new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer())))[0]!.rows; // 제목 · 가수 · 정답 · 가수 정답 · 힌트 …: the bracket went from the title and is an answer now (docs/13) expect(back.length === 4 && back[1]![2] === '갓 오브 워 2' && back[1]![6] === '액션' && back[3]![1] === 'https://youtu.be/iIIjS6yDMQo' && back[3]![4] === '감옥탈출; 구토할배; 감옥탈출 구토할배', `내보낸 내용: ${JSON.stringify(back)}`); // 파일에서 가져오기: a Korean Excel CSV (CP949), one new song and one already in the list const csv = new Uint8Array([ ...new TextEncoder().encode('link,'), 0xc1, 0xa4, 0xb4, 0xe4, // 정답 ...new TextEncoder().encode('\nhttps://youtu.be/9hzKkTpXDwM,'), 0xb0, 0xd9, 0xbe, 0xda, 0xc7, 0xc1, 0xb5, 0xe5, // 겟앰프드 ...new TextEncoder().encode('\nhttps://youtu.be/iIIjS6yDMQo,x\n'), ]); await p.getByRole('button', { name: '📄 파일' }).click(); await p.getByLabel('퀴즈 파일').setInputFiles({ name: 'more.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) }); await p.getByText('이미 목록에 있는 영상 1곡').waitFor(); await p.getByRole('button', { name: '1곡 목록 뒤에 추가' }).click(); await p.locator('.quiz-songs tbody tr', { hasText: '겟앰프드' }).waitFor(); await p.keyboard.press('Control+s'); await p.getByText('저장됨').waitFor(); expect(db.query<{ n: number }, [number]>('SELECT COUNT(*) n FROM custom_quiz_items WHERE quiz_id = ?').get(quizId)!.n === 4, '가져온 곡 저장'); }); await step('정답 자동 채우기: 빈 정답 칸은 서버가 채움, 채우는 중에 이지선다로 바꿔도 만들기 버튼이 막히지 않음, 실패는 "채웠어요"로 안 보임', async () => { const csv = new TextEncoder().encode('링크,제목,가수,정답\nhttps://youtu.be/9hzKkTpXDwM,사랑을 했다(LOVE SCENARIO),아이콘,\nhttps://youtu.be/Yz-Af4p_Vv8,광(狂),SG워너비,\n'); const openFile = async () => { await p.goto(`${ORIGIN}/admin/quizzes`); await p.getByRole('button', { name: /^파일로 만들기/ }).click(); await p.getByLabel('퀴즈 파일').setInputFiles({ name: '빈 정답.csv', mimeType: 'text/csv', buffer: Buffer.from(csv) }); }; // 1. the request hangs: switching to 이지선다 must not leave the button waiting let release!: () => void; const hold = new Promise((r) => (release = r)); await p.route(`${ORIGIN}/api/admin/quizzes/answers`, async (route) => (await hold, route.continue().catch(() => {}))); await openFile(); await p.getByText('자동으로 채우는 중').waitFor(); expect(await p.getByRole('button', { name: '2곡으로 만들기' }).isDisabled(), '채우는 중에는 만들기를 기다림'); await p.getByRole('radio', { name: /이지선다/ }).click(); const duelBtn = p.getByRole('button', { name: '2곡으로 이지선다 만들기' }); await duelBtn.waitFor(); for (let i = 0; i < 20 && (await duelBtn.isDisabled()); i++) await p.waitForTimeout(100); expect(await duelBtn.isEnabled(), '이지선다로 바꾼 뒤 만들기 버튼이 막힘(요청이 끝나지 않은 채)'); release(); await p.unroute(`${ORIGIN}/api/admin/quizzes/answers`); // 2. back to 일반: filled from the server, shown under the title await p.getByRole('radio', { name: /일반 퀴즈/ }).click(); await p.getByText('(자동으로 채웠어요)').waitFor(); await p.getByText('또는 LOVE SCENARIO, 사랑을 했다 LOVE SCENARIO').waitFor(); // 3. the server fails: those songs say so, never "채웠어요" await p.route(`${ORIGIN}/api/admin/quizzes/answers`, (route) => route.fulfill({ status: 502, contentType: 'application/json', body: '{"error":"잠깐 끊김"}' })); await openFile(); await p.getByText('2곡은 자동으로 못 채워서 적힌 정답만 써요').waitFor(); expect((await p.getByText('(자동으로 채웠어요)').count()) === 0, '실패했는데 채웠다고 보임'); expect(await p.getByRole('button', { name: '2곡으로 만들기' }).isEnabled(), '실패 뒤 만들기 버튼이 막힘'); await p.unroute(`${ORIGIN}/api/admin/quizzes/answers`); }); await step('재생목록으로 엑셀 만들기 → 검토(DB 곡·확인 필요·같은 영상은 빠진 곡) → 받은 엑셀을 파일로 만들기: 자동은 DB 하이라이트, 처음부터는 0초', async () => { await p.goto(`${ORIGIN}/admin/quizzes`); await p.getByRole('button', { name: /재생목록으로 엑셀 만들기/ }).click(); await p.getByLabel('재생목록 주소').fill('https://www.youtube.com/playlist?list=PLe2e'); // the first poll fails (network blip): polling goes on and the file still comes let failedPolls = 0; await p.route(`${ORIGIN}/api/admin/quizzes/pick/playlist/*`, async (route) => { if (failedPolls++ === 0) return route.fulfill({ status: 502, contentType: 'application/json', body: '{"error":"잠깐 끊김"}' }); await route.continue(); }); await p.getByRole('button', { name: '검토 시작' }).click(); const get = p.getByRole('button', { name: /일반 퀴즈용 엑셀/ }); await get.waitFor(); expect(failedPolls >= 2, `다시 묻지 않음: ${failedPolls}`); await p.unroute(`${ORIGIN}/api/admin/quizzes/pick/playlist/*`); expect((await get.innerText()).includes('2곡'), `받기 버튼: ${await get.innerText()}`); await p.getByText('재생목록 1번 곡과 같은 영상').waitFor(); await p.screenshot({ path: join(SHOTS, 'quiz-playlist-sheet.png'), fullPage: true }); const [dl] = await Promise.all([p.waitForEvent('download'), get.click()]); expect(dl.suggestedFilename() === '내 재생목록.xlsx', `파일 이름: ${dl.suggestedFilename()}`); const bytes = new Uint8Array(await Bun.file((await dl.path())!).arrayBuffer()); const book = await readXlsx(bytes); expect(book.map((x) => x.name).join() === '퀴즈,빠진 곡', `시트: ${book.map((x) => x.name)}`); expect( JSON.stringify(book[0]!.rows) === JSON.stringify([ ['순번', '유튜브 영상 링크', '제목', '가수', '정답(;로 구분)', '가수 정답(;로 구분)', '힌트', '시작(초)', '하이라이트(초)', '길이(초)', '비고'], ['1', 'https://youtu.be/jeqdYqsrsA0', '좋은 날', '아이유', '좋은 날', '아이유', '', '', '', '236', 'DB 곡'], ['2', 'https://youtu.be/iIIjS6yDMQo', '밤편지', '아이유', '밤편지', '아이유', '', '', '', '260', '제목·가수 확인 필요 (영상 제목 형식이 달라 채널 이름을 가수로 씀)'], ]), `엑셀 내용: ${JSON.stringify(book[0]!.rows)}`, ); // the 이지선다 form: an empty 조회수 column instead of the answers const [dlDuel] = await Promise.all([p.waitForEvent('download'), p.getByRole('button', { name: /이지선다용 엑셀/ }).click()]); expect(dlDuel.suggestedFilename() === '내 재생목록 (이지선다).xlsx', `파일 이름: ${dlDuel.suggestedFilename()}`); const duelBook = await readXlsx(new Uint8Array(await Bun.file((await dlDuel.path())!).arrayBuffer())); expect( JSON.stringify(duelBook[0]!.rows.slice(0, 2)) === JSON.stringify([ ['순번', '유튜브 영상 링크', '제목', '가수', '조회수', '시작(초)', '하이라이트(초)', '길이(초)', '비고'], ['1', 'https://youtu.be/jeqdYqsrsA0', '좋은 날', '아이유', '', '', '', '236', 'DB 곡'], ]), `이지선다 엑셀: ${JSON.stringify(duelBook[0]!.rows)}`, ); const upload = async (blank: '자동' | '처음부터', name: string) => { await p.goto(`${ORIGIN}/admin/quizzes`); await p.getByRole('button', { name: /^파일로 만들기/ }).click(); await p.getByLabel('퀴즈 파일').setInputFiles({ name: '내 재생목록.xlsx', mimeType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', buffer: Buffer.from(bytes) }); await p.getByText('시작·하이라이트가 빈 곡 2곡').waitFor(); if (blank === '처음부터') { await p.getByRole('radio', { name: /처음부터 재생/ }).click(); await p.screenshot({ path: join(SHOTS, 'quiz-file-blank-positions.png'), fullPage: true }); } await p.getByLabel('퀴즈 이름').fill(name); await p.getByRole('button', { name: '2곡으로 만들기' }).click(); await p.waitForURL(/\/admin\/quizzes\/\d+$/); const id = Number(new URL(p.url()).pathname.split('/').pop()); return db.query<{ title: string; auto: number; start_sec: number | null; highlight_sec: number | null; duration_sec: number | null }, [number]>( 'SELECT title, auto, start_sec, highlight_sec, duration_sec FROM custom_quiz_items WHERE quiz_id = ? ORDER BY pos', ).all(id); }; const auto = await upload('자동', '재생목록 자동'); expect( JSON.stringify(auto) === JSON.stringify([ { title: '좋은 날', auto: 0, start_sec: 0, highlight_sec: 95, duration_sec: 236 }, { title: '밤편지', auto: 1, start_sec: null, highlight_sec: null, duration_sec: 260 }, ]), `자동: ${JSON.stringify(auto)}`, ); const fromStart = await upload('처음부터', '재생목록 처음부터'); expect( JSON.stringify(fromStart) === JSON.stringify([ { title: '좋은 날', auto: 0, start_sec: 0, highlight_sec: 0, duration_sec: 236 }, { title: '밤편지', auto: 0, start_sec: 0, highlight_sec: 0, duration_sec: 260 }, ]), `처음부터: ${JSON.stringify(fromStart)}`, ); }); 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);