|
| 1 | +// Qqbot tests cover api-client plugin behavior. |
| 2 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 3 | +import { ApiError } from "../types.js"; |
| 4 | +import { ApiClient } from "./api-client.js"; |
| 5 | + |
| 6 | +function cancelTrackedResponse( |
| 7 | +text: string, |
| 8 | +init: ResponseInit, |
| 9 | +): { |
| 10 | +response: Response; |
| 11 | +wasCanceled: () => boolean; |
| 12 | +} { |
| 13 | +let canceled = false; |
| 14 | +const stream = new ReadableStream<Uint8Array>({ |
| 15 | +start(controller) { |
| 16 | +controller.enqueue(new TextEncoder().encode(text)); |
| 17 | +}, |
| 18 | +cancel() { |
| 19 | +canceled = true; |
| 20 | +}, |
| 21 | +}); |
| 22 | +return { |
| 23 | +response: new Response(stream, init), |
| 24 | +wasCanceled: () => canceled, |
| 25 | +}; |
| 26 | +} |
| 27 | + |
| 28 | +describe("ApiClient", () => { |
| 29 | +afterEach(() => { |
| 30 | +vi.restoreAllMocks(); |
| 31 | +}); |
| 32 | + |
| 33 | +it("bounds error bodies without using response.text()", async () => { |
| 34 | +const tracked = cancelTrackedResponse(`${"qqbot api unavailable ".repeat(1024)}tail`, { |
| 35 | +status: 503, |
| 36 | +headers: { "content-type": "text/plain" }, |
| 37 | +}); |
| 38 | +const textSpy = vi.spyOn(tracked.response, "text").mockRejectedValue(new Error("unbounded")); |
| 39 | +vi.spyOn(globalThis, "fetch").mockResolvedValue(tracked.response); |
| 40 | + |
| 41 | +const client = new ApiClient({ baseUrl: "https://qqbot.test" }); |
| 42 | + |
| 43 | +let error: unknown; |
| 44 | +try { |
| 45 | +await client.request("token-1", "GET", "/v2/users/@me"); |
| 46 | +} catch (caught) { |
| 47 | +error = caught; |
| 48 | +} |
| 49 | + |
| 50 | +expect(error).toBeInstanceOf(ApiError); |
| 51 | +expect(String(error)).toContain("API Error [/v2/users/@me] HTTP 503"); |
| 52 | +expect(String(error)).toContain("qqbot api unavailable"); |
| 53 | +expect(String(error)).not.toContain("tail"); |
| 54 | +expect(tracked.wasCanceled()).toBe(true); |
| 55 | +expect(textSpy).not.toHaveBeenCalled(); |
| 56 | +}); |
| 57 | +}); |