1
0
Fork 0
polaris-task-force/tests/int/bomperator-registry.int.spec.ts
Z8MB1E ad512bde11 test(minigames): cover bomperator input seq guard and snapshot echo
Two registry specs: stale/out-of-order seq posts are ignored while the newest
intent wins, and each seat's last applied seq is echoed in the snapshot.
2026-10-16 01:41:41 -04:00

345 lines
11 KiB
TypeScript

import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { getPayload, type Payload } from "payload";
import config from "@payload-config";
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 getPayload({ config });
}, 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));
});
});