Files
music_quiz/apps/server/src/duel.test.ts

167 lines
10 KiB
TypeScript

/** 이지선다: points (역배), quiz kinds kept apart, a game in both 진행 방식 (매번 새 두 곡 / 연속). */
import { afterEach, expect, test } from 'bun:test';
import type { DuelSide, GameView, ServerMessage } from '@mq/shared';
import { duelGains, duelWinner } from './game/duel';
import { Client, TEST_SUPERADMINS, api, boot, discordLogin, guest } from './test-utils';
type Msg<T extends ServerMessage['t']> = Extract<ServerMessage, { t: T }>;
const fakeDiscord = async (code: string) => ({ id: code, username: 'u', global_name: `회원${code.slice(-2)}`, avatar: null });
let s: ReturnType<typeof boot>;
afterEach(async () => s && (await s.stop()));
test('points: everyone right gets 1; 역배 (alone right against 2 or more) gets 2; equal views = both right', () => {
const picks = (xs: [string, DuelSide][]) => new Map(xs);
const pts = (m: Map<string, { points: number; reverse: boolean }>) => Object.fromEntries([...m].map(([id, g]) => [id, g.points]));
// 4:1, the one is right
expect(pts(duelGains(picks([['a', 'b'], ['b', 'a'], ['c', 'a'], ['d', 'a'], ['e', 'a']]), 'b'))).toEqual({ a: 2 });
// 4:1, the four are right
expect(pts(duelGains(picks([['a', 'b'], ['b', 'a'], ['c', 'a'], ['d', 'a'], ['e', 'a']]), 'a'))).toEqual({ b: 1, c: 1, d: 1, e: 1 });
// 1:1 and 3:2: no 역배
expect(pts(duelGains(picks([['a', 'a'], ['b', 'b']]), 'a'))).toEqual({ a: 1 });
expect(pts(duelGains(picks([['a', 'a'], ['b', 'a'], ['c', 'b'], ['d', 'b'], ['e', 'b']]), 'a'))).toEqual({ a: 1, b: 1 });
// alone, nobody else picked: 1
expect(pts(duelGains(picks([['a', 'a']]), 'a'))).toEqual({ a: 1 });
// equal views: whoever picked is right
expect(pts(duelGains(picks([['a', 'a'], ['b', 'b'], ['c', 'b']]), 'both'))).toEqual({ a: 1, b: 1, c: 1 });
expect(duelGains(picks([['a', 'a'], ['b', 'b'], ['c', 'b']]), 'a').get('a')).toEqual({ points: 2, reverse: true });
expect([duelWinner(5, 3), duelWinner(3, 5), duelWinner(4, 4)]).toEqual(['a', 'b', 'both']);
});
const VIEWS: Record<string, number> = { vvvvvvvvv01: 1000, vvvvvvvvv02: 5000, vvvvvvvvv03: 300, vvvvvvvvv04: 90000 };
const duelItem = (videoId: string) => ({ songId: null, videoId, title: `곡${videoId.slice(-2)}`, artist: '가수', titleAnswers: [], artistAnswers: [], hints: [], fromFile: true, durationSec: null, auto: true, startSec: null, highlightSec: null, views: VIEWS[videoId] });
async function setup() {
s = boot({ gameTiming: { countdownMs: 40, revealMs: 120, resumeLeadMs: 30, clipGraceMs: 150, lateMs: 150, tickMs: 20, limitMs: 400 }, discordExchange: fakeDiscord }, { DISCORD_CLIENT_ID: 'cid', DISCORD_CLIENT_SECRET: 'sec' });
const sa = (await discordLogin(s.base, TEST_SUPERADMINS[0])).cookie!;
const file = (body: Record<string, unknown>) => api(s.base, '/api/admin/quizzes/file', { method: 'POST', cookie: sa, body: JSON.stringify(body) });
// an 이지선다 quiz needs 2 songs or more
expect((await file({ name: 'x', kind: 'duel', items: [duelItem('vvvvvvvvv01')] })).res.status).toBe(400);
const duel = await file({ name: '조회수 대결', kind: 'duel', items: Object.keys(VIEWS).map(duelItem) });
expect(duel.res.status).toBe(200);
const normal = await file({ name: '일반 퀴즈', items: [{ ...duelItem('nnnnnnnnn01'), views: 5 }] });
const detail = (await api(s.base, `/api/admin/quizzes/${duel.body.id}`, { cookie: sa })).body.quiz;
expect(detail.kind).toBe('duel');
expect(detail.items.map((i: { views: number }) => i.views)).toEqual([1000, 5000, 300, 90000]);
// a 일반 퀴즈 file keeps no views
expect((await api(s.base, `/api/admin/quizzes/${normal.body.id}`, { cookie: sa })).body.quiz.items[0].views).toBeNull();
// each kind is listed only for its own mode
const list = async (kind: string) => (await api(s.base, `/api/made-quizzes?kind=${kind}`, { cookie: sa })).body.quizzes.map((q: { name: string }) => q.name);
expect(await list('duel')).toEqual(['조회수 대결']);
expect(await list('normal')).toEqual(['일반 퀴즈']);
return { sa, duelId: duel.body.id as number, normalId: normal.body.id as number };
}
async function room(host: string, players: string[]) {
const code: string = (await api(s.base, '/api/rooms', { method: 'POST', cookie: host, body: '{}' })).body.code;
const cls = await Promise.all([host, ...players].map((c) => new Client(s.base, c).connect()));
for (const cl of cls) {
cl.send({ t: 'join', code });
await cl.waitFor((m) => m.t === 'room');
}
return { code, cls };
}
const gameOf = (m: ServerMessage) => (m.t === 'game' ? m.game : null);
test('quiz kinds: picking an 이지선다 퀴즈 makes the room 이지선다; another mode drops it; no quiz, no start', async () => {
const { sa, duelId, normalId } = await setup();
const { cls } = await room(sa, []);
const host = cls[0]!;
host.send({ t: 'config', patch: { mode: 'duel' } });
const none = (await host.waitFor((m) => m.t === 'room' && m.room.config.mode === 'duel')) as Msg<'room'>;
// no 이지선다 퀴즈 yet: no songs (not the server DB pool)
expect(none.room.pool).toEqual({ playable: 0, total: 0 });
host.send({ t: 'start' });
await host.waitFor((m) => m.t === 'error' && m.message.includes('이지선다 퀴즈를 골라'));
host.send({ t: 'config', patch: { quizId: duelId } });
const r = (await host.waitFor((m) => m.t === 'room' && m.room.config.quizId === duelId)) as Msg<'room'>;
expect(r.room.config).toMatchObject({ mode: 'duel', quizName: '조회수 대결', duelSec: 30, duelFlow: 'pairs' });
expect(r.room.pool.playable).toBe(4);
// back to 듣고맞추기: the 이지선다 퀴즈 does not fit any more
host.send({ t: 'config', patch: { mode: 'listen' } });
await host.waitFor((m) => m.t === 'room' && m.room.config.mode === 'listen' && m.room.config.quizId === null);
// a 일반 퀴즈 is played as 듣고맞추기, switching to 이지선다 drops it
host.send({ t: 'config', patch: { quizId: normalId } });
await host.waitFor((m) => m.t === 'room' && m.room.config.quizId === normalId && m.room.config.mode === 'listen');
host.send({ t: 'config', patch: { mode: 'duel' } });
await host.waitFor((m) => m.t === 'room' && m.room.config.mode === 'duel' && m.room.config.quizId === null);
host.send({ t: 'config', patch: { duelSec: 15, duelFlow: 'chain' } });
await host.waitFor((m) => m.t === 'room' && m.room.config.duelSec === 15 && m.room.config.duelFlow === 'chain');
host.close();
});
test('매번 새 두 곡: picks show under the cards and can change, views come at the end, 역배 gets 2 points', async () => {
const { sa, duelId } = await setup();
const g1 = await guest(s.base, '손님1');
const g2 = await guest(s.base, '손님2');
const { cls } = await room(sa, [g1.cookie, g2.cookie]);
const [host, p1, p2] = cls as [Client, Client, Client];
host.send({ t: 'config', patch: { quizId: duelId } });
await host.waitFor((m) => m.t === 'room' && m.room.config.quizId === duelId);
host.send({ t: 'start' });
const q1 = gameOf(await host.waitFor((m) => gameOf(m)?.n === 1 && gameOf(m)?.phase === 'play'))!;
expect(q1.total).toBe(2);
const cards = q1.duel!.cards;
expect(cards.map((c) => c.side)).toEqual(['a', 'b']);
expect(cards.every((c) => c.views === null && c.picks.length === 0)).toBe(true);
const high: DuelSide = VIEWS[cards[0]!.videoId]! > VIEWS[cards[1]!.videoId]! ? 'a' : 'b';
const low: DuelSide = high === 'a' ? 'b' : 'a';
// the host first goes with the others, then changes to the right card alone
host.send({ t: 'pick', n: 1, side: low });
p1.send({ t: 'pick', n: 1, side: low });
p2.send({ t: 'pick', n: 1, side: low });
await host.waitFor((m) => gameOf(m)?.duel?.cards.find((c) => c.side === low)?.picks.length === 3);
host.send({ t: 'pick', n: 1, side: high });
const moved = gameOf(await host.waitFor((m) => gameOf(m)?.duel?.cards.find((c) => c.side === high)?.picks.length === 1))!;
expect(moved.duel!.cards.find((c) => c.side === low)!.picks).toHaveLength(2);
const rev = gameOf(await host.waitFor((m) => gameOf(m)?.phase === 'reveal'))!;
expect(rev.duel!.cards.map((c) => c.views)).toEqual(cards.map((c) => VIEWS[c.videoId]!));
expect(rev.duel!.result!.winner).toBe(high);
expect(rev.duel!.result!.gains).toHaveLength(1);
expect(rev.duel!.result!.gains[0]).toMatchObject({ points: 2, reverse: true });
expect(rev.scores[0]).toMatchObject({ score: 2, correct: 1, reverse: 1 });
expect(rev.history[0]!.duel!.winner).toBe(high);
const answer = (await host.waitFor((m) => m.t === 'answer')) as Msg<'answer'>;
expect(answer.line.text).toContain('역배 성공');
// question 2: two new songs; nobody picks → nobody gets points; then the results
const q2 = gameOf(await host.waitFor((m) => gameOf(m)?.n === 2 && gameOf(m)?.phase === 'play'))!;
expect(new Set([...cards, ...q2.duel!.cards].map((c) => c.videoId)).size).toBe(4);
// a late tap for question 1 changes nothing
p1.send({ t: 'pick', n: 1, side: 'a' });
const end = gameOf(await host.waitFor((m) => gameOf(m)?.phase === 'result'))!;
expect(end.history).toHaveLength(2);
expect(end.history[1]!.duel!.gains).toEqual([]);
expect(end.left).toBe(0);
for (const c of cls) c.close();
});
test('연속: the higher song stays as A with its views shown, a new song comes as B', async () => {
const { sa, duelId } = await setup();
const { cls } = await room(sa, []);
const host = cls[0]!;
host.send({ t: 'config', patch: { quizId: duelId, duelFlow: 'chain' } });
await host.waitFor((m) => m.t === 'room' && m.room.config.quizId === duelId && m.room.config.duelFlow === 'chain');
host.send({ t: 'start' });
const seen: GameView[] = [];
for (let n = 1; n <= 3; n++) {
const q = gameOf(await host.waitFor((m) => gameOf(m)?.n === n && gameOf(m)?.phase === 'play'))!;
seen.push(q);
host.send({ t: 'pick', n, side: 'a' });
await host.waitFor((m) => gameOf(m)?.n === n && gameOf(m)?.phase === 'reveal');
}
expect(seen[0]!.total).toBe(3);
expect(seen[0]!.duel!.cards[0]!.views).toBeNull();
for (let i = 1; i < 3; i++) {
const prev = seen[i - 1]!.duel!.cards;
const stay = VIEWS[prev[0]!.videoId]! >= VIEWS[prev[1]!.videoId]! ? prev[0]! : prev[1]!;
const [a, b] = seen[i]!.duel!.cards;
expect(a!.videoId).toBe(stay.videoId);
expect(a!.views).toBe(VIEWS[stay.videoId]!);
expect(b!.views).toBeNull();
}
const end = gameOf(await host.waitFor((m) => gameOf(m)?.phase === 'result'))!;
expect(end.history).toHaveLength(3);
host.close();
});