115 lines · 4.6 KB
import { beforeEach, describe, expect, mock, test } from "bun:test";
import { fakeD1 } from "../metering/fake-d1.test-helper";
import { scopedTestState } from "./scoped.test-helper";

let d1 = fakeD1();
const scoped = scopedTestState();
scoped.install();
const SCOPE: Record<string, string> = { s1: "r1", s2: "site:s2" };
function addUsage(site: string, day: string, account: string | null, requests: number, cpu: number): void {
  scoped
    .repo(SCOPE[site] ?? site)
    .query("INSERT INTO site_usage (site_id, day, account_id, requests, cpu_ms, bytes_out) VALUES (?, ?, ?, ?, ?, 0)")
    .run(site, day, account, requests, cpu);
}
const kv = new Map<string, string>();
const notified: { title: string; recipients: (string | null | undefined)[] }[] = [];
const fakeEnv: Record<string, unknown> = {
  get DB() {
    return d1.binding;
  },
  KV: {
    get: async (key: string) => kv.get(key) ?? null,
    put: async (key: string, value: string) => void kv.set(key, value),
    delete: async (key: string) => void kv.delete(key),
  },
  METERING_PLANS: "",
  PUBLIC_URL: "https://forge.test",
  SITES_DAILY_CPU_MS_LIMIT: "0",
  SITES_DAILY_REQUEST_LIMIT: "0",
};
mock.module("cloudflare:workers", () => ({ env: fakeEnv, waitUntil: () => undefined }));
mock.module("../notify/deliver", () => ({
  notifyUsers: async (input: { title: string; recipients: (string | null | undefined)[] }) => void notified.push(input),
}));

const platformSites = new Map<string, [number, number, number]>();
const actualCounters = await import("../counters");
mock.module("../counters", () => ({
  ...actualCounters,
  counterTotals: async (kind: string, _scope: string, key: string) =>