crypto.spec.ts 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { describe, expect, it } from "vitest";
  2. import { compress, computeHash, decompress, randomId } from "./crypto.js";
  3. //#region compress
  4. describe("crypto/compress", () => {
  5. it("Compresses strings and buffers as expected", async () => {
  6. const input = "Hello, world!".repeat(100);
  7. expect((await compress(input, "gzip", "string")).startsWith("H4sI")).toBe(true);
  8. expect((await compress(input, "deflate", "string")).startsWith("eJzz")).toBe(true);
  9. expect((await compress(input, "deflate-raw", "string")).startsWith("80jN")).toBe(true);
  10. expect(await compress(input, "gzip", "arrayBuffer")).toBeInstanceOf(ArrayBuffer);
  11. });
  12. });
  13. //#region decompress
  14. describe("crypto/decompress", () => {
  15. it("Decompresses strings and buffers as expected", async () => {
  16. const inputGz = "H4sIAAAAAAAACvNIzcnJ11Eozy/KSVH0GOWMckY5o5yRzQEAatVNcBQFAAA=";
  17. const inputDf = "eJzzSM3JyddRKM8vyklR9BjljHJGOaOckc0BAOWGxZQ=";
  18. const inputDfRaw = "80jNycnXUSjPL8pJUfQY5YxyRjmjnJHNAQA=";
  19. const expectedDecomp = "Hello, world!".repeat(100);
  20. expect(await decompress(inputGz, "gzip", "string")).toBe(expectedDecomp);
  21. expect(await decompress(inputDf, "deflate", "string")).toBe(expectedDecomp);
  22. expect(await decompress(inputDfRaw, "deflate-raw", "string")).toBe(expectedDecomp);
  23. });
  24. });
  25. //#region computeHash
  26. describe("crypto/computeHash", () => {
  27. it("Computes hashes as expected", async () => {
  28. const input1 = "Hello, world!";
  29. const input2 = input1.repeat(10);
  30. expect(await computeHash(input1, "SHA-1")).toBe("943a702d06f34599aee1f8da8ef9f7296031d699");
  31. expect(await computeHash(input1, "SHA-256")).toBe("315f5bdb76d078c43b8ac0064e4a0164612b1fce77c869345bfc94c75894edd3");
  32. expect(await computeHash(input1, "SHA-512")).toBe("c1527cd893c124773d811911970c8fe6e857d6df5dc9226bd8a160614c0cd963a4ddea2b94bb7d36021ef9d865d5cea294a82dd49a0bb269f51f6e7a57f79421");
  33. expect(await computeHash(input2, "SHA-256")).toBe(await computeHash(input2, "SHA-256"));
  34. });
  35. });
  36. //#region randomId
  37. describe("crypto/randomId", () => {
  38. it("Generates random IDs as expected", () => {
  39. const id1 = randomId(32, 36, false, true);
  40. expect(id1).toHaveLength(32);
  41. expect(id1).toMatch(/^[0-9a-zA-Z]+$/);
  42. const id2 = randomId(32, 36, true, true);
  43. expect(id2).toHaveLength(32);
  44. expect(id2).toMatch(/^[0-9a-zA-Z]+$/);
  45. expect(randomId(32, 2, false, false)).toMatch(/^[01]+$/);
  46. });
  47. it("Handles all edge cases", () => {
  48. expect(() => randomId(16, 1)).toThrow(RangeError);
  49. expect(() => randomId(16, 37)).toThrow(RangeError);
  50. expect(() => randomId(-1)).toThrow(RangeError);
  51. });
  52. });