52 lines · 1.7 KB
import { describe, expect, mock, test } from "bun:test";

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

const { scanThinDeltas, ScanIncompleteError } = await import("./push-protection");

const encoder = new TextEncoder();
const base = encoder.encode("hello ");
const insert = encoder.encode("world");
const delta = new Uint8Array([
  base.byteLength,
  base.byteLength + insert.byteLength,
  0x90,
  base.byteLength,
  insert.byteLength,
  ...insert,
]);
const unresolved = [{ baseSha: "b".repeat(40), inserted: [insert], delta }];

async function collect(loader: {
  blob: (sha: string) => Promise<Uint8Array | null>;
  isNonBlob: () => Promise<boolean>;
}) {
  const scanned: string[] = [];
  await scanThinDeltas(unresolved, loader, async (bytes) => {
    scanned.push(new TextDecoder().decode(bytes));
  });
  return scanned;
}

describe("scanThinDeltas", () => {
  test("scans the reconstructed blob when the base loads", async () => {
    expect(await collect({ blob: async () => base, isNonBlob: async () => false })).toEqual(["hello world"]);
  });

  test("fails closed when a blob base cannot be loaded", async () => {
    await expect(collect({ blob: async () => null, isNonBlob: async () => false })).rejects.toBeInstanceOf(
      ScanIncompleteError,
    );
  });