Luigit
repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by admin

extensions/quota/__tests__/http.test.ts

Raw
import { afterEach, describe, expect, it, vi } from "vitest";
import { fetchJson } from "../src/http.ts";

afterEach(() => vi.unstubAllGlobals());

describe("quota HTTP boundary", () => {
	it("keeps HTTP and malformed-body errors free of response content", async () => {
		const fetch = vi
			.fn()
			.mockResolvedValueOnce(
				new Response("sensitive-provider-body", { status: 401 }),
			)
			.mockResolvedValueOnce(new Response("sensitive-provider-body"));
		vi.stubGlobal("fetch", fetch);
		await expect(fetchJson("https://fixture.invalid", {})).rejects.toThrow(
			"Quota HTTP 401",
		);
		await expect(fetchJson("https://fixture.invalid", {})).rejects.toThrow(
			"Malformed quota response",
		);
		expect(fetch.mock.calls[0]?.[1]).toMatchObject({ redirect: "error" });
	});

	it("cancels oversized quota bodies before parsing", async () => {
		const cancel = vi.fn();
		const stream = new ReadableStream<Uint8Array>({
			start(controller) {
				controller.enqueue(new Uint8Array(1024 * 1024 + 1));
			},
			cancel,
		});
		vi.stubGlobal(
			"fetch",
			vi.fn(async () => new Response(stream)),
		);
		await expect(fetchJson("https://fixture.invalid", {})).rejects.toThrow(
			"exceeds 1 MiB",
		);
		expect(cancel).toHaveBeenCalledOnce();
	});
});