Files
WebTools/tests/random.test.ts
T

26 lines
1.1 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import { formatBytes } from '../src/lib/bytes'
import { secureRandomBytes, type RandomSource } from '../src/lib/random'
describe('secure random bytes', () => {
it('uses the supplied cryptographic source and preserves requested length', () => {
let next = 0
const source: RandomSource = {
getRandomValues<T extends ArrayBufferView>(array: T): T {
const bytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength)
bytes.forEach((_, index) => { bytes[index] = next; next += 1 })
return array
},
}
expect(secureRandomBytes(4, source)).toEqual(Uint8Array.from([0, 1, 2, 3]))
expect(() => secureRandomBytes(0, source)).toThrow('1 至 65536')
})
it('formats the same bytes for OpenSSL and source-code styles', () => {
const bytes = Uint8Array.from([0x0a, 0xbc, 0xff])
expect(formatBytes(bytes)).toBe('0ABCFF')
expect(formatBytes(bytes, { format: 'spaced-hex' })).toBe('0A BC FF')
expect(formatBytes(bytes, { format: 'byte-array', uppercase: false })).toBe('0x0a, 0xbc, 0xff')
})
})