|
| 1 | +import { AwsCrc32 } from "@aws-crypto/crc32"; |
| 2 | +import { numToUint8 } from "@aws-crypto/util"; |
| 3 | +import { describe, expect, test as it, vi } from "vitest"; |
| 4 | +import * as zlib from "zlib"; |
| 5 | + |
| 6 | +import { getCrc32ChecksumAlgorithmFunction } from "./getCrc32ChecksumAlgorithmFunction"; |
| 7 | + |
| 8 | +describe(getCrc32ChecksumAlgorithmFunction.name, () => { |
| 9 | + it("returns AwsCrc32 if zlib.crc32 is undefined", () => { |
| 10 | + vi.mock("zlib", () => ({ crc32: undefined })); |
| 11 | + expect(getCrc32ChecksumAlgorithmFunction()).toBe(AwsCrc32); |
| 12 | + }); |
| 13 | + |
| 14 | + it("returns NodeCrc32 if zlib.crc32 is defined", async () => { |
| 15 | + const mockData = new Uint8Array([1, 2, 3]); |
| 16 | + const mockChecksum = 42; |
| 17 | + |
| 18 | + // @ts-expect-error crc32 is defined only for Node.js >=v20.15.0 and >=v22.2.0. |
| 19 | + zlib.crc32 = vi |
| 20 | + .fn() |
| 21 | + .mockReturnValueOnce(mockChecksum) |
| 22 | + .mockReturnValueOnce(2 * mockChecksum); |
| 23 | + |
| 24 | + const crc32Fn = getCrc32ChecksumAlgorithmFunction(); |
| 25 | + expect(crc32Fn).not.toBe(AwsCrc32); |
| 26 | + |
| 27 | + // @ts-expect-error crc32 is defined only for Node.js >=v20.15.0 and >=v22.2.0. |
| 28 | + expect(zlib.crc32).not.toHaveBeenCalled(); |
| 29 | + const crc32 = new crc32Fn(); |
| 30 | + // @ts-expect-error crc32 is defined only for Node.js >=v20.15.0 and >=v22.2.0. |
| 31 | + expect(zlib.crc32).not.toHaveBeenCalled(); |
| 32 | + expect(await crc32.digest()).toEqual(numToUint8(0)); |
| 33 | + |
| 34 | + crc32.update(mockData); |
| 35 | + // @ts-expect-error crc32 is defined only for Node.js >=v20.15.0 and >=v22.2.0. |
| 36 | + expect(zlib.crc32).toHaveBeenCalledWith(mockData, 0); |
| 37 | + expect(await crc32.digest()).toEqual(numToUint8(mockChecksum)); |
| 38 | + |
| 39 | + crc32.update(mockData); |
| 40 | + // @ts-expect-error crc32 is defined only for Node.js >=v20.15.0 and >=v22.2.0. |
| 41 | + expect(zlib.crc32).toHaveBeenCalledWith(mockData, mockChecksum); |
| 42 | + expect(await crc32.digest()).toEqual(numToUint8(2 * mockChecksum)); |
| 43 | + |
| 44 | + crc32.reset(); |
| 45 | + expect(await crc32.digest()).toEqual(numToUint8(0)); |
| 46 | + }); |
| 47 | +}); |
0 commit comments