import { beforeEach, describe, expect, mock, test } from "bun:test"; mock.module("cloudflare:workers", () => ({ env: {}, waitUntil: () => undefined })); let reads = 0; let row: { disabled_at: number | null; disabled_reason: string | null } | null = null; let failing = false; mock.module("./db", () => ({ first: async () => { reads++; if (failing) throw new Error("D1 down"); return row; }, run: async () => ({ meta: { changes: 0 } }), all: async () => [], batch: async () => [], stmt: () => ({}), chunks: (items: T[]) => [items], placeholders: (count: number) => Array(count).fill("?").join(", "), MAX_IN_LIST: 90, })); const { avatarTakenDown } = await import("./avatars"); let next = 0; beforeEach(() => { reads = 0; failing = false; row = { disabled_at: null, disabled_reason: null }; }); describe("avatarTakenDown", () => { test("reads D1 once per account per minute", async () => { const key = `acct${next++}-abc`; expect(await avatarTakenDown(key)).toBe(false); expect(await avatarTakenDown(key)).toBe(false); expect(await avatarTakenDown(`${key.split("-")[0]}-other`)).toBe(false); expect(reads).toBe(1); }); test("a taken-down account is refused", async () => { row = { disabled_at: 5, disabled_reason: "admin" }; expect(await avatarTakenDown(`acct${next++}-abc`)).toBe(true); }); test("fails closed, uncached, when the lookup fails", async () => { const key = `acct${next++}-abc`; failing = true; expect(await avatarTakenDown(key)).toBe(true); failing = false; expect(await avatarTakenDown(key)).toBe(false); expect(reads).toBe(2); }); }); describe("avatar keys without an account prefix", () => { test("are refused without a lookup", async () => { reads = 0; expect(await avatarTakenDown("nodash")).toBe(true); expect(await avatarTakenDown("-abc")).toBe(true); expect(reads).toBe(0); }); });