Files
joke-app/e2e/admin.e2e.ts
EJClaw 1bd69200fd 라이어 게임: 관리자 화면에서 주제·제시어 추가/수정/삭제, 바보 모드 라이어는 비슷한 단어(같은 묶음)
- 제시어 1,519개를 주제별 '비슷한 단어 묶음' 391개로 정리(bank/*.ts groups). 바보 모드 라이어는 제시어와 같은 묶음의 다른 단어를 받음
- 관리자 → 라이어 제시어(/admin/liar): 주제 추가·이름 변경·삭제(내장 주제는 다시 살리기/처음 값으로), 제시어·묶음·다른 표기·컴퓨터 설명 편집, 저장 시 topicProblems 검사
- 저장: liar_topics(바뀐 주제), liar_bank_versions(판본). 새 판 옵션에 bank 판본을 붙여(prepareOptions) 다시 보기·복구가 같은 은행 사용
- 판 상태에 주제 이름·단어 목록·다른 표기를 복사해 진행 중 판은 관리자 수정의 영향을 받지 않음
- 대기실 주제 목록은 GET /api/liar/topics, 관리자 API /api/admin/liar/topics, 기록 liar.topic.*
- 테스트: 엔진(묶음·바보 모드·판본·검사), 서버(관리자 API·새 판·재시작), E2E(관리자 편집 → 대기실 새 주제)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 04:16:17 +09:00

256 lines
15 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Admin E2E (docs/14-admin.md §9): superadmin logs in with (mocked) Discord, edits omok defaults
* with a lock, adds an admin; a guest's new room reflects the settings.
* Run: bun e2e/admin.e2e.ts (needs apps/web/dist built)
*/
import { chromium } 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';
const PORT = Number(process.env.E2E_PORT ?? 4518);
const ORIGIN = `http://localhost:${PORT}`;
const SHOTS = process.env.E2E_SHOTS ?? join(import.meta.dir, '../test-results');
mkdirSync(SHOTS, { recursive: true });
/** Made-up ID; the real superadmin IDs live only in deploy/.env. */
const SUPER = '900000000000000001';
const config = loadConfig({ PORT: String(PORT), DB_PATH: join(mkdtempSync(join(process.env.TMPDIR ?? '/tmp', 'bg-e2e-')), 'app.db'), PUBLIC_ORIGIN: ORIGIN, SUPERADMIN_DISCORD_IDS: SUPER });
config.discord = { clientId: 'e2e', clientSecret: 'e2e' };
const app = startServer({
config,
log: () => {},
staticDir: join(import.meta.dir, '../apps/web/dist'),
discordExchange: async (code) => ({ id: code, username: 'owner', global_name: '사금향', avatar: null }),
});
const browser = await chromium.launch({ executablePath: process.env.CHROME ?? '/usr/bin/google-chrome', headless: true });
let failed = false;
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;
}
};
try {
const adminCtx = await browser.newContext({ viewport: { width: 1440, height: 900 }, locale: 'ko-KR' });
// Fake Discord: Playwright does not route redirect targets, so intercept our own /start, let the server
// set its state cookie, and bounce straight back to the callback with the superadmin's ID as the code.
await adminCtx.route(`${ORIGIN}/api/auth/discord/start*`, async (route) => {
const res = await fetch(route.request().url(), { redirect: 'manual' });
const loc = new URL(res.headers.get('location')!);
const back = `${ORIGIN}/api/auth/discord/callback?code=${SUPER}&state=${loc.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 a = await adminCtx.newPage();
const errors: string[] = [];
a.on('pageerror', (e) => errors.push(e.message));
await step('일반 사용자는 관리자 페이지 접근 불가', async () => {
await a.goto(ORIGIN + '/admin');
await a.getByText('권한이 없어요').waitFor();
});
await step('슈퍼어드민 디스코드 로그인 → 계정 페이지에 관리자 버튼', async () => {
await a.goto(ORIGIN + '/me');
await a.getByRole('link', { name: '디스코드로 로그인' }).click();
await a.waitForURL(`${ORIGIN}/me`);
await a.getByRole('button', { name: /관리자 페이지 \(슈퍼어드민\)/ }).click();
await a.getByText('지금 접속').waitFor();
await a.screenshot({ path: join(SHOTS, 'admin-1-dashboard.png') });
});
await step('상단 계정 메뉴에 [관리자 메뉴] → 관리자 화면', async () => {
await a.goto(ORIGIN + '/');
await a.getByRole('button', { name: /내 계정:/ }).click();
await a.getByRole('menuitem', { name: /관리자 메뉴/ }).click();
await a.waitForURL(`${ORIGIN}/admin`);
await a.getByText('지금 접속').waitFor();
});
await step('게임 설정: 오목 렌주룰 고정 + 한 수 45초 + 위협 가이드 켜기 저장', async () => {
await a.locator('.admin-side').getByRole('link', { name: '게임', exact: true }).click();
await a.getByRole('button', { name: /오목/ }).click();
await a.getByText('기본 규칙').waitFor();
const rule = a.locator('div.stack:has(> div.row > strong:text-is("규칙"))').first();
await rule.locator('select').selectOption('renju');
await rule.getByLabel(/방장 변경 금지/).check();
const per = a.locator('div.stack:has(> div.row > strong:text-is("한 수 제한(초)"))').first();
await per.locator('input[type=number]').fill('45');
const threat = a.locator('div.stack:has(> div.row > strong:text-is("위협 가이드(관리자 전용): 상대 3·4를 막을 자리 표시"))').first();
await threat.getByRole('button', { name: '켜기', exact: true }).click();
await a.screenshot({ path: join(SHOTS, 'admin-2-game-editor.png') });
await a.getByRole('button', { name: '저장', exact: true }).click();
await a.getByText('저장했어요.').waitFor();
const saved = await a.evaluate(async () => (await (await fetch('/api/admin/games')).json()).games.find((x: any) => x.id === 'omok').effective.defaultOptions.threatHints);
if (saved !== true) throw new Error(`threatHints not saved: ${saved}`);
});
await step('관리자 탭: 디스코드 ID로 어드민 추가', async () => {
await a.locator('.admin-side').getByRole('link', { name: '관리자', exact: true }).click();
await a.getByLabel('디스코드 ID(숫자)').fill('222222222222222222');
await a.getByLabel('메모(선택)').fill('친구');
await a.getByRole('button', { name: '추가', exact: true }).click();
await a.getByText('222222222222222222 · 친구').waitFor();
await a.screenshot({ path: join(SHOTS, 'admin-3-admins.png') });
});
await step('사이트 탭: 게임 속도 배율 2배 저장 → /api/config 반영', async () => {
await a.locator('.admin-side').getByRole('link', { name: '사이트', exact: true }).click();
const speed = a.getByRole('group', { name: /게임 속도 배율/ });
await speed.getByRole('button', { name: '2배', exact: true }).click();
await a.getByText('지금 값: 2배').waitFor();
await a.getByLabel('직접 입력(배)').evaluate((el) => el.scrollIntoView({ block: 'center' }));
await a.screenshot({ path: join(SHOTS, 'admin-4-speed.png') });
await a.getByRole('button', { name: '저장', exact: true }).click();
await a.getByText('저장했어요.').waitFor();
const cfg = await a.evaluate(async () => (await (await fetch('/api/config')).json()).gameSpeed);
if (cfg !== 2) throw new Error(`gameSpeed not saved: ${cfg}`);
});
await step('사이트 탭: 채팅 도배 방지는 기본 끄기, 켜기 저장 → 서버에 바로 반영', async () => {
const guard = a.getByRole('group', { name: '채팅 도배 방지' });
if ((await guard.getByRole('button', { name: '끄기' }).getAttribute('aria-pressed')) !== 'true') throw new Error('chat flood guard should default to off');
if (app.settings.getSite().chatFloodGuard !== false) throw new Error('server default should be off');
await guard.getByRole('button', { name: '켜기' }).click();
await guard.evaluate((el) => el.scrollIntoView({ block: 'center' }));
await a.screenshot({ path: join(SHOTS, 'admin-5-chat-flood-guard.png') });
await a.getByRole('button', { name: '저장', exact: true }).click();
await a.getByText('저장했어요.').last().waitFor();
for (let i = 0; i < 20 && app.settings.getSite().chatFloodGuard !== true; i++) await a.waitForTimeout(100);
if (app.settings.getSite().chatFloodGuard !== true) throw new Error('chat flood guard not saved');
});
await step('사이트 탭: 채팅 소리 크기 기본 80%, 150% 저장 → /api/config 반영', async () => {
const pct = a.getByLabel('채팅 소리 크기(%)');
if ((await pct.inputValue()) !== '80') throw new Error(`chat sound should default to 80: ${await pct.inputValue()}`);
await pct.fill('150');
await pct.evaluate((el) => el.scrollIntoView({ block: 'center' }));
await a.getByRole('button', { name: '들어 보기' }).click();
await a.screenshot({ path: join(SHOTS, 'admin-6-chat-sound.png') });
await a.getByRole('button', { name: '저장', exact: true }).click();
await a.getByText('저장했어요.').last().waitFor();
const cfg = await a.evaluate(async () => (await (await fetch('/api/config')).json()).chatSound);
if (cfg !== 150) throw new Error(`chatSound not saved: ${cfg}`);
});
await step('라이어 제시어: 과일에 제시어 더하기(묶음·다른 표기·설명) → 저장 → 새 주제 추가', async () => {
await a.locator('.admin-side').getByRole('link', { name: '라이어 제시어', exact: true }).click();
await a.getByRole('heading', { name: '라이어 게임 제시어' }).waitFor();
await a.locator('.card:has(strong:text-is("과일"))').getByRole('button', { name: '편집' }).click();
await a.getByRole('heading', { name: '과일 주제' }).waitFor();
await a.getByRole('button', { name: '+ 제시어 더하기' }).click();
await a.getByLabel('제시어(두 글자 이상)').fill('람부탄');
await a.getByLabel('비슷한 단어 묶음').fill('열대 과일');
await a.getByLabel(/정답으로 쳐 줄 다른 표기/).fill('람부땅');
await a.getByLabel(/컴퓨터가 쓸 설명/).fill('겉에 털 같은 가시가 있어요\n껍질을 까면 하얀 속살이 나와요');
await a.getByRole('button', { name: '확인', exact: true }).click();
await a.getByText('설명 2개 · 겉에 털 같은 가시가 있어요').waitFor();
await a.screenshot({ path: join(SHOTS, 'admin-7-liar-words.png') });
await a.getByRole('button', { name: /^저장/ }).click();
await a.getByText('저장했어요. 새로 시작하는 판부터 쓰여요.').waitFor();
const fruit = await a.evaluate(async () => (await (await fetch('/api/admin/liar/topics')).json()).topics.find((t: any) => t.id === 'fruit'));
const w = fruit.words.find((x: any) => x.word === '람부탄');
if (!fruit.modified || w?.group !== '열대 과일' || w.aliases?.[0] !== '람부땅') throw new Error(`liar word not saved: ${JSON.stringify(w)}`);
// A word inside its own hint is refused with the reason.
await a.getByRole('button', { name: '+ 제시어 더하기' }).click();
await a.getByLabel('제시어(두 글자 이상)').fill('잭프루트');
await a.getByLabel(/컴퓨터가 쓸 설명/).fill('잭프루트는 아주 커요');
await a.getByRole('button', { name: '확인', exact: true }).click();
await a.getByRole('button', { name: /^저장/ }).click();
await a.getByRole('alert').getByText(/'잭프루트'의 설명/).waitFor();
await a.getByRole('button', { name: '잭프루트 삭제' }).click();
await a.getByRole('button', { name: /^저장/ }).click();
await a.getByText('저장했어요. 새로 시작하는 판부터 쓰여요.').last().waitFor();
await a.getByRole('button', { name: '← 주제 목록' }).click();
await a.getByRole('button', { name: '+ 새 주제' }).click();
await a.getByLabel('주제 이름(게임 화면에 보여요)').fill('우리 반');
for (const [word, hint] of [
['칠판', '앞에 걸려 있어요'],
['사물함', '뒤에 있어요'],
]) {
await a.getByRole('button', { name: '+ 제시어 더하기' }).click();
await a.getByLabel('제시어(두 글자 이상)').fill(word!);
await a.getByLabel(/컴퓨터가 쓸 설명/).fill(hint!);
await a.getByRole('button', { name: '확인', exact: true }).click();
}
await a.getByRole('button', { name: /^저장/ }).click();
await a.waitForURL(/\/admin\/liar\/c_/);
const topics = await a.evaluate(async () => (await (await fetch('/api/liar/topics')).json()).topics);
if (topics.at(-1)?.ko !== '우리 반' || topics.at(-1)?.words !== 2) throw new Error(`new topic missing: ${JSON.stringify(topics.at(-1))}`);
await a.getByRole('button', { name: '← 주제 목록' }).click();
await a.getByText('관리자가 더함 · 제시어 2개').waitFor();
await a.screenshot({ path: join(SHOTS, 'admin-8-liar-topics.png') });
});
await step('기록 탭에 변경 내역', async () => {
await a.locator('.admin-side').getByRole('link', { name: '기록', exact: true }).click();
await a.getByText('어드민 추가').waitFor();
await a.getByText('게임 설정 변경').waitFor();
await a.getByText('라이어 주제 추가').waitFor();
});
await step('게스트의 새 오목 방: 렌주룰 · 45초 + 잠금 안내', async () => {
const g = await (await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'ko-KR' })).newPage();
g.on('pageerror', (e) => errors.push(e.message));
await g.goto(ORIGIN + '/');
await g.getByRole('button', { name: '+ 방 만들기' }).click();
await g.getByRole('dialog', { name: '게임 고르기' }).getByRole('button', { name: /오목/ }).click();
await g.getByLabel('내 이름(닉네임)').fill('손님');
await g.getByRole('button', { name: '이 이름으로 시작하기' }).click();
await g.waitForURL(/\/r\/\d{6}$/);
await g.getByText('렌주룰 · 15줄 · 한 수 45초').waitFor();
await g.getByText('일부 규칙은 관리자가 정해 두어서').waitFor();
// The admin turned the threat guide on; the host has no switch for it (checked below).
// Trying to switch to 한국식 is overridden by the server.
await g.getByRole('button', { name: '설정 바꾸기' }).click();
if (await g.getByText(/위험한 자리 알려|위협 가이드/).count()) throw new Error('host sees a threat-guide switch');
// Changes apply at once; the server keeps the locked rule and the sheet follows it.
await g.getByRole('button', { name: '한국식(쌍삼 금지)' }).click();
await g.waitForTimeout(300);
if ((await g.getByRole('button', { name: '렌주룰' }).getAttribute('aria-pressed')) !== 'true') throw new Error('locked rule not restored in the sheet');
await g.getByRole('button', { name: '닫기' }).click();
await g.getByText('렌주룰 · 15줄 · 한 수 45초').waitFor();
await g.goto(ORIGIN + '/admin');
await g.getByText('권한이 없어요').waitFor();
});
await step('게스트의 새 라이어 방: 관리자가 더한 주제를 고를 수 있어요', async () => {
const g = await (await browser.newContext({ viewport: { width: 390, height: 844 }, locale: 'ko-KR' })).newPage();
g.on('pageerror', (e) => errors.push(e.message));
await g.goto(ORIGIN + '/');
await g.getByRole('button', { name: '+ 방 만들기' }).click();
await g.getByRole('dialog', { name: '게임 고르기' }).getByRole('button', { name: /라이어 게임/ }).click();
await g.getByLabel('내 이름(닉네임)').fill('손님둘');
await g.getByRole('button', { name: '이 이름으로 시작하기' }).click();
await g.waitForURL(/\/r\/\d{6}$/);
await g.getByRole('button', { name: '설정 바꾸기' }).click();
await g.getByRole('group', { name: '주제' }).getByRole('button', { name: '우리 반' }).click();
await g.waitForTimeout(300);
await g.screenshot({ path: join(SHOTS, 'admin-9-liar-lobby.png') });
await g.getByRole('button', { name: '닫기' }).click();
await g.getByText(/주제 우리 반/).first().waitFor();
});
if (errors.length) throw new Error(`page errors: ${errors.join(' | ')}`);
} catch (e) {
failed = true;
console.error(e);
} finally {
await browser.close();
await app.stop();
}
console.log(failed ? 'E2E FAILED' : 'E2E PASSED');
process.exit(failed ? 1 : 0);