139 lines · 5.9 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";

const published: string[] = [];
mock.module("cloudflare:workers", () => ({
  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 },
  }),
}));
mock.module("./sites/deploy", () => ({
  loadSiteById: async (id: string) => db.query("SELECT * FROM sites WHERE id = ?").get(id) ?? null,
}));

const { actOnAbuseReport, guessAbuseCategory, recordAbuseReport, restoreSite, siteIdForUrl } = await import("./abuse");

function site(id: string, label: string, scratch: number, disabled: string | null = null) {
  db.query(
    `INSERT INTO sites (id, owner_id, label, source, scratch, disabled_reason, created_at, updated_at)
     VALUES (?, 'owner', ?, 'upload', ?, ?, 0, 0)`,
  ).run(id, label, scratch, disabled);
}