import {describe, expect, test} from 'bun:test' import {readStreamCapped, StreamOverflowError} from './stream' const chunkedReader = (chunks: Uint8Array[]) => new ReadableStream({ start(controller) { for (const chunk of chunks) controller.enqueue(chunk) controller.close() }, }).getReader() describe('readStreamCapped', () => { test('reject reads a body within the cap fully', async () => { const bytes = await readStreamCapped( chunkedReader([new TextEncoder().encode('hello')]), 1024, 'reject', ) expect(bytes).toEqual(new TextEncoder().encode('hello')) }) test('reject throws once the cap is exceeded', () => { const chunk = new Uint8Array(1024).fill(1) expect( readStreamCapped( chunkedReader(Array.from({length: 10}, () => chunk)), 4 * 1024, 'reject', ), ).rejects.toBeInstanceOf(StreamOverflowError) }) test('returns empty bytes without a reader', async () => { expect(await readStreamCapped(undefined, 1024, 'reject')).toEqual( new Uint8Array(), ) }) })