Skip to content

Commit

Permalink
test: add tests for utils (#6109)
Browse files Browse the repository at this point in the history
* chore: Add tests for utils toHex

* chore: Add tests for utils fromHex

* chore: Add tests for utils toHexString

* chore: enhance tests for bytes utils

* fix: fix lint warning

* fix: udpate to.be => to.deep

* chore: adjust tests output message
  • Loading branch information
murrayee authored Nov 23, 2023
1 parent be1cf76 commit a8767da
Showing 1 changed file with 52 additions and 1 deletion.
53 changes: 52 additions & 1 deletion packages/utils/test/unit/bytes.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import "../setup.js";
import {assert, expect} from "chai";
import {intToBytes, bytesToInt} from "../../src/index.js";
import {intToBytes, bytesToInt, toHex, fromHex, toHexString} from "../../src/index.js";

describe("intToBytes", () => {
const zeroedArray = (length: number): number[] => Array.from({length}, () => 0);
Expand Down Expand Up @@ -47,3 +47,54 @@ describe("bytesToInt", () => {
});
}
});

describe("toHex", () => {
const testCases: {input: Buffer | Uint8Array | string; output: string}[] = [
{input: Buffer.from("Hello, World!", "utf-8"), output: "0x48656c6c6f2c20576f726c6421"},
{input: new Uint8Array([72, 101, 108, 108, 111]), output: "0x48656c6c6f"},
{input: Buffer.from([72, 101, 108, 108, 111]), output: "0x48656c6c6f"},
{input: Buffer.from([]), output: "0x"},
];
for (const {input, output} of testCases) {
it(`should convert Uint8Array to hex string ${output}`, () => {
expect(toHex(input)).to.be.equal(output);
});
}
});

describe("fromHex", () => {
const testCases: {input: string; output: Buffer | Uint8Array}[] = [
{
input: "0x48656c6c6f2c20576f726c6421",
output: new Uint8Array([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]),
},
{
input: "48656c6c6f2c20576f726c6421",
output: new Uint8Array([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]),
},
{input: "0x", output: new Uint8Array([])},
];

for (const {input, output} of testCases) {
it(`should convert hex string ${input} to Uint8Array`, () => {
expect(fromHex(input)).to.deep.equal(output);
});
}
});

describe("toHexString", () => {
const testCases: {input: Uint8Array; output: string}[] = [
{input: new Uint8Array([1, 2, 3]), output: "0x010203"},
{input: new Uint8Array([72, 101, 108, 108, 111]), output: "0x48656c6c6f"},
{input: new Uint8Array([]), output: "0x"},
{input: new Uint8Array([0, 0, 0, 0]), output: "0x00000000"},
{input: new Uint8Array([15, 255, 16, 0, 127]), output: "0x0fff10007f"},
{input: new Uint8Array(5).fill(255), output: "0x" + "ff".repeat(5)},
];

for (const {input, output} of testCases) {
it(`should convert Uint8Array to hex string ${output}`, () => {
expect(toHexString(input)).to.be.equal(output);
});
}
});

0 comments on commit a8767da

Please sign in to comment.