527 lines · 18.7 KB
import { beforeEach, describe, expect, mock, test } from "bun:test";
import { Database } from "bun:sqlite";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import type { ReporterKind } from "./abuse";

const published: string[] = [];
mock.module("cloudflare:workers", () => ({
  waitUntil: () => undefined,
  env: {
    PUBLIC_URL: "https://forge.example.com",
    SITES_DOMAIN: "sites.example.net",
    SECRETS_KEY: "test-secret",
    ABUSE_FORWARD_TO: "",
    KV: { put: async (key: string) => void published.push(key) },
  },
}));

const db = new Database(":memory:");
const migrations = join(import.meta.dir, "../../migrations");
for (const file of readdirSync(migrations).sort())
  db.exec(readFileSync(join(migrations, file), "utf8"));

mock.module("./db", () => ({
  first: async (sql: string, ...params: unknown[]) =>
    db.query(sql).get(...(params as never[])) ?? null,
  all: async (sql: string, ...params: unknown[]) =>
    db.query(sql).all(...(params as never[])),
  run: async (sql: string, ...params: unknown[]) => ({
    meta: { changes: db.query(sql).run(...(params as never[])).changes },
  }),
  stmt: (sql: string, ...params: unknown[]) => ({ sql, params }),
}));
// Every repo and account object shares the one test database (it still has every table), so seeds stay in one place.
const scoped = {
  first: async (sql: string, ...params: unknown[]) =>
    db.query(sql).get(...(params as never[])) ?? null,
  all: async (sql: string, ...params: unknown[]) =>
    db.query(sql).all(...(params as never[])),
  run: async (sql: string, ...params: unknown[]) => ({