Skip to content

Commit 772e907

Browse files
committed
fix(registar): add unit tests
1 parent ca3092b commit 772e907

File tree

2 files changed

+42
-6
lines changed

2 files changed

+42
-6
lines changed

more/registrar/registrar.js

+10-6
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,16 @@ function makeRegistrar(systemVersion, seed = 0) {
2424
const useCount = (useCounts.get(realName) || 0) + 1;
2525
useCounts.set(realName, useCount);
2626
const depth = Math.max(4, Math.floor(Math.log10(useCount) + 1.6));
27-
const uniqueString = sparseInts.next().value.toString();
28-
const keyString = uniqueString.slice(-depth).padStart(depth, '0');
29-
// console.log(`RAND ${useCount} ${uniqueString} ${keyString}`);
30-
const key = `${realName}_${keyString}`;
31-
// if it was a random keyString, then we need to detect collision
32-
insist(!contents.has(key), 'Generated name must not collide');
27+
28+
// Retry until we have a unique key.
29+
let key;
30+
do {
31+
const uniqueString = sparseInts.next().value.toString();
32+
const keyString = uniqueString.slice(-depth).padStart(depth, '0');
33+
// console.log(`RAND ${useCount} ${uniqueString} ${keyString}`);
34+
key = `${realName}_${keyString}`;
35+
} while (contents.has(key));
36+
3337
contents.set(key, value);
3438
return key;
3539
},
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { test } from 'tape-promise/tape';
2+
import { makeRegistrar } from '../../../../more/registrar/registrar';
3+
4+
test('Registrar creation', async t => {
5+
try {
6+
const registrarService = makeRegistrar('testnet');
7+
const obj1 = {};
8+
const obj2 = {};
9+
const id1 = registrarService.register('myname', obj1);
10+
t.assert(id1.match(/^myname_\d{4,}$/), 'id1 is correct format')
11+
const id2 = registrarService.register('myname', obj2);
12+
t.assert(id2.match(/^myname_\d{4,}$/), 'id2 is correct format')
13+
t.isNot(id2, id1, 'ids for different objects are different');
14+
const id1a = registrarService.register('myname', obj1);
15+
t.assert(id1a.match(/^myname_\d{4,}$/), 'id1a is correct format')
16+
t.isNot(id1a, id1, 'ids for same object are different');
17+
const id1b = registrarService.register('othername', obj1);
18+
t.assert(id1b.match(/^othername_\d{4,}$/), 'id1b is correct format')
19+
const ret1 = registrarService.get(id1);
20+
t.equals(ret1, obj1, 'returned obj1 is equal');
21+
const ret2 = registrarService.get(id2);
22+
t.equals(ret2, obj2, 'returned obj2 is equal');
23+
const ret1a = registrarService.get(id1a);
24+
t.equals(ret1a, obj1, 'returned obj1a is equal');
25+
const ret1b = registrarService.get(id1b);
26+
t.equals(ret1b, obj1, 'returned obj1b is equal');
27+
} catch (e) {
28+
t.isNot(e, e, 'unexpected exception');
29+
} finally {
30+
t.end();
31+
}
32+
});

0 commit comments

Comments
 (0)