218 lines
13 KiB
TypeScript
218 lines
13 KiB
TypeScript
/**
|
|
* Stage 1 E2E (docs/10 1단계): guest start, Discord login (real /start → consent URL checked → mocked callback),
|
|
* both superadmins reach /admin, a plain member is refused, admin edits site settings and adds an admin.
|
|
* Run: bun run e2e (builds apps/web/dist, needs /usr/bin/google-chrome)
|
|
*/
|
|
import { chromium, 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 ?? 4618);
|
|
const ORIGIN = `http://localhost:${PORT}`;
|
|
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
|
|
mkdirSync(SHOTS, { recursive: true });
|
|
/** Made-up IDs; the real superadmin IDs live only in deploy/.env. */
|
|
const SUPERS = ['900000000000000001', '900000000000000002'];
|
|
const PLAIN = '900000000000000555';
|
|
const CLIENT_ID = '1561284577564037140';
|
|
|
|
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: SUPERS.join(','),
|
|
DISCORD_CLIENT_ID: CLIENT_ID,
|
|
DISCORD_CLIENT_SECRET: 'e2e',
|
|
});
|
|
const app = startServer({
|
|
config,
|
|
log: () => {},
|
|
staticDir: join(import.meta.dir, '../apps/web/dist'),
|
|
checkEmbed: async (id) => ({ state: 'ok', author: 'SG Wannabe - Topic', title: id }),
|
|
discordExchange: async (code) => ({ id: code, username: `u${code.slice(-3)}`, global_name: code === SUPERS[0] ? '사금향' : `친구${code.slice(-3)}`, avatar: null }),
|
|
});
|
|
|
|
{
|
|
const c = new Catalog(app.db);
|
|
const [id] = c.upsert({ melonId: 1, title: '광 (狂)', artists: [{ name: 'SG워너비' }], year: 2005, durationSec: 237, genres: ['ballad', 'kpop'], source: 'norabose', ref: '1' });
|
|
app.db.query("INSERT INTO youtube_candidates (song_id, video_id, title, channel, duration_sec, score, source) VALUES (?, 'VO88htcm09E', '광 (狂)', 'SG Wannabe', 237, 75, 'ytmusic')").run(id);
|
|
c.upsert({ melonId: 2, title: 'Love wins all', artists: [{ name: '아이유' }], year: 2024, genres: ['ballad', 'kpop'], source: 'norabose', ref: '2' });
|
|
}
|
|
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
|
|
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);
|
|
};
|
|
|
|
/** Fake Discord: let our real /start run (state cookie + consent URL), check the URL, bounce to our callback. */
|
|
async function fakeDiscord(ctx: BrowserContext, discordId: string, seen: { consent?: URL }) {
|
|
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')!);
|
|
seen.consent = consent;
|
|
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 {
|
|
await step('첫 화면: 로고·소개·디스코드 로그인·게스트 시작, 검색엔진 차단', async () => {
|
|
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR', colorScheme: 'light' });
|
|
const p = await ctx.newPage();
|
|
const errors: string[] = [];
|
|
p.on('pageerror', (e) => errors.push(e.message));
|
|
await p.goto(ORIGIN + '/');
|
|
await p.getByRole('heading', { name: /누가 먼저 맞히나/ }).waitFor();
|
|
expect(await p.locator('.site-logo img').evaluate((img: HTMLImageElement) => img.complete && img.naturalWidth > 0), '로고 이미지가 안 보여요');
|
|
expect(await p.getByRole('link', { name: '디스코드로 로그인' }).isVisible(), '디스코드 버튼 없음');
|
|
expect(await p.getByRole('button', { name: '게스트로 시작' }).isVisible(), '게스트 버튼 없음');
|
|
expect((await p.locator('meta[name=robots]').getAttribute('content'))?.includes('noindex'), 'noindex 없음');
|
|
expect((await (await fetch(ORIGIN + '/robots.txt')).text()).includes('Disallow: /'), 'robots.txt');
|
|
expect((await fetch(ORIGIN + '/favicon.ico')).ok, 'favicon');
|
|
await p.screenshot({ path: join(SHOTS, 'stage1-home.png') });
|
|
await ctx.close();
|
|
expect(errors.length === 0, errors.join(', '));
|
|
});
|
|
|
|
await step('게스트로 시작 → 헤더에 닉네임·게스트, 관리자 페이지는 디스코드 로그인 안내', async () => {
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'ko-KR' });
|
|
const p = await ctx.newPage();
|
|
await p.goto(ORIGIN + '/');
|
|
await p.getByLabel('게스트 닉네임 (2~12자)').fill('흥 많은 기타');
|
|
await p.getByRole('button', { name: '게스트로 시작' }).click();
|
|
await p.getByRole('button', { name: '내 계정: 흥 많은 기타' }).waitFor();
|
|
expect(await p.getByText('게스트', { exact: true }).first().isVisible(), '게스트 표시');
|
|
await p.goto(ORIGIN + '/admin');
|
|
await p.getByText('관리자는 디스코드로 로그인해야').waitFor();
|
|
// 로그아웃하면 게스트 계정은 지워짐
|
|
await p.goto(ORIGIN + '/');
|
|
await p.getByRole('button', { name: '내 계정: 흥 많은 기타' }).click();
|
|
await p.getByRole('menuitem', { name: /로그아웃/ }).click();
|
|
await p.getByRole('dialog').getByRole('button', { name: '로그아웃' }).click();
|
|
await p.getByRole('button', { name: '게스트로 시작' }).waitFor();
|
|
await ctx.close();
|
|
});
|
|
|
|
for (const [i, id] of SUPERS.entries()) {
|
|
await step(`슈퍼어드민 ${i + 1}: 디스코드 로그인(음악퀴즈 앱 동의 화면 주소 확인) → 관리자 페이지`, async () => {
|
|
const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
|
|
const seen: { consent?: URL } = {};
|
|
await fakeDiscord(ctx, id, seen);
|
|
const p = await ctx.newPage();
|
|
await p.goto(ORIGIN + '/');
|
|
await p.getByRole('link', { name: '디스코드로 로그인' }).click();
|
|
await p.getByRole('button', { name: /내 계정:/ }).waitFor();
|
|
const c = seen.consent!;
|
|
expect(c.origin + c.pathname === 'https://discord.com/oauth2/authorize', `consent ${c}`);
|
|
expect(c.searchParams.get('client_id') === CLIENT_ID, 'client_id');
|
|
expect(c.searchParams.get('scope') === 'identify', 'scope');
|
|
expect(c.searchParams.get('redirect_uri') === `${ORIGIN}/api/auth/discord/callback`, 'redirect_uri');
|
|
await p.getByRole('link', { name: '관리자' }).click();
|
|
await p.getByRole('heading', { name: '대시보드' }).waitFor();
|
|
await p.getByText('슈퍼어드민', { exact: true }).first().waitFor();
|
|
if (i === 0) {
|
|
const side = p.getByRole('navigation', { name: '관리자 메뉴' });
|
|
// 사이트 설정: 도배 방지 기본 꺼짐 → 켜고 저장
|
|
await side.getByRole('link', { name: /사이트/ }).click();
|
|
const guard = p.getByLabel('도배 방지 켜기 (기본: 꺼짐)');
|
|
expect(!(await guard.isChecked()), '도배 방지 기본값이 꺼짐이 아님');
|
|
await guard.check();
|
|
await p.getByLabel('공지 (첫 화면 위에 보여요)').fill('1단계 시험 중');
|
|
await p.getByRole('button', { name: '저장' }).click();
|
|
await p.getByText('저장했어요.').waitFor();
|
|
expect(app.settings.getSite().chatFloodGuard === true, '저장 안 됨');
|
|
await p.getByRole('note').getByText('1단계 시험 중').waitFor();
|
|
// 관리자 추가 (아직 로그인 안 한 사람)
|
|
await side.getByRole('link', { name: /관리자$/ }).click();
|
|
await p.getByPlaceholder('디스코드 ID (숫자 17~20자리)').fill('900000000000000777');
|
|
await p.getByRole('button', { name: '추가' }).click();
|
|
await p.getByText('관리자를 추가했어요.').waitFor();
|
|
await p.getByText('아직 로그인 안 함').first().waitFor();
|
|
await side.getByRole('link', { name: /사용자/ }).click();
|
|
await p.getByRole('cell', { name: '사금향' }).waitFor();
|
|
await side.getByRole('link', { name: /기록/ }).click();
|
|
await p.getByRole('cell', { name: 'admin.add' }).waitFor();
|
|
// 노래: 검색 → 편집 패널 → 후보 고르기 → 저장하면 확정
|
|
await side.getByRole('link', { name: /노래/ }).click();
|
|
await p.getByRole('heading', { name: '노래', exact: true }).waitFor();
|
|
await p.getByLabel('노래 검색').fill('SG');
|
|
await p.getByRole('button', { name: '검색' }).click();
|
|
await p.getByRole('button', { name: '광 (狂)' }).click();
|
|
await p.getByRole('heading', { name: '노래 편집' }).waitFor();
|
|
await p.locator('.cand').first().click();
|
|
await p.getByLabel('하이라이트 시작(초)').fill('75.8');
|
|
await p.getByRole('button', { name: '저장' }).click();
|
|
await p.getByText('저장했어요.').first().waitFor();
|
|
await p.locator('.data-table').getByText('확정').waitFor();
|
|
expect(app.db.query<{ youtube_id: string }, []>("SELECT youtube_id FROM songs WHERE melon_id = 1").get()!.youtube_id === 'VO88htcm09E', '유튜브 저장 안 됨');
|
|
// 회귀(리뷰 2026-10-18): 영상 없는 곡에 메모만 저장해도 자동 검색 대상에서 빠지지 않는다
|
|
await p.getByLabel('노래 검색').fill('Love wins');
|
|
await p.getByRole('button', { name: '검색' }).click();
|
|
await p.getByRole('button', { name: 'Love wins all' }).click();
|
|
await p.getByLabel('메모').fill('메모만 저장');
|
|
const patchReq = p.waitForRequest((r) => r.method() === 'PATCH' && r.url().includes('/api/admin/songs/'));
|
|
await p.getByRole('button', { name: '저장' }).click();
|
|
const sent = JSON.parse((await patchReq).postData() ?? '{}');
|
|
expect(!('youtube' in sent), `바꾸지 않은 유튜브 주소를 보냄: ${JSON.stringify(sent)}`);
|
|
await p.getByText('저장했어요.').first().waitFor();
|
|
const lw = app.db.query<{ note: string; youtube_source: string | null }, []>('SELECT note, youtube_source FROM songs WHERE melon_id = 2').get()!;
|
|
expect(lw.note === '메모만 저장' && lw.youtube_source === null, `메모 저장 후 youtube_source=${lw.youtube_source}`);
|
|
await side.getByRole('link', { name: /대시보드/ }).click();
|
|
await p.getByRole('heading', { name: '대시보드' }).waitFor();
|
|
await p.screenshot({ path: join(SHOTS, 'stage1-admin.png') });
|
|
}
|
|
await ctx.close();
|
|
});
|
|
}
|
|
|
|
await step('일반 디스코드 회원: 관리자 메뉴 없음, /admin 은 권한 없음', async () => {
|
|
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, locale: 'ko-KR', colorScheme: 'dark' });
|
|
await fakeDiscord(ctx, PLAIN, {});
|
|
const p = await ctx.newPage();
|
|
await p.goto(ORIGIN + '/login');
|
|
await p.getByRole('link', { name: '디스코드로 로그인' }).click();
|
|
await p.getByRole('button', { name: /내 계정: 친구555/ }).waitFor();
|
|
expect((await p.getByRole('link', { name: '관리자' }).count()) === 0, '관리자 메뉴가 보임');
|
|
await p.screenshot({ path: join(SHOTS, 'stage1-home-dark-member.png') });
|
|
await p.goto(ORIGIN + '/admin');
|
|
await p.getByRole('heading', { name: '권한이 없어요' }).waitFor();
|
|
expect((await p.evaluate(() => fetch('/api/admin/me').then((r) => r.status))) === 403, 'API 403 아님');
|
|
await ctx.close();
|
|
});
|
|
|
|
await step('휴대폰 화면(390px): 첫 화면이 가로로 넘치지 않음', async () => {
|
|
const ctx = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'ko-KR', isMobile: true, hasTouch: true });
|
|
const p = await ctx.newPage();
|
|
await p.goto(ORIGIN + '/');
|
|
await p.getByRole('button', { name: '게스트로 시작' }).waitFor();
|
|
const overflow = await p.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
|
|
expect(overflow <= 0, `가로 넘침 ${overflow}px`);
|
|
await p.screenshot({ path: join(SHOTS, 'stage1-mobile.png'), fullPage: true });
|
|
await ctx.close();
|
|
});
|
|
} catch {
|
|
failed = true;
|
|
} finally {
|
|
await browser.close();
|
|
await app.stop();
|
|
}
|
|
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
|
|
process.exit(failed ? 1 : 0);
|