Files
joke-app/packages/engine/src/testing.ts
EJClaw 39223bacdd 컴퓨터 방 자동 정리 + 게스트 계정 삭제(로그아웃·하루 미접속) + 테스트 10분→1분
- 방 화면을 벗어나면(홈·규칙) detach: 자리·접속 상태는 유지, 방 접속 수에서 빠짐
- 컴퓨터가 있는 방: 사람이 모두 [방 나가기]하면 바로 닫고, 아무도 안 보면 대기실·끝난 방 1분, 게임 중 30분 뒤 정리
- 게스트 로그아웃 = 계정 삭제(자리·전적·세션·소켓), 사이트를 닫고 24시간 지난 게스트도 1분 주기로 삭제
- users.last_seen_at을 요청·소켓 종료 때 갱신(이전엔 갱신 안 됨), 003 마이그레이션에서 기존 게스트 시계 초기화
- 테스트: 무작위 대국 시드를 playoutSeeds()로 평소 1/10, test:full은 전부. bun test --parallel=4, 테스트 서버 종료 대기 1s→50ms

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

91 lines
3.9 KiB
TypeScript

/**
* Shared test helpers (docs/09-game-engine.md §7): random playouts with invariant checks,
* determinism, JSON round-trip and hidden-info leak detection.
*/
import { SeededRng, type RngState } from './rng';
import type { AnyGameDefinition, PlayerId } from './types';
export interface PlayoutOptions<O> {
players: PlayerId[];
options?: O;
seed: RngState;
maxSteps?: number;
/** Extra invariant per step; throw to fail. */
invariant?: (state: unknown) => void;
maxApplyMs?: number;
}
export interface PlayoutReport {
steps: number;
finished: boolean;
trace: { actor: PlayerId; action: unknown }[];
finalState: unknown;
}
export function randomPlayout<O>(def: AnyGameDefinition, opts: PlayoutOptions<O>): PlayoutReport {
if (!def.legalActions) throw new Error(`${def.id}: legalActions is required for playouts`);
const rng = SeededRng.fromSeed(opts.seed);
const chooser = SeededRng.fromSeed([opts.seed[3], opts.seed[2], opts.seed[1], opts.seed[0] ^ 0x9e3779b9]);
let now = 1_700_000_000_000;
let state = def.setup({ players: opts.players, options: opts.options ?? def.defaultOptions, rng, now });
const trace: PlayoutReport['trace'] = [];
const maxSteps = opts.maxSteps ?? 5000;
for (let step = 0; step < maxSteps; step++) {
checkRoundTrip(state);
for (const p of opts.players) checkNoLeak(def, state, p, opts.players);
opts.invariant?.(state);
if (def.result(state)) return { steps: step, finished: true, trace, finalState: state };
const actives = def.activePlayers(state);
if (actives.length === 0) throw new Error(`${def.id}: no active players but game not finished`);
const actor = actives[chooser.int(actives.length)]!;
const legal = def.legalActions(state, actor);
const action = legal.length > 0 ? legal[chooser.int(legal.length)] : def.onTimeout(state, actor);
const v = def.validate(state, actor, action);
if (!v.ok) throw new Error(`${def.id}: generated action rejected: ${v.reason} ${JSON.stringify(action)}`);
now += 1000;
const t0 = performance.now();
state = def.apply(state, actor, action, { rng, now }).state;
const ms = performance.now() - t0;
if (ms > (opts.maxApplyMs ?? 5)) throw new Error(`${def.id}: apply took ${ms.toFixed(2)}ms`);
trace.push({ actor, action });
}
return { steps: maxSteps, finished: false, trace, finalState: state };
}
export function checkRoundTrip(state: unknown): void {
const json = JSON.stringify(state);
const back = JSON.parse(json);
if (JSON.stringify(back) !== json) throw new Error('state is not JSON round-trippable');
}
/** The viewer's view must not contain secrets belonging to any other player. */
export function checkNoLeak(def: AnyGameDefinition, state: unknown, viewer: PlayerId, players: PlayerId[]): void {
if (!def.secretsOf) return;
const view = JSON.stringify(def.view(state, viewer));
const spectatorView = JSON.stringify(def.view(state, null));
for (const other of players) {
for (const secret of def.secretsOf(state, other)) {
if (other !== viewer && view.includes(JSON.stringify(secret))) {
throw new Error(`${def.id}: view for ${viewer} leaks secret ${secret} of ${other}`);
}
if (spectatorView.includes(JSON.stringify(secret))) {
throw new Error(`${def.id}: spectator view leaks secret ${secret} of ${other}`);
}
}
}
}
export function seedN(n: number): RngState {
return [n >>> 0, (n * 2654435761) >>> 0, (n ^ 0xdeadbeef) >>> 0, (n + 1) >>> 0];
}
/**
* How many random-playout seeds a test runs. Plain `bun test` runs a tenth of `full` so the suite stays quick;
* `FULL_TESTS=1 bun test` (`bun run test:full`, before a release) runs all of them.
*/
export function playoutSeeds(full: number): number {
const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env;
const fullRun = !!env?.FULL_TESTS;
return fullRun ? full : Math.max(1, Math.ceil(full / 10));
}