71 lines · 4.1 KB
import { beforeEach, expect, mock, test } from "bun:test";
import { Database } from "bun:sqlite";
import { readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";

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"));

type Statement = { sql: string; params: unknown[] };
const exec = (sql: string, params: unknown[]) => db.query(sql).run(...(params as never[]));
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: exec(sql, params).changes } }),
  batch: async (statements: Statement[]) => statements.map((statement) => exec(statement.sql, statement.params)),
  stmt: (sql: string, ...params: unknown[]): Statement => ({ sql, params }),
}));
mock.module("./admin-audit", () => ({ recordAdminAction: async () => undefined }));
mock.module("./events/emit", () => ({ publicUrl: (path: string) => path }));
mock.module("./user-inbox", () => ({ invalidateUnread: async () => undefined }));
mock.module("./access-revocation", () => ({ dropMcpAccess: async () => undefined }));

const { deleteDiscussionComment, deleteIssueComment } = await import("./comment-removal");
const { setModerationHidden } = await import("./moderation");

const issueCount = () => (db.query("SELECT comments_count AS n FROM issues").get() as { n: number }).n;
const discussionCount = () => (db.query("SELECT comments_count AS n FROM discussions").get() as { n: number }).n;

beforeEach(() => {
  db.exec(`
    DELETE FROM discussion_comments; DELETE FROM discussions; DELETE FROM discussion_categories;
    DELETE FROM review_comments; DELETE FROM comments; DELETE FROM issues; DELETE FROM repos; DELETE FROM accounts;
    INSERT INTO accounts (id, name, kind, created_at) VALUES ('u', 'u', 'user', 0);
    INSERT INTO repos (id, owner_id, name, artifacts_name, artifacts_remote, visibility, created_at, updated_at)
    VALUES ('r', 'u', 'r', 'a', 'x', 'public', 0, 0);
    INSERT INTO issues (id, repo_id, number, author_id, title, state, comments_count, created_at, updated_at)
    VALUES ('i', 'r', 1, 'u', 't', 'open', 2, 0, 0);
    INSERT INTO comments (id, issue_id, author_id, body, created_at, updated_at)
    VALUES ('c1', 'i', 'u', 'a', 0, 0), ('c2', 'i', 'u', 'b', 0, 0);