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

170 lines
5.8 KiB
TypeScript

/**
* Contribution moderation actions: a moderator can grant manual XP and revoke a
* grant with a reason (the reason is stored and shown to the earner), and both
* are gated on `contribution-entries:moderate`.
*/
import { getTestPayload } from "../helpers/get-test-payload";
import { type Payload } from "payload";
import { afterAll, beforeAll, describe, expect, it, vi, type MockInstance } from "vitest";
import type { Role, User } from "@/payload-types";
import type { Permission } from "@/permissions";
import {
grantManualContribution,
revokeContribution,
} from "@/app/(frontend)/contributions/actions";
vi.mock("next/headers", () => ({ headers: async () => new Headers() }));
vi.mock("next/cache", () => ({ revalidatePath: () => {} }));
const RUN = `cmod-${Date.now().toString(36)}`;
const TIMEOUT = 30_000;
let payload: Payload;
let authSpy: MockInstance;
describe("Contribution moderation actions", () => {
const roleIds: number[] = [];
const userIds: number[] = [];
let moderator: User;
let plain: User;
let target: User;
const makeRole = async (label: string, permissions: Permission[]): Promise<Role> => {
const role = (await payload.create({
collection: "roles",
data: { name: `${RUN}-${label}`, slug: `${RUN}-${label}`, permissions },
overrideAccess: true,
depth: 0,
})) as unknown as Role;
roleIds.push(role.id);
return role;
};
const makeUser = async (label: string, roleId: number): Promise<User> => {
const user = (await payload.create({
collection: "users",
data: {
username: `${RUN}-${label}`,
discordUsername: `${RUN}-${label}`,
displayName: label.toUpperCase(),
steamId: `7656119${Math.floor(Math.random() * 1e9)}`,
password: "Test123",
roleDocs: [roleId],
},
overrideAccess: true,
depth: 0,
})) as unknown as User;
userIds.push(user.id);
return user;
};
const bucketFor = async (userId: number): Promise<number> => {
const res = await payload.find({
collection: "profiles",
where: { user: { equals: userId } },
limit: 1,
depth: 0,
overrideAccess: true,
select: { progression: { contributions: { xpEarned: true } } },
});
return res.docs[0]?.progression?.contributions?.xpEarned ?? 0;
};
beforeAll(async () => {
payload = await getTestPayload();
const modRole = await makeRole("mod", ["contribution-entries:moderate"]);
const plainRole = await makeRole("plain", []);
moderator = await makeUser("mod", modRole.id);
plain = await makeUser("plain", plainRole.id);
target = await makeUser("target", plainRole.id);
authSpy = vi.spyOn(payload, "auth");
}, TIMEOUT);
afterAll(async () => {
authSpy?.mockRestore();
for (const id of userIds) {
await payload
.delete({
collection: "contribution-entries",
where: { user: { equals: id } },
overrideAccess: true,
})
.catch(() => {});
const profiles = await payload
.find({ collection: "profiles", where: { user: { equals: id } }, 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, overrideAccess: true }).catch(() => {});
}
for (const id of roleIds) {
await payload.delete({ collection: "roles", id, overrideAccess: true }).catch(() => {});
}
}, TIMEOUT);
it("lets a moderator grant manual XP", async () => {
authSpy.mockResolvedValue({ user: moderator });
const before = await bucketFor(target.id);
const res = await grantManualContribution({
userId: target.id,
points: 12,
summary: "Helped organize the unit event",
});
expect(res.success).toBe(true);
expect(await bucketFor(target.id)).toBe(before + 12);
});
it("requires a reason to grant", async () => {
authSpy.mockResolvedValue({ user: moderator });
const res = await grantManualContribution({ userId: target.id, points: 5, summary: "x" });
expect(res.success).toBe(false);
});
it("blocks a non-moderator from granting", async () => {
authSpy.mockResolvedValue({ user: plain });
const res = await grantManualContribution({ userId: target.id, points: 5, summary: "nope" });
expect(res.success).toBe(false);
expect(res.error).toMatch(/not allowed/i);
});
it("revokes a grant with a reason and pulls the XP back", async () => {
authSpy.mockResolvedValue({ user: moderator });
const grant = await grantManualContribution({
userId: target.id,
points: 8,
summary: "To be revoked",
});
expect(grant.success).toBe(true);
const entryId = grant.data!.entryId;
const before = await bucketFor(target.id);
const res = await revokeContribution({ entryId, reason: "Spam entry" });
expect(res.success).toBe(true);
expect(await bucketFor(target.id)).toBe(before - 8);
const entry = await payload.findByID({
collection: "contribution-entries",
id: entryId,
depth: 0,
overrideAccess: true,
});
expect(entry.status).toBe("revoked");
expect(entry.revokedReason).toBe("Spam entry");
});
it("requires a reason to revoke", async () => {
authSpy.mockResolvedValue({ user: moderator });
const res = await revokeContribution({ entryId: 1, reason: "" });
expect(res.success).toBe(false);
expect(res.error).toMatch(/reason/i);
});
it("blocks a non-moderator from revoking", async () => {
authSpy.mockResolvedValue({ user: plain });
const res = await revokeContribution({ entryId: 1, reason: "trying" });
expect(res.success).toBe(false);
expect(res.error).toMatch(/not allowed/i);
});
});