1
0
Fork 0
polaris-task-force/tests/int/roll-call-force.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

236 lines
8.1 KiB
TypeScript

import { getTestPayload } from "../helpers/get-test-payload";
import { Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import type { Campaign, Map as MissionMap, Mission, User } from "@/payload-types";
import {
getNextUpcomingScheduledMission,
resolveMissionByRef,
validateRollCallTarget,
} from "@/lib/intelligence/rollCall";
let payload: Payload;
const RUN = `rc-${Date.now().toString(36)}`;
describe("Forced roll-call target helpers", () => {
let mapId: number;
let campaignId: number;
let authorId: number;
const missionIds: number[] = [];
beforeAll(async () => {
payload = await getTestPayload();
const map = (await payload.create({
collection: "maps",
data: { name: `${RUN} Map`, worldSizeWidth: 8192, worldSizeHeight: 8192, basemapMode: "image" },
overrideAccess: true,
depth: 0,
})) as unknown as MissionMap;
mapId = map.id;
const campaign = (await payload.create({
collection: "campaigns",
data: { name: `${RUN} Campaign`, summary: "Roll-call force test campaign", status: "concept", campaignMode: "custom" },
overrideAccess: true,
depth: 0,
})) as unknown as Campaign;
campaignId = campaign.id;
const author = (await payload.create({
collection: "users",
data: {
username: `${RUN}-author`,
discordUsername: `${RUN}-author`,
displayName: "RC AUTHOR",
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roles: ["user"],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
authorId = author.id;
});
afterAll(async () => {
for (const id of missionIds) {
await payload.delete({ collection: "missions", id, overrideAccess: true }).catch(() => {});
}
await payload
.delete({ collection: "campaigns", id: campaignId, overrideAccess: true })
.catch(() => {});
await payload.delete({ collection: "maps", id: mapId, overrideAccess: true }).catch(() => {});
// User deletion trips FK constraints unless the hook-provisioned
// personal bank account and profile are removed first.
const accounts = await payload
.find({
collection: "bank-accounts",
where: { ownerUser: { equals: authorId } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const account of accounts?.docs ?? []) {
await payload
.delete({ collection: "bank-accounts", id: account.id, overrideAccess: true })
.catch(() => {});
}
const profiles = await payload
.find({
collection: "profiles",
where: { user: { equals: authorId } },
limit: 5,
depth: 0,
overrideAccess: true,
})
.catch(() => null);
for (const profile of profiles?.docs ?? []) {
await payload
.delete({ collection: "profiles", id: profile.id, overrideAccess: true })
.catch(() => {});
}
await payload
.delete({ collection: "users", id: authorId, overrideAccess: true })
.catch(() => {});
});
const makeMission = async (
label: string,
overrides: {
name?: string;
status?: Mission["ownershipAndStatus"]["status"];
visibility?: Mission["ownershipAndStatus"]["visibility"];
start: Date;
},
): Promise<Mission> => {
const mission = (await payload.create({
collection: "missions",
data: {
name: overrides.name ?? `${RUN} ${label}`,
codeName: `${RUN}-${label}`,
summary: "Forced roll-call test mission",
operationType: "main",
classification: {
map: mapId,
missionType: "PvE",
campaign: campaignId,
startDateTime: overrides.start.toISOString(),
estimatedDuration: 60,
},
ownershipAndStatus: {
authors: [authorId],
status: overrides.status ?? "Scheduled",
visibility: overrides.visibility ?? "unit",
},
missionRoles: {
maxPlayers: 16,
},
gameDetails: {
serverDetails: {
serverIp: "127.0.0.1",
serverPort: 2302,
},
},
briefing: [],
},
overrideAccess: true,
depth: 0,
})) as unknown as Mission;
missionIds.push(mission.id);
return mission;
};
describe("getNextUpcomingScheduledMission", () => {
it("picks the soonest future Scheduled unit op and skips past, draft, and leadership ops", async () => {
const now = new Date();
await makeMission("far", { start: new Date(now.getTime() + 4 * 86_400_000) });
const soon = await makeMission("soon", { start: new Date(now.getTime() + 2 * 86_400_000) });
const past = await makeMission("past", { start: new Date(now.getTime() - 3_600_000) });
const draft = await makeMission("draft", {
status: "Ready",
start: new Date(now.getTime() + 600_000),
});
const leadership = await makeMission("leadership", {
visibility: "leadership",
start: new Date(now.getTime() + 600_000),
});
const next = await getNextUpcomingScheduledMission(payload, now);
expect(next).not.toBeNull();
// Other suites may leave missions in the shared test DB, so assert
// ordering/exclusion rather than exact identity: the pick must never be
// one of the excluded rows and must start no later than our soonest.
expect([past.id, draft.id, leadership.id]).not.toContain(next!.id);
expect(new Date(next!.classification.startDateTime).getTime()).toBeLessThanOrEqual(
new Date(soon.classification.startDateTime).getTime(),
);
});
});
describe("resolveMissionByRef", () => {
it("resolves by ID, name, and code name", async () => {
const now = new Date();
const mission = await makeMission("solo", { start: new Date(now.getTime() + 86_400_000) });
const byId = await resolveMissionByRef(payload, String(mission.id));
expect(byId.mission?.id).toBe(mission.id);
const byCodeName = await resolveMissionByRef(payload, `${RUN}-solo`);
expect(byCodeName.mission?.id).toBe(mission.id);
const byName = await resolveMissionByRef(payload, `${RUN} solo`);
expect(byName.mission?.id).toBe(mission.id);
});
it("reports no-match and ambiguity instead of guessing", async () => {
const now = new Date();
const twinStart = new Date(now.getTime() + 86_400_000);
await makeMission("twin-a", { name: `${RUN} twins`, start: twinStart });
await makeMission("twin-b", { name: `${RUN} twins`, start: twinStart });
const missing = await resolveMissionByRef(payload, `${RUN} definitely-not-here`);
expect(missing.mission).toBeUndefined();
expect(missing.error).toContain("No mission matches");
const ambiguous = await resolveMissionByRef(payload, `${RUN} twins`);
expect(ambiguous.mission).toBeUndefined();
expect(ambiguous.error).toContain("Multiple missions match");
});
});
describe("validateRollCallTarget", () => {
const base = (overrides: {
status?: Mission["ownershipAndStatus"]["status"];
visibility?: Mission["ownershipAndStatus"]["visibility"];
start?: Date;
}): Mission =>
({
id: 1,
name: "Validation Probe",
ownershipAndStatus: {
status: overrides.status ?? "Scheduled",
visibility: overrides.visibility ?? "unit",
},
classification: {
startDateTime: (overrides.start ?? new Date(Date.now() + 86_400_000)).toISOString(),
},
}) as unknown as Mission;
it("accepts a future Scheduled unit op", () => {
expect(validateRollCallTarget(base({}))).toBeNull();
});
it("rejects drafts, leadership visibility, and started ops with explanations", () => {
expect(validateRollCallTarget(base({ status: "Ready" }))).toContain("not Scheduled");
expect(validateRollCallTarget(base({ visibility: "leadership" }))).toContain(
"not unit-visible",
);
expect(
validateRollCallTarget(base({ start: new Date(Date.now() - 60_000) })),
).toContain("already started");
});
});
});