UNPKG

@cloudpss/ubjson

Version:

Opinionated UBJSON encoder/decoder for CloudPSS.

38 lines (36 loc) 1.69 kB
import { Readable } from 'node:stream'; import { encode as encodeStream, decode as decodeStream } from '../../dist/stream/index.js'; import { EXPECTED, INPUTS } from './.data.js'; describe('stream', () => { it.each(Object.keys(INPUTS))('%s', async (name) => { const input = INPUTS[name]; const expected = EXPECTED[name] ?? input; if (expected instanceof Error) { await expect(async () => { const encoded = await Readable.fromWeb(/** @type {any} */ (encodeStream(input))).toArray(); const decoded = await decodeStream( /** @type {ReadableStream<Uint8Array>} */ (Readable.toWeb(Readable.from(encoded))), ); expect(decoded).toEqual(expected); }).rejects.toThrow(expected); } else { const encoded = await Readable.fromWeb(/** @type {any} */ (encodeStream(input))).toArray(); const data = encoded.flatMap((/** @type {Buffer} */ chunk) => { if (chunk.length < 2) return [chunk]; // split to random chunks const chunks = []; let offset = 0; while (offset < chunk.length) { const size = Math.floor(Math.random() * chunk.length); chunks.push(chunk.subarray(offset, offset + size)); offset += size; } return chunks; }); const decoded = await decodeStream( /** @type {ReadableStream<Uint8Array>} */ (Readable.toWeb(Readable.from(data))), ); expect(decoded).toEqual(expected); } }); });