import { expect } from 'chai'; import { uuidv4, randomIntInclusive, randomIntExclusive, randomFloatInclusive, randomFloatExclusive, randomChar, randomString } from '../../../lib/core/random'; function repeat(n: number, callbackfn: (...args: any[]) => any) { while (n-- > 0) callbackfn(); } const repeatSome = repeat.bind(undefined, 10); const HEX = 'abcdef0123456789'; const ALNUM = 'abcdefghijklmnopqrstuvwxyz0123456789'; describe('core.random', () => { describe('uuidv4', () => { test('uuidv4', () => { repeatSome(() => { expect(uuidv4()).to.match(/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/); }); }); }); describe('randomIntInclusive', () => { test.each([ [0, 1], [0, 255], [-128, 127], ])('randomIntInclusive(%d, %d)', (min: number, max: number) => { repeatSome(() => { expect(randomIntInclusive(min, max)).to.be.within(min, max); }); }); }); describe('randomIntExclusive', () => { test.each([ [0, 1], [0, 255], [-128, 127], ])('randomIntExclusive(%d, %d)', (min: number, max: number) => { repeatSome(() => { expect(randomIntExclusive(min, max)).to.be.at.least(min).and.below(max); }); }); }); describe('randomFloatInclusive', () => { test.each([ [0, 1], [0, 255], [-128, 127], [0.5, 1.5], [-Math.PI, Math.PI], ])('randomFloatInclusive(%d, %d)', (min: number, max: number) => { repeatSome(() => { expect(randomFloatInclusive(min, max)).to.be.within(min, max); }); }); }); describe('randomFloatExclusive', () => { test.each([ [0, 1], [0, 255], [-128, 127], [0.5, 1.5], [-Math.PI, Math.PI], ])('randomFloatExclusive(%d, %d)', (min: number, max: number) => { repeatSome(() => { expect(randomFloatExclusive(min, max)).to.be.at.least(min).and.below(max); }); }); }); describe('randomChar', () => { test.each([ [HEX, /^[a-f\d]$/], [ALNUM, /^[\w\d]$/], ])('randomChar(%s)', (alphabet: string, re: RegExp) => { repeatSome(() => { expect(randomChar(alphabet)).to.match(re); }); }); }); describe('randomString', () => { test.each([ [1, HEX, /^[a-f\d]$/], [5, HEX, /^[a-f\d]{5}$/], [12,HEX, /^[a-f\d]{12}$/], [1, ALNUM, /^[\w\d]$/], [5, ALNUM, /^[\w\d]{5}$/], [12,ALNUM, /^[\w\d]{12}$/], ])('randomString(%s)', (size: number, alphabet: string, re: RegExp) => { repeatSome(() => { expect(randomString(size, alphabet)).to.match(re); }); }); }); });