276 lines
15 KiB
TypeScript
276 lines
15 KiB
TypeScript
/**
|
||
* Stage 8 E2E (docs/10 관리자 완성): a superadmin in a real browser.
|
||
* 노래 추가·일괄 작업·휴지통·초성 검색·내보내기/가져오기·중복 정리, 가수 별칭, 장르, 통계 승인, 방 강제 종료, 수집 실행/멈추기,
|
||
* 새 방 기본 설정·잠금.
|
||
* Run: bun run build && bun e2e/admin.e2e.ts (needs /usr/bin/google-chrome)
|
||
*/
|
||
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright-core';
|
||
import { mkdirSync, mkdtempSync, writeFileSync } 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 ?? 4623);
|
||
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 runs: { kind: string; limit?: number }[] = [];
|
||
const stops: number[] = [];
|
||
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: 'Someone - Topic', title: 'Official Audio' }),
|
||
collect: {
|
||
kinds: [{ id: 'match-youtube', label: '유튜브 원곡 찾기', limit: true }],
|
||
run: (kind, limit) => {
|
||
runs.push({ kind, limit });
|
||
app.db.query("INSERT INTO collect_jobs (kind, status, total, started_at, log, pid) VALUES (?, 'running', ?, ?, 'started from e2e', 1)").run(kind, limit ?? 0, Date.now());
|
||
return null;
|
||
},
|
||
stop: (id) => {
|
||
stops.push(id);
|
||
app.db.query("UPDATE collect_jobs SET status = 'stopped', finished_at = ? WHERE id = ?").run(Date.now(), id);
|
||
return null;
|
||
},
|
||
},
|
||
});
|
||
const db = app.db;
|
||
{
|
||
const c = new Catalog(db);
|
||
for (const [t, a, lv] of [
|
||
['사건의 지평선', '윤하', 3],
|
||
['좋은 날', '아이유', 3],
|
||
['밤양갱', '비비', 3],
|
||
['쉬운노래', '쉬운가수', 5],
|
||
] as const) {
|
||
const [id] = c.upsert({ title: t, artists: [{ name: a }], year: 2020, genres: ['kpop'], source: 'e2e', ref: t });
|
||
c.autoLevel(id!, 'all', lv);
|
||
db.query("UPDATE songs SET youtube_status = 'matched', embeddable = 1, youtube_id = 'VO88htcm09E', duration_sec = 200 WHERE id = ?").run(id!);
|
||
}
|
||
// a duplicate row of 밤양갱 that an import missed
|
||
db.query("INSERT INTO songs (title, artist, match_key, created_at, updated_at) SELECT '밤양갱 (Bam Yang Gang)', '비비', match_key, 0, 0 FROM songs WHERE title = '밤양갱'").run();
|
||
// plays: 쉬운노래 is always guessed fast → suggestion ★5 → ★4
|
||
const easy = db.query<{ id: number }, []>("SELECT id FROM songs WHERE title = '쉬운노래'").get()!.id;
|
||
for (let i = 0; i < 6; i++) db.query("INSERT INTO song_plays (song_id, game_id, played_at, players, winner_id, ms, how) VALUES (?, 'g', ?, 3, 'u', 2500, 'correct')").run(easy, Date.now());
|
||
}
|
||
|
||
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>` });
|
||
});
|
||
}
|
||
|
||
const toastSeen = (p: Page, text: string | RegExp) => p.locator('.toast', { hasText: text }).first().waitFor({ timeout: 5000 });
|
||
const row = (p: Page, title: string) => p.locator('.data-table tbody tr', { hasText: title });
|
||
|
||
let failed = false;
|
||
try {
|
||
const ctx = await browser.newContext({ viewport: { width: 1500, height: 950 }, locale: 'ko-KR', acceptDownloads: true });
|
||
await fakeDiscord(ctx, SUPER);
|
||
const p = await ctx.newPage();
|
||
p.on('pageerror', (e) => errors.push(e.message));
|
||
await p.goto(ORIGIN + '/');
|
||
await p.getByRole('link', { name: '디스코드로 로그인' }).click();
|
||
await p.getByRole('button', { name: '내 계정: 사금향' }).waitFor();
|
||
|
||
await step('노래: 추가(제목·가수·유튜브) → 편집 패널, 초성 검색, 미리듣기 + "지금 위치를 하이라이트로" 버튼', async () => {
|
||
await p.goto(ORIGIN + '/admin/songs');
|
||
await p.getByRole('button', { name: '+ 노래 추가' }).click();
|
||
const sheet = p.getByRole('dialog', { name: '노래 추가' });
|
||
await sheet.getByLabel('제목').fill('새로 넣은 노래');
|
||
await sheet.getByLabel('가수 (여러 명이면 쉼표로)').fill('관리자가수');
|
||
await sheet.getByLabel(/유튜브 주소/).fill('https://youtu.be/abcdefghijk');
|
||
await sheet.getByRole('button', { name: '추가', exact: true }).click();
|
||
await toastSeen(p, '추가했어요');
|
||
await p.getByRole('complementary', { name: '노래 편집' }).getByRole('button', { name: '⏱ 지금 위치를 하이라이트로' }).waitFor();
|
||
expect(db.query("SELECT youtube_status s FROM songs WHERE title = '새로 넣은 노래'").get() as { s: string }, '추가 안 됨');
|
||
await p.getByLabel('노래 검색').fill('ㅅㄱㅇㅈㅍㅅ');
|
||
await p.getByRole('button', { name: '검색' }).click();
|
||
await p.locator('form .muted.small', { hasText: /^1곡$/ }).waitFor();
|
||
await row(p, '사건의 지평선').waitFor();
|
||
});
|
||
|
||
await step('노래: 2곡 골라 일괄 숨기기 → 숨김 배지, 휴지통으로 → 휴지통에서 복원', async () => {
|
||
await p.getByLabel('노래 검색').fill('');
|
||
await p.getByRole('button', { name: '검색' }).click();
|
||
await row(p, '좋은 날').getByRole('checkbox').check();
|
||
await row(p, '밤양갱 (Bam').getByRole('checkbox').check();
|
||
await p.getByRole('region', { name: '선택한 곡 일괄 작업' }).getByText('2곡 선택').waitFor();
|
||
await p.getByRole('button', { name: '적용' }).click();
|
||
await toastSeen(p, '2곡에 적용했어요');
|
||
await row(p, '좋은 날').locator('.badge', { hasText: '숨김' }).waitFor();
|
||
await row(p, '좋은 날').getByRole('checkbox').check();
|
||
await p.getByLabel('일괄 작업', { exact: true }).selectOption('trash');
|
||
await p.getByRole('button', { name: '적용' }).click();
|
||
await p.getByRole('dialog').getByRole('button', { name: '적용' }).click();
|
||
await row(p, '좋은 날').waitFor({ state: 'detached' });
|
||
await p.getByRole('button', { name: '🗑 휴지통', exact: true }).click();
|
||
await p.getByRole('heading', { name: '휴지통' }).waitFor();
|
||
await row(p, '좋은 날').getByRole('button', { name: '복원' }).click();
|
||
await toastSeen(p, '복원했어요');
|
||
await p.getByRole('button', { name: '🗑 휴지통', exact: true }).click();
|
||
await row(p, '좋은 날').waitFor();
|
||
});
|
||
|
||
await step('노래: CSV 내보내기(현재 필터) → 가져오기(새 곡 추가·있는 곡 건너뜀)', async () => {
|
||
const href = await p.getByRole('link', { name: 'CSV 내보내기' }).getAttribute('href');
|
||
const csv = await (await p.request.get(ORIGIN + href)).text();
|
||
expect(csv.includes('title,artist') && csv.includes('사건의 지평선'), 'CSV 내용이 이상함');
|
||
const file = join(TMP, 'songs.csv');
|
||
writeFileSync(file, csv.replace(/^/, '') + ',가져온 노래,가져온가수,2011,ballad,4,,,0\n');
|
||
await p.getByLabel('가져올 파일').setInputFiles(file);
|
||
await toastSeen(p, /새 곡 1곡, 이미 있던 곡 \d+곡/);
|
||
await p.getByLabel('노래 검색').fill('가져온');
|
||
await p.getByRole('button', { name: '검색' }).click();
|
||
await row(p, '가져온 노래').waitFor();
|
||
});
|
||
|
||
await step('노래: 중복 정리 — 밤양갱 2곡을 하나로 합치기', async () => {
|
||
await p.getByRole('button', { name: '중복 정리' }).click();
|
||
const sheet = p.getByRole('dialog', { name: '중복 정리' });
|
||
await sheet.getByText('밤양갱 (Bam Yang Gang)').waitFor();
|
||
await sheet.getByRole('button', { name: /로 합치기$/ }).first().click();
|
||
await toastSeen(p, '합쳤어요');
|
||
await sheet.getByText('중복된 곡이 없어요.').waitFor();
|
||
await p.keyboard.press('Escape');
|
||
expect(db.query<{ n: number }, []>("SELECT COUNT(*) n FROM songs WHERE title LIKE '밤양갱%' AND deleted_at IS NULL").get()!.n === 1, '합쳐지지 않음');
|
||
});
|
||
|
||
await step('가수: 아이유에 별칭 IU·이지은 → 별칭으로도 검색됨', async () => {
|
||
await p.getByRole('link', { name: '🎤 가수' }).click();
|
||
await p.getByLabel('가수 검색').fill('아이유');
|
||
await p.getByRole('button', { name: '검색' }).click();
|
||
await p.getByRole('button', { name: '아이유 고치기' }).click();
|
||
await p.getByLabel('별칭').fill('IU, 이지은');
|
||
await p.getByRole('button', { name: '저장' }).click();
|
||
await toastSeen(p, '저장했어요');
|
||
await p.getByLabel('가수 검색').fill('이지은');
|
||
await p.getByRole('button', { name: '검색' }).click();
|
||
await row(p, 'IU, 이지은').waitFor();
|
||
});
|
||
|
||
await step('장르: 시티팝 추가 → 방 설정에 보임, 숨기면 사라짐', async () => {
|
||
await p.getByRole('link', { name: '🏷 장르' }).click();
|
||
await p.getByLabel('새 장르 ID').fill('citypop');
|
||
await p.getByLabel('새 장르 이름').fill('시티팝');
|
||
await p.getByRole('button', { name: '장르 추가' }).click();
|
||
await toastSeen(p, '추가했어요');
|
||
let meta = await (await p.request.get(ORIGIN + '/api/catalog/meta')).json();
|
||
expect(meta.genres.some((g: { name: string }) => g.name === '시티팝'), '방 설정에 새 장르가 없음');
|
||
await p.getByLabel('시티팝 숨김').click();
|
||
await p.getByLabel('시티팝 숨김').and(p.locator(':checked')).waitFor();
|
||
await p.waitForTimeout(300);
|
||
meta = await (await p.request.get(ORIGIN + '/api/catalog/meta')).json();
|
||
expect(!meta.genres.some((g: { name: string }) => g.name === '시티팝'), '숨긴 장르가 보임');
|
||
});
|
||
|
||
await step('통계: 쉬운노래(6번 모두 2.5초) → ★5 → ★4 제안 승인', async () => {
|
||
await p.getByRole('link', { name: '📈 통계' }).click();
|
||
await p.getByText('난이도 조정 제안').waitFor();
|
||
await p.getByRole('button', { name: '★5 → ★4 승인' }).click();
|
||
await toastSeen(p, '★4로 바꿨어요');
|
||
expect(db.query<{ level: number }, []>("SELECT level FROM song_levels l JOIN songs s ON s.id = l.song_id WHERE s.title = '쉬운노래' AND scope = 'all'").get()!.level === 4, '난이도가 안 바뀜');
|
||
});
|
||
|
||
await step('방: 손님의 비공개 방이 보이고, 강제 종료하면 손님은 첫 화면 + "관리자가 방을 닫았어요"', async () => {
|
||
const gctx = await browser.newContext({ locale: 'ko-KR' });
|
||
const g = await gctx.newPage();
|
||
g.on('pageerror', (e) => errors.push(`guest: ${e.message}`));
|
||
await g.goto(ORIGIN + '/');
|
||
await g.getByLabel('게스트 닉네임 (2~12자)').fill('손님');
|
||
await g.getByRole('button', { name: '게스트로 시작' }).click();
|
||
await g.getByRole('button', { name: '내 계정: 손님' }).waitFor();
|
||
const code = await g.evaluate(async () => (await (await fetch('/api/rooms', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ config: { visibility: 'private' } }) })).json()).code as string);
|
||
await g.goto(`${ORIGIN}/r/${code}`);
|
||
await g.locator('.pool-banner').waitFor();
|
||
await p.getByRole('link', { name: '🚪 방' }).click();
|
||
await row(p, code).waitFor();
|
||
await row(p, code).getByRole('button', { name: '강제 종료' }).click();
|
||
await p.getByRole('dialog').getByRole('button', { name: '강제 종료' }).click();
|
||
await g.locator('.toast', { hasText: '관리자가 방을 닫았어요.' }).waitFor({ timeout: 5000 });
|
||
await g.waitForURL(ORIGIN + '/');
|
||
await gctx.close();
|
||
});
|
||
|
||
await step('수집: 곡 수 넣고 실행 → 진행 중 + 멈추기 → 기록과 로그', async () => {
|
||
await p.getByRole('link', { name: '📥 수집' }).click();
|
||
await p.getByLabel('유튜브 원곡 찾기 곡 수').fill('120');
|
||
await p.getByRole('button', { name: '실행' }).click();
|
||
await toastSeen(p, '시작했어요');
|
||
expect(runs.at(-1)?.limit === 120, `실행 요청 ${JSON.stringify(runs)}`);
|
||
await p.getByRole('button', { name: '멈추기' }).click({ timeout: 8000 });
|
||
await row(p, '멈춤').waitFor();
|
||
await p.getByRole('button', { name: '실행' }).waitFor();
|
||
expect(stops.length === 1, '멈추기 요청 없음');
|
||
await p.getByRole('button', { name: '로그' }).first().click();
|
||
await p.getByText('started from e2e').waitFor();
|
||
});
|
||
|
||
await step('사이트: 새 방 기본 난이도 ★2 + 난이도 잠금 → 손님이 만든 방은 ★2, 방장도 못 바꿈', async () => {
|
||
await p.getByRole('link', { name: '⚙️ 사이트' }).click();
|
||
await p.getByRole('radio', { name: /^2단계/ }).click();
|
||
await p.getByLabel('🔒 난이도').check();
|
||
await p.getByRole('button', { name: '저장', exact: true }).click();
|
||
await toastSeen(p, '저장했어요');
|
||
await p.screenshot({ path: join(SHOTS, 'stage8-site.png'), fullPage: true });
|
||
const gctx = await browser.newContext({ locale: 'ko-KR' });
|
||
const g = await gctx.newPage();
|
||
await g.goto(ORIGIN + '/');
|
||
await g.getByLabel('게스트 닉네임 (2~12자)').fill('새방장');
|
||
await g.getByRole('button', { name: '게스트로 시작' }).click();
|
||
await g.getByRole('button', { name: '+ 방 만들기' }).click();
|
||
await g.waitForURL(/\/r\/\d{6}$/);
|
||
await g.locator('.pool-banner', { hasText: '★2' }).waitFor();
|
||
await g.getByRole('radio', { name: /^5단계/ }).click();
|
||
await g.locator('.toast', { hasText: '관리자가 고정한 설정' }).waitFor({ timeout: 5000 });
|
||
await gctx.close();
|
||
});
|
||
|
||
await p.goto(ORIGIN + '/admin/songs');
|
||
await p.locator('.data-table tbody tr').first().waitFor();
|
||
await p.screenshot({ path: join(SHOTS, 'stage8-songs.png'), fullPage: true });
|
||
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, `stage8-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);
|