Files
kuber/tests/lib/request-log.test.ts
T

66 lines
1.9 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import { logServerRequest } from "../../lib/request-log";
describe("server response logging", () => {
test("does not consume streaming response bodies", async () => {
let pulls = 0;
const body = new ReadableStream<Uint8Array>({
pull(controller) {
pulls += 1;
controller.enqueue(new TextEncoder().encode('{"message":"live"}\n'));
},
});
const logs: Record<string, unknown>[] = [];
const response = new Response(body, {
headers: { "content-type": "application/x-ndjson; charset=utf-8" },
});
await Bun.sleep(0);
const pullsBeforeLogging = pulls;
const loggedResponse = await logServerRequest(
new Request("https://kuber.astrxl.dev/logs"),
"streaming-response",
() => response,
{ log: (entry) => logs.push(entry) },
);
expect(pulls).toBe(pullsBeforeLogging);
expect(logs).toContainEqual(
expect.objectContaining({
event: "kuber.server.response.body",
bodySkipped: true,
streaming: true,
}),
);
const reader = loggedResponse.body!.getReader();
expect(new TextDecoder().decode((await reader.read()).value)).toBe(
'{"message":"live"}\n',
);
await reader.cancel();
});
test("logs bounded non-streaming response bodies", async () => {
const logs: Record<string, unknown>[] = [];
await logServerRequest(
new Request("https://kuber.astrxl.dev/health"),
"bounded-response",
() =>
new Response("healthy", {
headers: {
"content-length": "7",
"content-type": "text/plain; charset=utf-8",
},
}),
{ log: (entry) => logs.push(entry) },
);
await Bun.sleep(0);
expect(logs).toContainEqual(
expect.objectContaining({
event: "kuber.server.response.body",
body: { encoding: "base64", data: "aGVhbHRoeQ==" },
}),
);
});
});