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.
175 lines
6.4 KiB
TypeScript
175 lines
6.4 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 {
|
|
completedMonthWindows,
|
|
completedYearWindows,
|
|
} from "@/lib/minigames/periods/calendar";
|
|
|
|
const ANCHOR = "2026-01-15T00:00:00.000Z";
|
|
const RUN = `mgc-${Date.now().toString(36)}`;
|
|
|
|
let payload: Payload;
|
|
let userA: number;
|
|
let userB: number;
|
|
let originalRules: Record<string, unknown> | null = null;
|
|
|
|
const at = (iso: string) => new Date(iso);
|
|
|
|
describe("Minigame month/year achievements", () => {
|
|
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: 5,
|
|
},
|
|
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");
|
|
|
|
// January window (anchor-relative, Jan 15 to Feb 1): A leads.
|
|
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 10, durationMs: 1_000, now: at("2026-01-20T12:00:00Z") });
|
|
await recordMinigameEntry({ payload, userId: userA, game: "eod", score: 5, durationMs: 1_000, now: at("2026-01-22T12:00:00Z") });
|
|
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score: 3, durationMs: 1_000, now: at("2026-01-25T12:00:00Z") });
|
|
// February window (Feb 1 to Mar 1): B leads.
|
|
await recordMinigameEntry({ payload, userId: userA, game: "flappy", score: 2, durationMs: 1_000, now: at("2026-02-03T12:00:00Z") });
|
|
await recordMinigameEntry({ payload, userId: userB, game: "flappy", score: 20, durationMs: 1_000, now: at("2026-02-05T12:00:00Z") });
|
|
});
|
|
|
|
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);
|
|
});
|
|
|
|
it("enumerates completed UTC calendar windows, partial first window included", () => {
|
|
const anchor = at(ANCHOR);
|
|
|
|
const months = completedMonthWindows(anchor, at("2026-03-05T00:00:00Z"));
|
|
expect(months.map((window) => window.label)).toEqual(["January 2026", "February 2026"]);
|
|
expect(months[0].windowStart.toISOString()).toBe("2026-01-15T00:00:00.000Z");
|
|
expect(months[1].windowStart.toISOString()).toBe("2026-02-01T00:00:00.000Z");
|
|
|
|
expect(completedMonthWindows(anchor, at("2026-01-20T00:00:00Z"))).toHaveLength(0);
|
|
expect(completedYearWindows(anchor, at("2026-12-31T00:00:00Z"))).toHaveLength(0);
|
|
const years = completedYearWindows(anchor, at("2027-01-02T00:00:00Z"));
|
|
expect(years.map((window) => window.label)).toEqual(["2026"]);
|
|
expect(years[0].windowStart.toISOString()).toBe("2026-01-15T00:00:00.000Z");
|
|
expect(years[0].windowEnd.toISOString()).toBe("2027-01-01T00:00:00.000Z");
|
|
});
|
|
|
|
it("crowns each completed month and is idempotent", async () => {
|
|
const first = await closeDuePeriods(payload, at("2026-03-05T00:00:00Z"));
|
|
const months = first.calendar.filter((entry) => entry.unit === "month");
|
|
expect(months.map((entry) => entry.label).sort()).toEqual(["February 2026", "January 2026"]);
|
|
|
|
const january = await monthChampion("2026-01-15T00:00:00.000Z");
|
|
const february = await monthChampion("2026-02-01T00:00:00.000Z");
|
|
expect(january?.user).toBe(userA);
|
|
expect(february?.user).toBe(userB);
|
|
|
|
const before = await achievementCount();
|
|
const second = await closeDuePeriods(payload, at("2026-03-05T00:00:00Z"));
|
|
expect(second.calendar).toHaveLength(0);
|
|
expect(second.closed).toHaveLength(0);
|
|
expect(await achievementCount()).toBe(before);
|
|
});
|
|
|
|
it("crowns the year once it closes", async () => {
|
|
const summary = await closeDuePeriods(payload, at("2027-01-02T00:00:00Z"));
|
|
const years = summary.calendar.filter((entry) => entry.unit === "year");
|
|
expect(years.map((entry) => entry.label)).toEqual(["2026"]);
|
|
|
|
const year = await yearChampion("2026-01-15T00:00:00.000Z");
|
|
expect(year?.user).toBe(userA);
|
|
expect(year?.window).toBe("year");
|
|
});
|
|
|
|
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 monthChampion(windowStart: string) {
|
|
return firstAchievement("player-of-month", windowStart);
|
|
}
|
|
|
|
async function yearChampion(windowStart: string) {
|
|
return firstAchievement("player-of-year", windowStart);
|
|
}
|
|
|
|
async function firstAchievement(type: string, windowStart: string) {
|
|
const res = await payload.find({
|
|
collection: "achievements",
|
|
where: { and: [{ type: { equals: type } }, { windowStart: { equals: windowStart } }] },
|
|
limit: 1,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
return res.docs[0];
|
|
}
|
|
|
|
async function achievementCount() {
|
|
const res = await payload.find({
|
|
collection: "achievements",
|
|
limit: 0,
|
|
depth: 0,
|
|
overrideAccess: true,
|
|
});
|
|
return res.totalDocs;
|
|
}
|
|
});
|