|
| 1 | +import { assert, assertEquals } from '@std/assert' |
| 2 | +import { createUTF8Stream, UnicodeDecodeError } from './streams.ts' |
| 3 | + |
| 4 | +function streamFromUint8Array(arr: Uint8Array): ReadableStream<Uint8Array> { |
| 5 | + return new ReadableStream({ |
| 6 | + start(controller) { |
| 7 | + controller.enqueue(arr) |
| 8 | + controller.close() |
| 9 | + }, |
| 10 | + }) |
| 11 | +} |
| 12 | + |
| 13 | +Deno.test('createUTF8Stream', async (t) => { |
| 14 | + await t.step('should return a TransformStream with UTF8StreamTransformer', () => { |
| 15 | + const stream = createUTF8Stream() |
| 16 | + assertEquals(stream instanceof TransformStream, true) |
| 17 | + }) |
| 18 | + |
| 19 | + await t.step('should correctly transform UTF-8 input', async () => { |
| 20 | + const rawstream = streamFromUint8Array(new TextEncoder().encode('Hello, world!')) |
| 21 | + const reader = rawstream.pipeThrough(createUTF8Stream()).getReader() |
| 22 | + const { value } = await reader.read() |
| 23 | + assertEquals(value, 'Hello, world!') |
| 24 | + |
| 25 | + await reader.cancel() |
| 26 | + }) |
| 27 | + |
| 28 | + await t.step('should throw UnicodeDecodeError for UTF-16 input', async () => { |
| 29 | + const rawStream = streamFromUint8Array(new Uint8Array([0xFF, 0xFE, 0x00, 0x00])) |
| 30 | + |
| 31 | + let reader |
| 32 | + try { |
| 33 | + // The exception can't be localized to either of the following lines |
| 34 | + // but is raised before the second returns |
| 35 | + reader = rawStream.pipeThrough(createUTF8Stream()).getReader() |
| 36 | + const { value } = await reader.read() |
| 37 | + assert(false, 'Expected UnicodeDecodeError, got ' + value) |
| 38 | + } catch (e: any) { |
| 39 | + assertEquals(e instanceof UnicodeDecodeError, true) |
| 40 | + assertEquals(e?.message, 'This file appears to be UTF-16') |
| 41 | + } finally { |
| 42 | + if (reader) await reader.cancel |
| 43 | + } |
| 44 | + }) |
| 45 | +}) |
0 commit comments