import { NextRequest } from "next/server"; import { beforeEach, describe, expect, it, vi } from "vitest"; const isDatabaseConfiguredMock = vi.fn(); const getOpsPruneTokenMock = vi.fn(); const getRuleAdminEmailsMock = vi.fn(); const getSessionUserMock = vi.fn(); const isRuleAdminEmailMock = vi.fn(); const findManyMock = vi.fn(); vi.mock("../../lib/server/env", () => ({ isDatabaseConfigured: () => isDatabaseConfiguredMock(), getOpsPruneToken: () => getOpsPruneTokenMock(), getRuleAdminEmails: () => getRuleAdminEmailsMock(), })); vi.mock("../../lib/server/db", () => ({ prisma: { publishedRule: { findMany: (...args: unknown[]) => findManyMock(...args), }, }, })); vi.mock("../../lib/server/session", () => ({ getSessionUser: () => getSessionUserMock(), })); vi.mock("../../lib/server/ruleAdmins", () => ({ isRuleAdminEmail: (...args: unknown[]) => isRuleAdminEmailMock(...args), })); import { GET } from "../../app/api/ops/rule-counts/route"; function get(auth?: string) { return new NextRequest("https://x.test/api/ops/rule-counts", { headers: auth ? { authorization: auth } : undefined, }); } beforeEach(() => { isDatabaseConfiguredMock.mockReset(); getOpsPruneTokenMock.mockReset(); getRuleAdminEmailsMock.mockReset(); getSessionUserMock.mockReset(); isRuleAdminEmailMock.mockReset(); findManyMock.mockReset(); isDatabaseConfiguredMock.mockReturnValue(true); getOpsPruneTokenMock.mockReturnValue("secret"); getRuleAdminEmailsMock.mockReturnValue(["ops@example.org"]); getSessionUserMock.mockResolvedValue(null); isRuleAdminEmailMock.mockReturnValue(false); findManyMock.mockResolvedValue([ { orgType: "mutualAid", communityLocation: "Boulder" }, { orgType: "mutualAid", communityLocation: "Boulder" }, { orgType: "mutualAid", communityLocation: "Boulder" }, { orgType: "mutualAid", communityLocation: "Boulder" }, { orgType: "mutualAid", communityLocation: "Boulder" }, ]); }); describe("GET /api/ops/rule-counts", () => { it("returns 404 when neither admins nor an ops token are configured", async () => { getRuleAdminEmailsMock.mockReturnValue([]); getOpsPruneTokenMock.mockReturnValue(null); const res = await GET(get("Bearer secret"), undefined); expect(res.status).toBe(404); expect(findManyMock).not.toHaveBeenCalled(); }); it("returns folded counts for a matching bearer token", async () => { const res = await GET(get("Bearer secret"), undefined); expect(res.status).toBe(200); const body = (await res.json()) as { finished: number; cells: Array<{ folded: boolean; count: number }>; }; expect(body.finished).toBe(5); expect(body.cells[0]).toMatchObject({ folded: false, count: 5 }); }); it("returns 401 when the session is not a named admin", async () => { const res = await GET(get(), undefined); expect(res.status).toBe(401); expect(findManyMock).not.toHaveBeenCalled(); }); });