1
0
Fork 0
polaris-task-force/tests/int/minigame-entries.int.spec.ts
Z8MB1E 938da9bf86 test(vitest): isolate:false shared forks with per-pid template clones + memoized payload boot
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.
2026-10-21 12:54:30 -04:00

189 lines
5.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 { derivePeriodForInstant } from "@/lib/minigames/periods/derive";
const ANCHOR = "2026-10-12T00:00:00.000Z";
const RUN = `mg-${Date.now().toString(36)}`;
let payload: Payload;
let userId: number;
let originalRules: Record<string, unknown> | null = null;
const entryPeriodId = (entry: { period?: unknown }): number | null => {
const period = entry.period;
if (period == null) return null;
return typeof period === "object" ? (period as { id: number }).id : (period as number);
};
/** Wipe the minigame feature tables so this file never sees another file's rows. */
async function clearMinigameData(): Promise<void> {
for (const collection of [
"achievements",
"minigame-entries",
"minigame-periods",
"minigames",
] as const) {
await payload.delete({
collection,
where: { id: { greater_than: 0 } },
overrideAccess: true,
});
}
}
describe("Minigame entry recording + anchored periods", () => {
beforeAll(async () => {
payload = await getTestPayload();
// The period 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 },
overrideAccess: true,
});
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-player`,
discordUsername: `${RUN}-player`,
displayName: "MG PLAYER",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userId = user.id;
});
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,
},
overrideAccess: true,
})
.catch(() => undefined);
});
it("derives anchored period indexes, labels and pre-anchor nulls", () => {
const anchor = new Date(ANCHOR);
const period0 = derivePeriodForInstant(anchor, 14, new Date(ANCHOR));
expect(period0?.index).toBe(0);
expect(period0?.label).toBe("Oct 12 to Oct 25, 2026");
const period1 = derivePeriodForInstant(anchor, 14, new Date("2026-10-26T00:00:00.000Z"));
expect(period1?.index).toBe(1);
expect(period1?.label).toBe("Oct 26 to Nov 8, 2026");
expect(
derivePeriodForInstant(anchor, 14, new Date("2026-10-11T23:59:59.999Z")),
).toBeNull();
});
it("lazily creates the anchored period and links entries to it", async () => {
await recordMinigameEntry({
payload,
userId,
game: "flappy",
score: 7,
durationMs: 12_000,
now: new Date("2026-10-14T12:00:00.000Z"),
});
await recordMinigameEntry({
payload,
userId,
game: "eod",
score: 300,
durationMs: 45_000,
mode: "perimeter",
now: new Date("2026-10-15T08:00:00.000Z"),
});
const entries = await payload.find({
collection: "minigame-entries",
where: {
and: [
{ user: { equals: userId } },
{ game: { in: ["flappy", "eod"] } },
],
},
sort: "createdAt",
depth: 0,
overrideAccess: true,
});
expect(entries.docs.length).toBe(2);
const periodIds = new Set(entries.docs.map(entryPeriodId));
expect(periodIds.size).toBe(1);
const periodId = [...periodIds][0];
expect(periodId).toBeTruthy();
const period = await payload.findByID({
collection: "minigame-periods",
id: periodId as number,
depth: 0,
overrideAccess: true,
});
expect(period.label).toBe("Oct 12 to Oct 25, 2026");
expect(period.status).toBe("open");
});
it("records entries before the anchor with no period", async () => {
await recordMinigameEntry({
payload,
userId,
game: "opord",
score: 5,
durationMs: 30_000,
now: new Date("2026-10-01T00:00:00.000Z"),
});
const res = await payload.find({
collection: "minigame-entries",
where: {
and: [{ user: { equals: userId } }, { game: { equals: "opord" } }],
},
limit: 1,
depth: 0,
overrideAccess: true,
});
expect(res.docs.length).toBe(1);
expect(entryPeriodId(res.docs[0])).toBeNull();
});
it("never throws when recording fails", async () => {
// A non-existent user id violates the FK; the recorder must swallow it.
await expect(
recordMinigameEntry({
payload,
userId: 999_999_999,
game: "flappy",
score: 1,
durationMs: 1_000,
now: new Date("2026-10-14T12:00:00.000Z"),
}),
).resolves.toBeUndefined();
});
});