121 lines · 5.0 KB
import { 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 { PullRow } from "./pulls";

mock.module("cloudflare:workers", () => ({ env: {}, waitUntil: () => undefined }));

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

const bind = (params: unknown[]) => params as never[];
mock.module("./db", () => ({
  first: async (sql: string, ...params: unknown[]) => db.query(sql).get(...bind(params)) ?? null,
  all: async (sql: string, ...params: unknown[]) => db.query(sql).all(...bind(params)),
  run: async (sql: string, ...params: unknown[]) => db.query(sql).run(...bind(params)),
  batch: async () => [],
  stmt: (sql: string, ...params: unknown[]) => ({ sql, params }),
  placeholders: (count: number) => Array(count).fill("?").join(", "),
  chunks: <T>(items: T[]) => [items],
  MAX_IN_LIST: 90,
}));

const { loadStack, mergePath, stackChildren, stackParent } = await import("./stacks");
const { PULL_SELECT } = await import("./pulls");

db.exec(`
  INSERT INTO accounts (id, name, kind, created_at) VALUES ('owner', 'owner', 'user', 0);
  INSERT INTO repos (id, owner_id, name, visibility, status, default_branch, artifacts_name, artifacts_remote, created_at, updated_at)
    VALUES ('repo', 'owner', 'app', 'public', 'ready', 'main', 'a', 'r', 0, 0),
           ('fork', 'owner', 'app-fork', 'public', 'ready', 'main', 'b', 'f', 0, 0);
`);

function addPull(number: number, head: string, base: string, options: { state?: string; headRepo?: string } = {}) {
  const id = `pr${number}`;
  db.query(
    `INSERT INTO issues (id, repo_id, number, title, body, state, author_id, is_pull, created_at, updated_at)
     VALUES (?, 'repo', ?, ?, '', ?, 'owner', 1, 0, 0)`,
  ).run(id, number, `Change ${number}`, options.state ?? "open");