From 8e1e99f971a7e200cb3955ef51ddbe38bdd39965 Mon Sep 17 00:00:00 2001 From: 0xLogN Date: Thu, 23 Feb 2023 08:30:59 -0800 Subject: [PATCH] test(DirectStream): add new 4kb and 4mb encode tests After other implementations of this, it was determined that expect(4mb).toEqual(4mb) took around 30 seconds to run, so we only really check (and care about) the first three bytes. --- .vscode/settings.json | 2 +- src/tests/stream/DirectStream.test.ts | 27 ++++++++++++++++++++++++++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index b942939..ab896b5 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,3 @@ { - "cSpell.words": ["TCPIO"] + "cSpell.words": ["bufncmp", "TCPIO"] } diff --git a/src/tests/stream/DirectStream.test.ts b/src/tests/stream/DirectStream.test.ts index d596fa2..12e9a86 100644 --- a/src/tests/stream/DirectStream.test.ts +++ b/src/tests/stream/DirectStream.test.ts @@ -20,6 +20,16 @@ import { kb, mb } from "../../lib/sizeHelpers"; import { ControlCharacters } from "../../stream/controlCharacters"; import DirectStream, { DirectStreamEvents } from "../../stream/DirectStream"; +/** Like C's memncmp() for buffers. Used in the large-buffer tests to avoid long test times */ +function bufncmp(n: number, left: Buffer, right: Buffer): number { + const len = Math.min(left.length, right.length, n); + for (let i = 0; i < len; i++) { + if (left[i] < right[i]) return -1; + if (left[i] > right[i]) return 1; + } + return 0; +} + /** Makes a new {@link DirectStream} and attaches listeners. */ function makeNewStream(): { stream: DirectStream; onRead: jest.Mock; onPacket: jest.Mock; onReset: jest.Mock } { const stream = new DirectStream(); @@ -317,7 +327,22 @@ describe("Stream", () => { 0xff ]) ); - // TODO: more? + it("4kb", () => { + const stream = new DirectStream(); + + const expected = Buffer.concat([Buffer.from([ControlCharacters.ReadKB, 0x00]), Buffer.alloc(kb(4))]); + + // Running .toEqual is extremely slow on huge buffers, so we use a custom bufncmp function + expect(bufncmp(3, stream.encode(expected.subarray(2)), expected)).toBe(0); + }); + it("4mb", () => { + const stream = new DirectStream(); + + const expected = Buffer.concat([Buffer.from([ControlCharacters.ReadMB, 0x00]), Buffer.alloc(mb(4))]); + + // See above + expect(bufncmp(3, stream.encode(expected.subarray(2)), expected)).toBe(0); + }); }); it("fails for unsupported read sizes", () => {