Files
patriothacks/api/blob.integration.test.ts

70 lines
2.5 KiB
TypeScript

import type { AddressInfo } from "node:net";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { createApiServer } from "./_lib/devServer.ts";
import { MAX_BLOB_SIZE_BYTES } from "./_lib/blobStore.ts";
describe("blob/KV backend integration (todo 56)", () => {
let server: ReturnType<typeof createApiServer>;
let baseUrl: string;
let storeDir: string;
beforeAll(async () => {
storeDir = await mkdtemp(join(tmpdir(), "commons-blob-test-"));
process.env.BLOB_DB_PATH = join(storeDir, "blobs.sqlite3");
server = createApiServer();
await new Promise<void>((resolve) => server.listen(0, resolve));
const { port } = server.address() as AddressInfo;
baseUrl = `http://127.0.0.1:${port}`;
});
afterAll(async () => {
await new Promise<void>((resolve) => server.close(() => resolve()));
delete process.env.BLOB_DB_PATH;
await rm(storeDir, { recursive: true, force: true });
});
it("stores and retrieves a sample mini-app blob by id over real HTTP", async () => {
const sampleHtml = "<html><body>sample mini-app</body></html>";
const putRes = await fetch(`${baseUrl}/api/blob`, {
method: "POST",
headers: { "Content-Type": "text/html" },
body: sampleHtml,
});
expect(putRes.status).toBe(201);
const { id } = (await putRes.json()) as { id: string };
expect(id).toMatch(/^[0-9a-f-]{36}$/);
const getRes = await fetch(`${baseUrl}/api/blob/${id}`);
expect(getRes.status).toBe(200);
expect(getRes.headers.get("content-type")).toBe("text/html");
expect(await getRes.text()).toBe(sampleHtml);
});
it("rejects an oversized upload with a clear 413 error, not silent truncation", async () => {
const oversized = new Uint8Array(MAX_BLOB_SIZE_BYTES + 1024);
const res = await fetch(`${baseUrl}/api/blob`, {
method: "POST",
headers: { "Content-Type": "application/octet-stream" },
body: oversized,
});
expect(res.status).toBe(413);
const body = (await res.json()) as { error: string; maxBytes: number };
expect(body.error).toMatch(/exceeds maximum size/i);
expect(body.maxBytes).toBe(MAX_BLOB_SIZE_BYTES);
});
it("returns a clean 404 for a non-existent blob id", async () => {
const res = await fetch(`${baseUrl}/api/blob/00000000-0000-0000-0000-000000000000`);
expect(res.status).toBe(404);
const body = (await res.json()) as { error: string };
expect(body.error).toMatch(/not found/i);
});
});