187 lines · 6.9 KB
import { beforeEach, describe, expect, mock, test } from "bun:test";
import type { Viewer } from "~/lib/types";

class StubEntrypoint {}
mock.module("cloudflare:workers", () => ({
  env: {
    PUBLIC_URL: "https://forge.example.com",
    ACCOUNT_STATE: { idFromName: (name: string) => name, get: () => ({ destroy: async () => undefined }) },
  },
  waitUntil: () => undefined,
  WorkflowEntrypoint: StubEntrypoint,
  DurableObject: StubEntrypoint,
  WorkerEntrypoint: StubEntrypoint,
}));

const state = {
  orgExists: true,
  repos: [] as Array<{ id: string; name: string }>,
  retired: new Set<string>(),
  statements: [] as string[],
  deletedRepos: [] as string[],
  removedRunners: [] as string[],
};
const roles: Record<string, "owner" | "member"> = { "u-owner": "owner", "u-member": "member" };

const d1 = {
  first: async (sql: string, ...params: unknown[]) => {
    if (sql.includes("kind = 'org'"))
      return state.orgExists && params[0] === "acme" ? { id: "org-1", name: "acme" } : null;
    if (sql.includes("FROM accounts WHERE name = ?")) return null;
    if (sql.includes("retired_account_names"))
      return state.retired.has(String(params[0]).toLowerCase()) ? { ok: 1 } : null;
    if (sql.includes("FROM account_redirects WHERE old_name")) return null;
    if (sql.includes("SELECT role FROM org_members")) {
      const role = roles[String(params[1])];
      return role ? { role } : null;
    }
    if (sql.includes("FROM org_members")) return roles[String(params[1])] ? { ok: 1 } : null;
    if (sql.includes("WHERE r.id = ?")) return { id: params[0], name: "repo", owner_name: "acme" };
    return null;