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.
185 lines
6.3 KiB
TypeScript
185 lines
6.3 KiB
TypeScript
import { getTestPayload } from "../helpers/get-test-payload";
|
|
import { Payload } from "payload";
|
|
|
|
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
|
import type { User } from "@/payload-types";
|
|
import { recordMinigameEntry } from "@/lib/minigames/periods/record";
|
|
import { closeDuePeriods } from "@/lib/minigames/periods/lifecycle";
|
|
import {
|
|
buildLeaderboardPayload,
|
|
recentAchievements,
|
|
} from "@/lib/minigames/periods/standings";
|
|
import { CORE_MINIGAME_KEYS } from "@/lib/minigames/registry";
|
|
|
|
const ANCHOR = "2026-09-07T00:00:00.000Z";
|
|
const RUN = `mgs-${Date.now().toString(36)}`;
|
|
|
|
let payload: Payload;
|
|
let userA: number;
|
|
let userB: number;
|
|
let originalRules: Record<string, unknown> | null = null;
|
|
|
|
describe("Minigame leaderboard read model", () => {
|
|
beforeAll(async () => {
|
|
payload = await getTestPayload();
|
|
await clearMinigameData();
|
|
|
|
originalRules = (await payload.findGlobal({
|
|
slug: "minigame-rules",
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
})) as unknown as Record<string, unknown> | null;
|
|
|
|
await payload.updateGlobal({
|
|
slug: "minigame-rules",
|
|
data: {
|
|
enabled: true,
|
|
anchorDate: ANCHOR,
|
|
periodLengthDays: 14,
|
|
placementLadderTopN: 10,
|
|
precisionMinAttempts: 1,
|
|
},
|
|
overrideAccess: true,
|
|
});
|
|
|
|
const createUser = async (suffix: string, displayName: string) =>
|
|
(
|
|
(await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-${suffix}`,
|
|
discordUsername: `${RUN}-${suffix}`,
|
|
displayName,
|
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
|
password: "Test123",
|
|
roles: ["user"],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as User
|
|
).id;
|
|
|
|
userA = await createUser("a", "Alpha Operator");
|
|
userB = await createUser("b", "Bravo Operator");
|
|
});
|
|
|
|
afterAll(async () => {
|
|
await clearMinigameData();
|
|
if (!originalRules) return;
|
|
await payload
|
|
.updateGlobal({
|
|
slug: "minigame-rules",
|
|
data: {
|
|
enabled: Boolean(originalRules.enabled),
|
|
anchorDate: originalRules.anchorDate as string,
|
|
periodLengthDays: (originalRules.periodLengthDays as number) ?? 14,
|
|
placementLadderTopN: (originalRules.placementLadderTopN as number) ?? 10,
|
|
precisionMinAttempts: (originalRules.precisionMinAttempts as number) ?? 5,
|
|
},
|
|
overrideAccess: true,
|
|
})
|
|
.catch(() => undefined);
|
|
});
|
|
|
|
it("builds period boards from the ledger with names and placement points", async () => {
|
|
const when = new Date("2026-09-08T12:00:00.000Z");
|
|
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 9, durationMs: 1_000, now: when });
|
|
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score: 4, durationMs: 1_000, now: when });
|
|
|
|
const periodRow = await payload.find({
|
|
collection: "minigame-periods",
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const periodId = periodRow.docs[0]?.id ?? null;
|
|
|
|
const payloadData = await buildLeaderboardPayload(payload, {
|
|
scope: "period",
|
|
periodId,
|
|
includeAchievements: true,
|
|
});
|
|
|
|
expect(payloadData.mode).toBe("period");
|
|
expect(payloadData.period?.label).toBe("Sep 7 to Sep 20, 2026");
|
|
expect(payloadData.boards).toHaveLength(CORE_MINIGAME_KEYS.length);
|
|
|
|
const flappy = payloadData.boards.find((board) => board.key === "flappy");
|
|
expect(flappy?.rows.map((row) => row.name)).toEqual(["Alpha Operator", "Bravo Operator"]);
|
|
expect(flappy?.rows[0].points).toBe(10);
|
|
expect(flappy?.rows[1].points).toBe(9);
|
|
expect(flappy?.rows[0].rank).toBe(1);
|
|
});
|
|
|
|
it("resolves the current period's boards when no periodId is given", async () => {
|
|
// Real-clock run: lands in the period covering `now` and lazily creates
|
|
// its period row, exactly like a production submission does. The default
|
|
// "current" scope must show it even though no periodId is passed.
|
|
await recordMinigameEntry({
|
|
payload,
|
|
userId: userA,
|
|
game: "flappy",
|
|
score: 28,
|
|
durationMs: 34_000,
|
|
});
|
|
|
|
const payloadData = await buildLeaderboardPayload(payload, { scope: "period" });
|
|
|
|
expect(payloadData.mode).toBe("period");
|
|
expect(payloadData.period).not.toBeNull();
|
|
expect(payloadData.period?.id).not.toBeNull();
|
|
const flappy = payloadData.boards.find((board) => board.key === "flappy");
|
|
const row = flappy?.rows.find((entry) => entry.name === "Alpha Operator");
|
|
expect(row?.bestScore).toBe(28);
|
|
expect(row?.attempts).toBe(1);
|
|
});
|
|
|
|
it("reads All-Time boards from the untouched profile aggregates", async () => {
|
|
const rankRes = await payload.find({
|
|
collection: "ranks",
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const rankId = rankRes.docs[0]?.id;
|
|
expect(rankId).toBeTruthy();
|
|
|
|
await payload.create({
|
|
collection: "profiles",
|
|
data: {
|
|
user: userA,
|
|
rank: rankId,
|
|
dossier: { enlistmentDate: new Date().toISOString() },
|
|
progression: { minigames: { flappyBird: { bestScore: 42, gamesPlayed: 7 } } },
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
});
|
|
|
|
const payloadData = await buildLeaderboardPayload(payload, { scope: "all-time" });
|
|
expect(payloadData.mode).toBe("all-time");
|
|
const flappy = payloadData.boards.find((board) => board.key === "flappy");
|
|
expect(flappy?.rows[0]?.name).toBe("Alpha Operator");
|
|
expect(flappy?.rows[0]?.bestScore).toBe(42);
|
|
expect(flappy?.rows[0]?.attempts).toBe(7);
|
|
});
|
|
|
|
it("surfaces achievements after a close", async () => {
|
|
await closeDuePeriods(payload, new Date("2026-09-21T00:00:00.000Z"));
|
|
const achievements = await recentAchievements(payload, 20);
|
|
const types = achievements.map((achievement) => achievement.type);
|
|
expect(types).toContain("period-champion");
|
|
expect(achievements.every((achievement) => achievement.userName.length > 0)).toBe(true);
|
|
});
|
|
|
|
async function clearMinigameData() {
|
|
for (const collection of [
|
|
"achievements",
|
|
"minigame-entries",
|
|
"minigame-periods",
|
|
"minigames",
|
|
] as const) {
|
|
await payload.delete({ collection, where: { id: { greater_than: 0 } }, overrideAccess: true });
|
|
}
|
|
}
|
|
});
|