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.
264 lines
9.7 KiB
TypeScript
264 lines
9.7 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,
|
|
closePeriodById,
|
|
reopenPeriodById,
|
|
} from "@/lib/minigames/periods/lifecycle";
|
|
import { computePeriodAwards, type LedgerEntry } from "@/lib/minigames/periods/boards";
|
|
|
|
const ANCHOR = "2026-10-12T00:00:00.000Z";
|
|
const PERIOD_0_LABEL = "Oct 12 to Oct 25, 2026";
|
|
const RUN = `mgp-${Date.now().toString(36)}`;
|
|
|
|
const inPeriod0 = (day: number) => new Date(`2026-10-${String(day).padStart(2, "0")}T12:00:00.000Z`);
|
|
const AFTER_PERIOD_0 = new Date("2026-10-26T00:00:30.000Z");
|
|
|
|
let payload: Payload;
|
|
let userA: number;
|
|
let userB: number;
|
|
let originalRules: Record<string, unknown> | null = null;
|
|
|
|
const entry = (over: Partial<LedgerEntry>): LedgerEntry => ({
|
|
userId: 1,
|
|
game: "flappy",
|
|
score: 1,
|
|
durationMs: 1_000,
|
|
accuracy: null,
|
|
createdAtMs: 0,
|
|
...over,
|
|
});
|
|
|
|
describe("Minigame period close pipeline", () => {
|
|
beforeAll(async () => {
|
|
payload = await getTestPayload();
|
|
|
|
// The entries spec shares these tables and the same anchor; start clean so
|
|
// the two files are order-independent.
|
|
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) =>
|
|
(
|
|
(await payload.create({
|
|
collection: "users",
|
|
data: {
|
|
username: `${RUN}-${suffix}`,
|
|
discordUsername: `${RUN}-${suffix}`,
|
|
displayName: `MG ${suffix.toUpperCase()}`,
|
|
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
|
|
password: "Test123",
|
|
roles: ["user"],
|
|
},
|
|
overrideAccess: true,
|
|
depth: 0,
|
|
})) as unknown as User
|
|
).id;
|
|
|
|
userA = await createUser("a");
|
|
userB = await createUser("b");
|
|
});
|
|
|
|
afterAll(async () => {
|
|
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);
|
|
});
|
|
|
|
describe("pure award math", () => {
|
|
it("ranks boards, sums placement points and picks every period award", () => {
|
|
const entries: LedgerEntry[] = [
|
|
entry({ userId: 1, game: "flappy", score: 10, createdAtMs: 10 }),
|
|
entry({ userId: 2, game: "flappy", score: 3, createdAtMs: 20 }),
|
|
entry({ userId: 2, game: "flappy", score: 2, createdAtMs: 21 }),
|
|
entry({ userId: 2, game: "flappy", score: 1, createdAtMs: 22 }),
|
|
entry({ userId: 1, game: "radio", score: 5, accuracy: 0.9, createdAtMs: 30 }),
|
|
];
|
|
const awards = computePeriodAwards({
|
|
entries,
|
|
games: ["flappy", "radio"],
|
|
topN: 10,
|
|
precisionMinAttempts: 1,
|
|
previousPointsByUser: new Map([
|
|
[1, 50],
|
|
[2, 0],
|
|
]),
|
|
});
|
|
const byType = Object.fromEntries(awards.map((award) => [award.type, award]));
|
|
// Flappy: user1 rank1 (10 pts), user2 rank2 (9 pts). Radio: user1 rank1 (10 pts).
|
|
expect(byType["period-champion"].userId).toBe(1);
|
|
expect(byType["period-champion"].value).toBe(20);
|
|
expect(byType.diligence.userId).toBe(2); // 3 attempts vs 2
|
|
expect(byType.precision.userId).toBe(1);
|
|
expect(Number(byType.precision.value)).toBeCloseTo(0.9, 4);
|
|
// user2 gained points over the previous period (0 -> 9).
|
|
expect(byType["most-improved"].userId).toBe(2);
|
|
expect(byType["most-improved"].value).toBe(9);
|
|
});
|
|
|
|
it("skips most-improved when there is no previous period", () => {
|
|
const awards = computePeriodAwards({
|
|
entries: [entry({ userId: 1, game: "flappy", score: 1 })],
|
|
games: ["flappy"],
|
|
topN: 10,
|
|
precisionMinAttempts: 1,
|
|
previousPointsByUser: null,
|
|
});
|
|
expect(awards.some((award) => award.type === "most-improved")).toBe(false);
|
|
});
|
|
|
|
it("gives ladder points only down to topN", () => {
|
|
const entries: LedgerEntry[] = Array.from({ length: 12 }, (_, i) =>
|
|
entry({ userId: i + 1, game: "flappy", score: 100 - i }),
|
|
);
|
|
const awards = computePeriodAwards({
|
|
entries,
|
|
games: ["flappy"],
|
|
topN: 3,
|
|
precisionMinAttempts: 10,
|
|
previousPointsByUser: null,
|
|
});
|
|
// Only the top three earn points; user 4+ get zero, and the champion is
|
|
// the top scorer, not the deepest roster.
|
|
expect(awards.find((award) => award.type === "period-champion")?.value).toBe(3);
|
|
});
|
|
});
|
|
|
|
describe("close / reopen against the ledger", () => {
|
|
it("closes the due period and grants the four Period-1 awards", async () => {
|
|
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 10, durationMs: 1_000, now: inPeriod0(14) });
|
|
await recordMinigameEntry({ payload, userId: userA, game: "eod", score: 5, durationMs: 1_000, now: inPeriod0(14) });
|
|
await recordMinigameEntry({ payload, userId: userA, game: "radio", score: 5, durationMs: 1_000, accuracy: 0.9, now: inPeriod0(14) });
|
|
await recordMinigameEntry({ payload, userId: userA, game: "opord", score: 4, durationMs: 1_000, accuracy: 0.8, now: inPeriod0(15) });
|
|
await recordMinigameEntry({ payload, userId: userA, game: "qualification", score: 6, durationMs: 1_000, accuracy: 1, now: inPeriod0(15) });
|
|
|
|
for (const score of [3, 2, 2, 1, 1]) {
|
|
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score, durationMs: 10_000, now: inPeriod0(14) });
|
|
}
|
|
await recordMinigameEntry({ payload, userId: userB, game: "eod", score: 9, durationMs: 10_000, now: inPeriod0(14) });
|
|
|
|
// A later period exists but must stay untouched.
|
|
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 1, durationMs: 1_000, now: new Date("2026-10-27T12:00:00.000Z") });
|
|
|
|
const summary = await closeDuePeriods(payload, AFTER_PERIOD_0);
|
|
expect(summary.closed.length).toBe(1);
|
|
expect(summary.closed[0].label).toBe(PERIOD_0_LABEL);
|
|
expect(summary.closed[0].achievements).toBe(4);
|
|
expect(summary.createdPeriodId).toBeTruthy();
|
|
|
|
const period0 = await findPeriodByLabel(PERIOD_0_LABEL);
|
|
expect(period0.status).toBe("closed");
|
|
expect(period0.closedAt).toBeTruthy();
|
|
|
|
const awards = await periodAwards(period0.startDate);
|
|
const types = awards.map((row) => row.type).sort();
|
|
expect(types).toEqual(["dedication", "diligence", "period-champion", "precision"]);
|
|
expect(awards.find((row) => row.type === "period-champion")?.user).toBe(userA);
|
|
expect(awards.find((row) => row.type === "diligence")?.user).toBe(userB);
|
|
expect(awards.find((row) => row.type === "dedication")?.user).toBe(userB);
|
|
expect(awards.find((row) => row.type === "precision")?.user).toBe(userA);
|
|
});
|
|
|
|
it("is idempotent: a second sweep grants nothing new", async () => {
|
|
const period0 = await findPeriodByLabel(PERIOD_0_LABEL);
|
|
const before = (await periodAwards(period0.startDate)).length;
|
|
|
|
const summary = await closeDuePeriods(payload, AFTER_PERIOD_0);
|
|
expect(summary.closed.length).toBe(0);
|
|
expect((await periodAwards(period0.startDate)).length).toBe(before);
|
|
});
|
|
|
|
it("reopens a period, removing its awards, then re-grants on close", async () => {
|
|
const period0 = await findPeriodByLabel(PERIOD_0_LABEL);
|
|
|
|
const reopened = await reopenPeriodById(payload, period0.id);
|
|
expect(reopened?.periodId).toBe(period0.id);
|
|
expect((await periodAwards(period0.startDate)).length).toBe(0);
|
|
const afterReopen = await payload.findByID({
|
|
collection: "minigame-periods",
|
|
id: period0.id,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
expect(afterReopen.status).toBe("open");
|
|
expect(afterReopen.closedAt).toBeFalsy();
|
|
|
|
const reclosed = await closePeriodById(payload, period0.id, AFTER_PERIOD_0);
|
|
expect(reclosed?.achievements).toBe(4);
|
|
expect((await periodAwards(period0.startDate)).length).toBe(4);
|
|
});
|
|
});
|
|
|
|
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,
|
|
});
|
|
}
|
|
}
|
|
|
|
async function findPeriodByLabel(label: string) {
|
|
const res = await payload.find({
|
|
collection: "minigame-periods",
|
|
where: { label: { equals: label } },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
const doc = res.docs[0];
|
|
expect(doc).toBeTruthy();
|
|
return doc;
|
|
}
|
|
|
|
async function periodAwards(windowStart: string) {
|
|
const res = await payload.find({
|
|
collection: "achievements",
|
|
where: {
|
|
and: [{ window: { equals: "period" } }, { windowStart: { equals: windowStart } }],
|
|
},
|
|
limit: 50,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
return res.docs;
|
|
}
|
|
});
|