Files
MUA-Mikes-Unraid-Agent/src/process-output.test.ts
T

70 lines
2.9 KiB
TypeScript

import { describe, expect, test } from "bun:test";
import { readProcessOutput } from "./process-output";
function source(parts: string[], onCancel = () => {}) {
const encoder = new TextEncoder();
return new ReadableStream<Uint8Array>({
start(controller) {
for (const part of parts) controller.enqueue(encoder.encode(part));
controller.close();
},
cancel: onCancel,
});
}
describe("bounded pipe capture", () => {
test("preserves small UTF-8 output across chunk boundaries", async () => {
const bytes = new TextEncoder().encode("Grüße");
const stream = new ReadableStream<Uint8Array>({ start(controller) {
for (const byte of bytes) controller.enqueue(Uint8Array.of(byte));
controller.close();
} });
expect(await readProcessOutput(stream, bytes.length)).toEqual({ text: "Grüße", truncated: false, bytesRead: bytes.length });
expect(stream.locked).toBe(false);
});
test("tail survives ring wraparound and oversized chunks", async () => {
for (const parts of [["ab", "cdef", "ghij", "kl"], ["abcdefghijkl"], ["abcdefghij", "kl"]]) {
expect(await readProcessOutput(source(parts), 5, { mode: "tail", stopOnLimit: false })).toEqual({
text: "hijkl", truncated: true, bytesRead: 12,
});
}
});
test("draining a bounded head consumes the whole stream without cancellation", async () => {
let cancelled = false;
expect(await readProcessOutput(source(["abcd", "efgh", "ijkl"], () => { cancelled = true; }), 5, { stopOnLimit: false })).toEqual({
text: "abcde", truncated: true, bytesRead: 12,
});
expect(cancelled).toBe(false);
});
test("read-only capture cancels a producer after the budget is exceeded", async () => {
let cancelled = false;
const stream = new ReadableStream<Uint8Array>({
pull(controller) { controller.enqueue(new TextEncoder().encode("abcd")); },
cancel() { cancelled = true; },
});
expect(await readProcessOutput(stream, 5)).toEqual({ text: "abcda", truncated: true, bytesRead: 8 });
expect(cancelled).toBe(true);
expect(stream.locked).toBe(false);
});
test("abort cancels an idle pipe and releases its reader", async () => {
let cancelled = false;
const stream = new ReadableStream<Uint8Array>({ cancel() { cancelled = true; } });
const abort = new AbortController();
const pending = readProcessOutput(stream, 64, { stopOnLimit: false, signal: abort.signal });
abort.abort(new Error("synthetic timeout"));
await expect(pending).rejects.toThrow("synthetic timeout");
expect(cancelled).toBe(true);
expect(stream.locked).toBe(false);
});
test("stream failures release the reader", async () => {
const stream = new ReadableStream<Uint8Array>({ start(controller) { controller.error(new Error("synthetic failure")); } });
await expect(readProcessOutput(stream, 64)).rejects.toThrow("synthetic failure");
expect(stream.locked).toBe(false);
});
});