Stage 3 of the int-suite speedup (gate G2 showed Vitest 4's pool scheduler only reuses worker processes between isolate:false tasks, so per-file fork spawning made clone+boot costs unavoidable at stage 2): - config: workers branch runs pool=forks with isolate:false, cap 8 via VITEST_MAX_FORKS, node default env (jsdom docblocks on DOM specs), failure-marker reporter, and idempotent setupFiles chain - vitest-worker-setup: one template clone PER FORK PROCESS named by pid (VITEST_WORKER_ID churns per task, which silently re-cloned per file); DATABASE_URI repoint + TEST_PG_POOL_MAX=8 (measured hook deadlocks at 3) - vitest.setup: once-per-process serial test URI markers; afterEach useRealTimers guard (restoreAllMocks omitted: it resurrects vi.mock module factories mid-file); logging absorber for fire-and-forget event writes that reject after their spec's cleanup deleted fixture users - helpers/get-test-payload.ts: memoized Payload boot shared across files in a fork; codemod converted all 91 self-booting specs mechanically - pinned opt-outs (own boot + comments): game-structures-labor-route, mission-reminder, notification-inbox-scope (jwtSign writes leak into the shared instance's auth state across files) - promotion-nominations: create the superuser before its rank ladder so the Users-hook Recruit rank gets leading orderable tokens (its top-of-ladder guard needs Col to remain ladder-max on fresh clones); operation-economy: itemType-scope the market-state assertion (asset and resource ids collide as bare integers under per-fork databases) Gate G3: 5 consecutive full green runs (149/149 files), warm wall 53-65s vs 598s baseline (~10x), zero clone residue after green runs. Vitest 4 note: globalTeardown config no longer exists; teardown returns from globalSetup.
352 lines
12 KiB
TypeScript
352 lines
12 KiB
TypeScript
/**
|
|
* In-process registry suite (the HTTP transport backend). The arena port of
|
|
* this game logic has its own suites: tests/int/arena-bomperator.int.spec.ts
|
|
* (module, awards/delivery stubbed) and tests/int/arena-server.int.spec.ts
|
|
* (live server + real sockets). This file stays because the registry remains
|
|
* live behind the HttpTransport fallback until prod proves the arena.
|
|
*/
|
|
import { getTestPayload } from "../helpers/get-test-payload";
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
|
|
import { type Payload } from "payload";
|
|
|
|
import {
|
|
INTER_ROUND_COUNTDOWN_TICKS,
|
|
MAX_SEATS,
|
|
MIN_TO_START,
|
|
RECONNECT_WINDOW_MS,
|
|
} from "@/lib/minigames/bomperator/constants";
|
|
import {
|
|
advanceForTests,
|
|
clearMatchesForTests,
|
|
createMatch,
|
|
endMatch,
|
|
forceExpireMatch,
|
|
getSnapshotFor,
|
|
joinMatch,
|
|
leaveMatch,
|
|
listMatchSummaries,
|
|
setAutoTickForTests,
|
|
startMatch,
|
|
submitInput,
|
|
} from "@/lib/minigames/bomperator/registry";
|
|
import {
|
|
awardBomperatorResult,
|
|
computeBomperatorStatsDelta,
|
|
readBomperatorStats,
|
|
xpForBomperator,
|
|
} from "@/lib/minigames/bomperator/stats";
|
|
|
|
beforeEach(() => {
|
|
setAutoTickForTests(false); // drive the sim manually; no wall-clock intervals
|
|
clearMatchesForTests();
|
|
});
|
|
afterEach(() => clearMatchesForTests());
|
|
afterAll(() => {
|
|
clearMatchesForTests();
|
|
setAutoTickForTests(true);
|
|
});
|
|
|
|
/** Bring a freshly started match out of the countdown and into battle. */
|
|
function toBattle(matchId: string): void {
|
|
advanceForTests(matchId, INTER_ROUND_COUNTDOWN_TICKS + 1);
|
|
}
|
|
|
|
describe("bomperator registry: lobby", () => {
|
|
it("seats the host and reports a waiting match", () => {
|
|
const matchId = createMatch(9001, "Host");
|
|
const summary = listMatchSummaries(9001).find((row) => row.matchId === matchId);
|
|
expect(summary?.phase).toBe("waiting");
|
|
expect(summary?.seatedCount).toBe(1);
|
|
expect(summary?.joined).toBe(true);
|
|
expect(listMatchSummaries(9002).find((row) => row.matchId === matchId)?.joined).toBe(false);
|
|
});
|
|
|
|
it("fills seats up to the cap and rejects an extra player", () => {
|
|
const matchId = createMatch(9101, "Host");
|
|
for (let seat = 1; seat < MAX_SEATS; seat += 1) joinMatch(matchId, 9101 + seat, `P${seat}`);
|
|
expect(() => joinMatch(matchId, 9999, "Overflow")).toThrow("full");
|
|
});
|
|
|
|
it("stops a user seating at two matches at once", () => {
|
|
createMatch(9201, "Host");
|
|
const second = createMatch(9202, "Other");
|
|
expect(() => joinMatch(second, 9201, "Host")).toThrow("already in another match");
|
|
});
|
|
|
|
it("lets a non-seated user read a spectator snapshot with no seat", () => {
|
|
const matchId = createMatch(9301, "Host");
|
|
const view = getSnapshotFor(matchId, 9302);
|
|
expect(view.yourSeat).toBeNull();
|
|
expect(view.players[0].name).toBe("Host");
|
|
});
|
|
});
|
|
|
|
describe("bomperator registry: start gating", () => {
|
|
it("refuses to start below the minimum and starts at the minimum", () => {
|
|
const matchId = createMatch(9401, "Host");
|
|
expect(() => startMatch(matchId, 9401)).toThrow(`at least ${MIN_TO_START}`);
|
|
joinMatch(matchId, 9402, "Guest");
|
|
const view = startMatch(matchId, 9401);
|
|
expect(view.phase).toBe("countdown");
|
|
});
|
|
|
|
it("rejects starting twice", () => {
|
|
const matchId = createMatch(9501, "Host");
|
|
joinMatch(matchId, 9502, "Guest");
|
|
startMatch(matchId, 9501);
|
|
expect(() => startMatch(matchId, 9501)).toThrow("already started");
|
|
});
|
|
});
|
|
|
|
describe("bomperator registry: input + ticking", () => {
|
|
it("applies a queued movement input over subsequent ticks", () => {
|
|
const matchId = createMatch(9601, "Host");
|
|
joinMatch(matchId, 9602, "Guest");
|
|
startMatch(matchId, 9601);
|
|
toBattle(matchId);
|
|
|
|
const before = getSnapshotFor(matchId, 9601);
|
|
expect(before.phase).toBe("battle");
|
|
expect(before.players[before.yourSeat!].x).toBeCloseTo(1, 3);
|
|
|
|
submitInput(matchId, 9601, { dir: "right" });
|
|
advanceForTests(matchId, 6);
|
|
const after = getSnapshotFor(matchId, 9601);
|
|
expect(after.players[after.yourSeat!].x).toBeGreaterThan(1.5);
|
|
});
|
|
|
|
it("rejects inputs from a non-seated user", () => {
|
|
const matchId = createMatch(9701, "Host");
|
|
joinMatch(matchId, 9702, "Guest");
|
|
startMatch(matchId, 9701);
|
|
expect(() => submitInput(matchId, 9799, { dir: "left" })).toThrow("not in this match");
|
|
});
|
|
});
|
|
|
|
describe("bomperator registry: input sequencing", () => {
|
|
it("applies only the newest seq and ignores stale out-of-order posts", () => {
|
|
const matchId = createMatch(9751, "Host");
|
|
joinMatch(matchId, 9752, "Guest");
|
|
startMatch(matchId, 9751);
|
|
toBattle(matchId);
|
|
|
|
submitInput(matchId, 9751, { dir: "right", seq: 1 });
|
|
advanceForTests(matchId, 6);
|
|
const right = getSnapshotFor(matchId, 9751);
|
|
const rightX = right.players[right.yourSeat!].x;
|
|
expect(rightX).toBeGreaterThan(1.5);
|
|
|
|
// A stale echo of an older intent must never resurrect it.
|
|
submitInput(matchId, 9751, { dir: "left", seq: 3 });
|
|
submitInput(matchId, 9751, { dir: "right", seq: 2 });
|
|
advanceForTests(matchId, 6);
|
|
const after = getSnapshotFor(matchId, 9751);
|
|
expect(after.players[after.yourSeat!].x).toBeLessThan(rightX);
|
|
});
|
|
|
|
it("echoes each seat's last applied input seq in the snapshot", () => {
|
|
const matchId = createMatch(9761, "Host");
|
|
joinMatch(matchId, 9762, "Guest");
|
|
startMatch(matchId, 9761);
|
|
toBattle(matchId);
|
|
|
|
expect(getSnapshotFor(matchId, 9761).players[0].lastInputSeq).toBe(0);
|
|
submitInput(matchId, 9761, { dir: "down", seq: 5 });
|
|
submitInput(matchId, 9761, { dir: "up", seq: 4 }); // stale: ignored
|
|
const view = getSnapshotFor(matchId, 9761);
|
|
expect(view.players[0].lastInputSeq).toBe(5);
|
|
expect(view.players[1].lastInputSeq).toBe(0);
|
|
});
|
|
});
|
|
|
|
describe("bomperator registry: disconnect and dissolve", () => {
|
|
it("holds a seat on leave and restores it on rejoin", () => {
|
|
const matchId = createMatch(9801, "Host");
|
|
joinMatch(matchId, 9802, "Guest");
|
|
startMatch(matchId, 9801);
|
|
toBattle(matchId);
|
|
|
|
leaveMatch(matchId, 9801);
|
|
expect(getSnapshotFor(matchId, 9802).players[0].connected).toBe(false);
|
|
|
|
joinMatch(matchId, 9801, "Host"); // rejoin within the window
|
|
expect(getSnapshotFor(matchId, 9802).players[0].connected).toBe(true);
|
|
});
|
|
|
|
it("dissolves the match once a held seat's reconnect window lapses", () => {
|
|
const matchId = createMatch(9901, "Host");
|
|
joinMatch(matchId, 9902, "Guest");
|
|
startMatch(matchId, 9901);
|
|
toBattle(matchId);
|
|
|
|
leaveMatch(matchId, 9901); // host walks away
|
|
// Advance with a clock past the reconnect window: the seat expires and the
|
|
// match drops below two active technicians.
|
|
advanceForTests(matchId, 1, Date.now() + RECONNECT_WINDOW_MS + 5_000);
|
|
const view = getSnapshotFor(matchId, 9902);
|
|
expect(view.phase).toBe("complete");
|
|
expect(view.endReason).toBe("dissolved");
|
|
});
|
|
});
|
|
|
|
describe("bomperator registry: exit paths", () => {
|
|
it("ends the match as soon as the last connected technician leaves", () => {
|
|
const matchId = createMatch(9951, "Host");
|
|
joinMatch(matchId, 9952, "Guest");
|
|
startMatch(matchId, 9951);
|
|
toBattle(matchId);
|
|
|
|
leaveMatch(matchId, 9951); // host walks; guest still connected -> alive
|
|
expect(() => getSnapshotFor(matchId, 9952)).not.toThrow();
|
|
|
|
leaveMatch(matchId, 9952); // last connected leaves -> dissolve + dispose now
|
|
expect(() => getSnapshotFor(matchId, 9952)).toThrow("Match not found.");
|
|
});
|
|
|
|
it("lets a seated technician end the drill, but not a stranger", () => {
|
|
const matchId = createMatch(9961, "Host");
|
|
joinMatch(matchId, 9962, "Guest");
|
|
startMatch(matchId, 9961);
|
|
toBattle(matchId);
|
|
|
|
expect(() => endMatch(matchId, 9999)).toThrow("Only a technician");
|
|
endMatch(matchId, 9962); // guest can end it
|
|
expect(() => getSnapshotFor(matchId, 9961)).toThrow("Match not found.");
|
|
});
|
|
});
|
|
|
|
describe("bomperator registry: disposal", () => {
|
|
it("force-expiring removes the match", () => {
|
|
const matchId = createMatch(9911, "Host");
|
|
forceExpireMatch(matchId);
|
|
expect(() => getSnapshotFor(matchId, 9911)).toThrow("Match not found.");
|
|
});
|
|
|
|
it("clearing for tests isolates subsequent specs", () => {
|
|
createMatch(9921, "Host");
|
|
clearMatchesForTests();
|
|
expect(listMatchSummaries()).toHaveLength(0);
|
|
});
|
|
});
|
|
|
|
describe("bomperator: stat math", () => {
|
|
it("reads defaults and accumulates a finished match", () => {
|
|
expect(readBomperatorStats({})).toEqual({
|
|
matchesPlayed: 0,
|
|
matchWins: 0,
|
|
roundsWon: 0,
|
|
kills: 0,
|
|
xpEarned: 0,
|
|
});
|
|
|
|
const win = computeBomperatorStatsDelta(readBomperatorStats({}), {
|
|
userId: 1,
|
|
won: true,
|
|
kills: 3,
|
|
roundsWon: 2,
|
|
});
|
|
expect(win).toEqual({
|
|
matchesPlayed: 1,
|
|
matchWins: 1,
|
|
roundsWon: 2,
|
|
kills: 3,
|
|
xpEarned: xpForBomperator(true, 3),
|
|
});
|
|
|
|
const loss = computeBomperatorStatsDelta(win, {
|
|
userId: 1,
|
|
won: false,
|
|
kills: 1,
|
|
roundsWon: 0,
|
|
});
|
|
expect(loss.matchesPlayed).toBe(2);
|
|
expect(loss.matchWins).toBe(1);
|
|
expect(loss.roundsWon).toBe(2);
|
|
expect(loss.kills).toBe(4);
|
|
});
|
|
|
|
it("scores XP as a base plus a per-kill bounty", () => {
|
|
expect(xpForBomperator(false, 0)).toBeLessThan(xpForBomperator(true, 0));
|
|
expect(xpForBomperator(true, 2) - xpForBomperator(true, 1)).toBe(
|
|
xpForBomperator(false, 1) - xpForBomperator(false, 0),
|
|
);
|
|
});
|
|
});
|
|
|
|
describe("bomperator: awards write to the profile (DB round-trip)", () => {
|
|
let payload: Payload;
|
|
const createdUserIds: number[] = [];
|
|
|
|
beforeAll(async () => {
|
|
payload = await getTestPayload();
|
|
}, 30_000);
|
|
|
|
afterAll(async () => {
|
|
// Order matters: event logs reference the user (actor FK), profiles too.
|
|
for (const userId of createdUserIds) {
|
|
const events = await payload.find({
|
|
collection: "game-event-logs",
|
|
where: { actor: { equals: userId } },
|
|
limit: 200,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
for (const e of events.docs) {
|
|
await payload.delete({ collection: "game-event-logs", id: e.id, overrideAccess: true });
|
|
}
|
|
const profiles = await payload.find({
|
|
collection: "profiles",
|
|
where: { user: { equals: userId } },
|
|
limit: 50,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
for (const p of profiles.docs) {
|
|
await payload.delete({ collection: "profiles", id: p.id, overrideAccess: true });
|
|
}
|
|
await payload.delete({ collection: "users", id: userId, overrideAccess: true });
|
|
}
|
|
});
|
|
|
|
it("persists stats and derives chips from XP", async () => {
|
|
const username = `bomp_${Date.now().toString(36)}_${Math.floor(Math.random() * 1e6)}`;
|
|
const user = (await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username,
|
|
discordUsername: username,
|
|
displayName: `Bomp ${username}`,
|
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
|
password: "Test123",
|
|
roles: ["user"],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as { id: number };
|
|
createdUserIds.push(user.id);
|
|
|
|
const result = await awardBomperatorResult(payload, "match-abc12345", [
|
|
{ userId: user.id, won: true, kills: 2, roundsWon: 1 },
|
|
]);
|
|
|
|
const profileRes = await payload.find({
|
|
collection: "profiles",
|
|
where: { user: { equals: user.id } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const group = profileRes.docs[0]?.progression?.minigames?.bomperator;
|
|
expect(group).toMatchObject({
|
|
matchesPlayed: 1,
|
|
matchWins: 1,
|
|
roundsWon: 1,
|
|
kills: 2,
|
|
xpEarned: xpForBomperator(true, 2),
|
|
});
|
|
// Chips are auto-derived at 10 per XP, so the bank must have grown.
|
|
expect((profileRes.docs[0]?.progression?.chipBank ?? 0)).toBeGreaterThan(0);
|
|
expect(result.xpByUser[user.id]).toBe(xpForBomperator(true, 2));
|
|
});
|
|
});
|
|
|