퀴즈 편집 수정: 저장 중에 바꾼 내용이 응답으로 덮여 사라지고 '저장됨'으로 보이던 것(보낸 내용과 지금 내용이 다르면 지금 내용을 두고 새 곡 id만 붙임, 저장 안 됨 유지). 새로 추가한 서버 DB 곡의 하이라이트가 DB 값 대신 곡 길이 30%로 보이고 자동을 끄면 그 값으로 굳던 것(추가 즉시 /quizzes/pick/songs로 DB 정보를 받고, 받기 전엔 자동 스위치·표시 이동 잠금). e2e/quiz.e2e.ts로 두 경로 회귀 확인
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
126
e2e/quiz.e2e.ts
Normal file
126
e2e/quiz.e2e.ts
Normal file
@@ -0,0 +1,126 @@
|
||||
/**
|
||||
* 관리자 → 퀴즈 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);
|
||||
Reference in New Issue
Block a user