M1 서버: 통합 테스트 + 방 단위 테스트, 종료 대기·중도 이탈 자리 처리 수정

- 실제 서버 + WS 클라이언트로 테스트 문서 3절 시나리오 검증(방 만들기·링크 입장·재접속·
  서버 강제 종료 후 복구·차례 위반·중복 cs·탭 교체·방장 이전·도배 제한·잘못된 메시지·
  Origin 검사·디스코드 콜백 state 검증·게스트 합치기)
- 시계를 조작하는 방 단위 테스트: 시간 초과 자동 착수, 연결 끊김 유예, 재시작 후 마감 30초 유예,
  게임 오류 격리(3회 → 일시 정지), 한 판 더 흑백 교대, 게임 중 나가기
- Bun server.stop()이 서버 쪽 WS 종료 뒤 끝나지 않는 문제: 대기 시간 1초로 제한
- 게임 중 나간 사람의 자리가 게임 종료 후 비워지지 않던 버그 수정

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-04 04:24:49 +09:00
parent 0f4d22f413
commit b1f3d7c500
5 changed files with 622 additions and 5 deletions

View File

@@ -0,0 +1,300 @@
/** Integration scenarios from docs/10-testing.md §3. */
import { afterEach, describe, expect, test } from 'bun:test';
import { Client, api, boot, guest, sleep } from './test-utils';
type Booted = ReturnType<typeof boot>;
const running: Booted[] = [];
const clients: Client[] = [];
afterEach(async () => {
for (const c of clients.splice(0)) {
try {
c.close();
} catch {}
}
for (const s of running.splice(0)) {
try {
await s.stop();
} catch {}
}
});
function start(dbPath?: string): Booted {
const s = boot(dbPath);
running.push(s);
return s;
}
async function client(s: Booted, nick: string, cookie?: { cookie: string; id: string }): Promise<Client> {
const g = cookie ?? (await guest(s.base, nick));
const c = await new Client(s.base, g.cookie, g.id).connect();
clients.push(c);
return c;
}
async function createRoom(s: Booted, c: Client, gameId = 'omok'): Promise<string> {
const r = await api(s.base, '/api/rooms', { method: 'POST', cookie: c.cookie, body: JSON.stringify({ gameId }) });
expect(r.res.status).toBe(200);
return r.body.code;
}
async function join(c: Client, code: string, as: 'player' | 'spectator' = 'player') {
c.send({ t: 'join', code, as });
return c.next('room');
}
/** A hosts (black), B joins; game started. */
async function twoPlayerGame(s: Booted) {
const a = await client(s, '호랑이');
const b = await client(s, '고양이');
const code = await createRoom(s, a);
await join(a, code);
await join(b, code);
a.send({ t: 'config', options: { colorAssignment: 'hostBlack', ruleSet: 'free' } });
await a.next('room', (m) => (m.room.options as any).colorAssignment === 'hostBlack');
const sa = a.next('state');
const sb = b.next('state');
a.send({ t: 'start' });
await Promise.all([sa, sb]);
return { a, b, code };
}
const place = (c: Client, x: number, y: number) => c.act({ type: 'place', x, y });
describe('M1 integration scenarios', () => {
test('1. create room, join by code, auto-seat, play omok to the end, result stored', async () => {
const s = start();
const { a, b, code } = await twoPlayerGame(s);
expect(code).toMatch(/^\d{6}$/);
const room = a.lastOf('room')!.room;
expect(room.seats.filter(Boolean).map((x) => x!.user.nickname)).toEqual(['호랑이', '고양이']);
// Black (A) plays a horizontal five, White (B) answers elsewhere.
for (let i = 0; i < 4; i++) {
let p = b.next('state', (m) => (m.view as any).turn === 'white');
place(a, 3 + i, 7);
await p;
p = a.next('state', (m) => (m.view as any).turn === 'black');
place(b, 3 + i, 0);
await p;
}
const res = a.next('result');
place(a, 7, 7);
const r = await res;
expect(r.result.ranking).toEqual([[a.id], [b.id]]);
const stats = await api(s.base, '/api/me/stats', { cookie: a.cookie });
expect(stats.body.stats).toEqual([{ gameId: 'omok', played: 1, wins: 1, draws: 0 }]);
const room2 = (await a.next('room', (m) => m.room.status === 'finished').catch(() => a.lastOf('room')!)).room;
expect(room2.lastSeed).toMatch(/^[0-9a-f]{32}$/);
expect(room2.sessionStats[a.id]).toEqual({ played: 1, wins: 1 });
});
test('2. joining via link preview without login, then guest + auto seat', async () => {
const s = start();
const a = await client(s, '방장님');
const code = await createRoom(s, a);
await join(a, code);
const preview = await api(s.base, `/api/rooms/${code}`);
expect(preview.body).toMatchObject({ code, gameId: 'omok', host: '방장님', seated: 1, maxPlayers: 2 });
const b = await client(s, '손님');
const r = await join(b, code);
expect(r.room.seats[1]?.user.id).toBe(b.id);
// A third person becomes a spectator.
const c = await client(s, '구경꾼');
const r3 = await join(c, code);
expect(r3.room.spectators.map((u) => u.id)).toContain(c.id);
});
test('3. disconnect and reconnect keeps seat and state', async () => {
const s = start();
const { a, b, code } = await twoPlayerGame(s);
const p = b.next('state', (m) => (m.view as any).moveCount === 1);
place(a, 7, 7);
await p;
const notice = a.next('notice', (m) => m.code === 'disconnected');
b.close();
await notice;
const roomMsg = await a.next('room', (m) => m.room.seats[1]?.connected === false).catch(() => a.lastOf('room')!);
expect(roomMsg.room.seats[1]?.connected).toBe(false);
const b2 = await client(s, '', { cookie: b.cookie, id: b.id });
expect(b2.lastOf('welcome')!.activeRoom).toBe(code);
b2.send({ t: 'join', code, as: 'player' });
const st = await b2.next('state');
expect((st.view as any).board[7 * 15 + 7]).toBe(1);
expect((st.view as any).turn).toBe('white');
const after = b2.lastOf('room') ?? (await b2.next('room'));
expect(after.room.seats[1]?.user.id).toBe(b.id);
});
test('4. server crash (no graceful stop) → restart restores the game', async () => {
const s1 = boot();
const { a, b, code } = await twoPlayerGame(s1);
let p = b.next('state', (m) => (m.view as any).moveCount === 1);
place(a, 7, 7);
await p;
p = a.next('state', (m) => (m.view as any).moveCount === 2);
place(b, 0, 0);
await p;
// Simulate a crash: drop the listener and timers without the graceful bye/cleanup.
for (const r of s1.rooms.all()) r.clearTimer();
await Promise.race([s1.server.stop(true), sleep(300)]);
s1.db.close();
const s2 = start(s1.dbPath);
const a2 = await client(s2, '', { cookie: a.cookie, id: a.id });
const b2 = await client(s2, '', { cookie: b.cookie, id: b.id });
expect(a2.lastOf('welcome')!.activeRoom).toBe(code);
a2.send({ t: 'join', code, as: 'player' });
b2.send({ t: 'join', code, as: 'player' });
const st = await a2.next('state');
const v = st.view as any;
expect(v.moveCount).toBe(2);
expect(v.turn).toBe('black');
const p2 = b2.next('state', (m) => (m.view as any).moveCount === 3);
place(a2, 8, 8);
await p2;
});
test('5. acting out of turn is rejected without state change', async () => {
const s = start();
const { a, b } = await twoPlayerGame(s);
const before = b.lastOf('state')!.seq;
const rej = b.next('reject');
const cs = place(b, 1, 1);
const r = await rej;
expect(r.cs).toBe(cs);
expect(r.reason).toBe('지금은 내 차례가 아니에요.');
await sleep(50);
expect(a.lastOf('state')!.seq).toBe(before);
});
test('6. duplicate cs is processed once', async () => {
const s = start();
const { a, b } = await twoPlayerGame(s);
const cs = place(a, 7, 7);
a.send({ t: 'act', cs, a: { type: 'place', x: 8, y: 8 } });
await b.next('state', (m) => (m.view as any).moveCount >= 1);
await sleep(100);
const states = b.messages.filter((m) => m.t === 'state');
expect((states[states.length - 1]!.view as any).moveCount).toBe(1);
const mine = a.messages.filter((m) => m.t === 'state' && m.cs === cs);
expect(mine).toHaveLength(1);
});
test('7. second tab replaces the first', async () => {
const s = start();
const a = await client(s, '탭주인');
const code = await createRoom(s, a);
await join(a, code);
const a2 = await client(s, '', { cookie: a.cookie, id: a.id });
const bye = a.next('bye');
await join(a2, code);
expect((await bye).reason).toBe('replaced');
});
test('9. host leaves → host transfers', async () => {
const s = start();
const a = await client(s, '첫방장');
const b = await client(s, '다음방장');
const code = await createRoom(s, a);
await join(a, code);
await join(b, code);
const r = b.next('room', (m) => m.room.hostId === b.id);
a.send({ t: 'leave' });
expect((await r).room.seats.filter(Boolean)).toHaveLength(1);
});
test('10. flooding is rate limited and the server stays healthy', async () => {
const s = start();
const a = await client(s, '도배왕');
for (let i = 0; i < 100; i++) a.send({ t: 'ping', ts: i });
await sleep(200);
const pongs = a.messages.filter((m) => m.t === 'pong').length;
expect(pongs).toBeLessThanOrEqual(45);
expect(pongs).toBeGreaterThan(0);
const h = await api(s.base, '/healthz');
expect(h.res.status).toBe(200);
});
test('11. malformed / oversized / schema-invalid messages', async () => {
const s = start();
const a = await client(s, '이상한값');
a.ws.send('{not json');
await a.next('error', (m) => m.code === 'bad-json');
a.send({ t: 'act', cs: 'x' });
await a.next('error', (m) => m.code === 'bad-message');
a.ws.send('x'.repeat(20 * 1024));
for (let i = 0; i < 20 && !a.closed; i++) await sleep(25);
expect(a.closed?.code).toBe(1009);
const h = await api(s.base, '/healthz');
expect(h.res.status).toBe(200);
});
test('12a. discord login is hidden when not configured', async () => {
const s = boot(undefined, {
discordExchange: async () => ({ id: '123', username: 'disco', global_name: '디코친구', avatar: null }),
});
running.push(s);
// Discord disabled in this config → 404.
const off = await api(s.base, '/api/auth/discord/start');
expect(off.res.status).toBe(404);
});
test('origin check: foreign origin cannot open WS or POST', async () => {
const s = start();
const g = await guest(s.base, '보안확인');
const res = await fetch(s.base + '/ws', { headers: { origin: 'https://evil.example', cookie: g.cookie, upgrade: 'websocket', connection: 'Upgrade', 'sec-websocket-key': 'dGhlIHNhbXBsZSBub25jZQ==', 'sec-websocket-version': '13' } });
expect(res.status).toBe(403);
const post = await fetch(s.base + '/api/rooms', { method: 'POST', headers: { origin: 'https://evil.example', cookie: g.cookie, 'content-type': 'application/json' }, body: '{"gameId":"omok"}' });
expect(post.status).toBe(403);
});
test('nickname rules and change', async () => {
const s = start();
const bad = await api(s.base, '/api/auth/guest', { method: 'POST', body: JSON.stringify({ nickname: 'a' }) });
expect(bad.res.status).toBe(400);
const g = await guest(s.base, ' 처음 이름 ');
const me = await api(s.base, '/api/me', { cookie: g.cookie });
expect(me.body.me.nickname).toBe('처음 이름');
const ch = await api(s.base, '/api/me', { method: 'PATCH', cookie: g.cookie, body: JSON.stringify({ nickname: '바뀐이름' }) });
expect(ch.body.me.nickname).toBe('바뀐이름');
});
test('chat is filtered and spectators receive public view only', async () => {
const s = start();
const { a, code } = await twoPlayerGame(s);
const c = await client(s, '관전자');
c.send({ t: 'join', code, as: 'spectator' });
const st = await c.next('state');
expect((st.view as any).myColor).toBeNull();
const chat = c.next('chat');
a.send({ t: 'chat', text: '안녕 씨발' });
expect((await chat).text).toBe('안녕 **');
});
});
describe('Discord login flow', () => {
test('state mismatch rejected, valid flow merges guest into new member', async () => {
const s = boot(undefined, {
discordExchange: async () => ({ id: '42', username: 'disco', global_name: '디코친구', avatar: 'abc' }),
});
running.push(s);
s.config.discord = { clientId: 'cid', clientSecret: 'sec' };
const g = await guest(s.base, '게스트였음');
const startRes = await api(s.base, '/api/auth/discord/start?next=/r/123456', { cookie: g.cookie });
expect(startRes.res.status).toBe(302);
const loc = new URL(startRes.res.headers.get('location')!);
expect(loc.host).toBe('discord.com');
const state = loc.searchParams.get('state')!;
const oauthCookie = startRes.setCookie!.split(';')[0]!;
const bad = await api(s.base, `/api/auth/discord/callback?code=x&state=wrong`, { cookie: `${g.cookie}; ${oauthCookie}` });
expect(bad.res.headers.get('location')).toBe('/?login=failed');
const good = await api(s.base, `/api/auth/discord/callback?code=x&state=${state}`, { cookie: `${g.cookie}; ${oauthCookie}` });
expect(good.res.headers.get('location')).toBe('/r/123456?linked=1');
const sid = good.setCookie!.split(/,(?=\s*\w+=)/).find((c) => c.trim().startsWith('sid='))!.split(';')[0]!.trim();
const me = await api(s.base, '/api/me', { cookie: sid });
expect(me.body.me).toMatchObject({ id: g.id, nickname: '게스트였음', kind: 'member' });
expect(me.body.me.avatar).toBe('https://cdn.discordapp.com/avatars/42/abc.png?size=128');
// Old guest session no longer valid.
const old = await api(s.base, '/api/me', { cookie: g.cookie });
expect(old.body.me).toBeNull();
});
});