1 | import * as assert from 'assert';
|
---|
2 | import test, { describe } from 'node:test';
|
---|
3 | import native from '../native.js';
|
---|
4 | import v4 from '../v4.js';
|
---|
5 | const randomBytesFixture = Uint8Array.of(0x10, 0x91, 0x56, 0xbe, 0xc4, 0xfb, 0xc1, 0xea, 0x71, 0xb4, 0xef, 0xe1, 0x67, 0x1c, 0x58, 0x36);
|
---|
6 | const expectedBytes = Uint8Array.of(16, 145, 86, 190, 196, 251, 65, 234, 177, 180, 239, 225, 103, 28, 88, 54);
|
---|
7 | describe('v4', () => {
|
---|
8 | test('subsequent UUIDs are different', () => {
|
---|
9 | const id1 = v4();
|
---|
10 | const id2 = v4();
|
---|
11 | assert.ok(id1 !== id2);
|
---|
12 | });
|
---|
13 | test('should uses native randomUUID() if no option is passed', async () => {
|
---|
14 | const mock = (await import('node:test')).default.mock;
|
---|
15 | if (!mock) {
|
---|
16 | return;
|
---|
17 | }
|
---|
18 | const mockRandomUUID = mock.method(native, 'randomUUID');
|
---|
19 | assert.equal(mockRandomUUID.mock.callCount(), 0);
|
---|
20 | v4();
|
---|
21 | assert.equal(mockRandomUUID.mock.callCount(), 1);
|
---|
22 | mock.restoreAll();
|
---|
23 | });
|
---|
24 | test('should not use native randomUUID() if an option is passed', async () => {
|
---|
25 | const mock = (await import('node:test')).default.mock;
|
---|
26 | if (!mock) {
|
---|
27 | return;
|
---|
28 | }
|
---|
29 | const mockRandomUUID = mock.method(native, 'randomUUID');
|
---|
30 | assert.equal(mockRandomUUID.mock.callCount(), 0);
|
---|
31 | v4({});
|
---|
32 | assert.equal(mockRandomUUID.mock.callCount(), 0);
|
---|
33 | mock.restoreAll();
|
---|
34 | });
|
---|
35 | test('explicit options.random produces expected result', () => {
|
---|
36 | const id = v4({ random: randomBytesFixture });
|
---|
37 | assert.strictEqual(id, '109156be-c4fb-41ea-b1b4-efe1671c5836');
|
---|
38 | });
|
---|
39 | test('explicit options.rng produces expected result', () => {
|
---|
40 | const id = v4({ rng: () => randomBytesFixture });
|
---|
41 | assert.strictEqual(id, '109156be-c4fb-41ea-b1b4-efe1671c5836');
|
---|
42 | });
|
---|
43 | test('fills one UUID into a buffer as expected', () => {
|
---|
44 | const buffer = new Uint8Array(16);
|
---|
45 | const result = v4({ random: randomBytesFixture }, buffer);
|
---|
46 | assert.deepEqual(buffer, expectedBytes);
|
---|
47 | assert.strictEqual(buffer, result);
|
---|
48 | });
|
---|
49 | test('fills two UUIDs into a buffer as expected', () => {
|
---|
50 | const buffer = new Uint8Array(32);
|
---|
51 | v4({ random: randomBytesFixture }, buffer, 0);
|
---|
52 | v4({ random: randomBytesFixture }, buffer, 16);
|
---|
53 | const expectedBuf = new Uint8Array(32);
|
---|
54 | expectedBuf.set(expectedBytes);
|
---|
55 | expectedBuf.set(expectedBytes, 16);
|
---|
56 | assert.deepEqual(buffer, expectedBuf);
|
---|
57 | });
|
---|
58 | });
|
---|