144 lines · 5.5 KB
import { beforeEach, describe, expect, mock, test } from "bun:test";
import { fakeD1 } from "../metering/fake-d1.test-helper";
import { scopedTestState } from "./scoped.test-helper";

let d1 = fakeD1();
const scoped = scopedTestState();
scoped.install();
const kv = new Map<string, string>();
const objects = new Map<string, number>();
const LIST_LIMIT = 2;
const fakeEnv = {
  PUBLIC_URL: "https://forge.test",
  get DB() {
    return d1.binding;
  },
  KV: {
    get: async (key: string, type?: string) => {
      const value = kv.get(key) ?? null;
      return value !== null && type === "json" ? JSON.parse(value) : value;
    },
    put: async (key: string, value: string) => void kv.set(key, value),
    delete: async (key: string) => void kv.delete(key),
  },
  BUCKET: {
    list: async (options: { prefix: string; cursor?: string }) => {
      const keys = [...objects.keys()].filter((key) => key.startsWith(options.prefix)).sort();
      const start = Number(options.cursor ?? 0);
      const page = keys.slice(start, start + LIST_LIMIT);
      return {
        objects: page.map((key) => ({ key, uploaded: new Date(objects.get(key) ?? 0) })),
        truncated: start + LIST_LIMIT < keys.length,
        cursor: String(start + LIST_LIMIT),
      };
    },
    head: async (key: string) => (objects.has(key) ? { uploaded: new Date(objects.get(key) ?? 0) } : null),
    delete: async (keys: string[]) => void keys.forEach((key) => objects.delete(key)),
  },
};
mock.module("cloudflare:workers", () => ({ env: fakeEnv, waitUntil: () => undefined }));
const notices: string[] = [];