Skip to content

Commit

Permalink
fix(registar): add unit tests
Browse files Browse the repository at this point in the history
  • Loading branch information
michaelfig committed Oct 22, 2019
1 parent ca3092b commit 772e907
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 6 deletions.
16 changes: 10 additions & 6 deletions more/registrar/registrar.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,16 @@ function makeRegistrar(systemVersion, seed = 0) {
const useCount = (useCounts.get(realName) || 0) + 1;
useCounts.set(realName, useCount);
const depth = Math.max(4, Math.floor(Math.log10(useCount) + 1.6));
const uniqueString = sparseInts.next().value.toString();
const keyString = uniqueString.slice(-depth).padStart(depth, '0');
// console.log(`RAND ${useCount} ${uniqueString} ${keyString}`);
const key = `${realName}_${keyString}`;
// if it was a random keyString, then we need to detect collision
insist(!contents.has(key), 'Generated name must not collide');

// Retry until we have a unique key.
let key;
do {
const uniqueString = sparseInts.next().value.toString();
const keyString = uniqueString.slice(-depth).padStart(depth, '0');
// console.log(`RAND ${useCount} ${uniqueString} ${keyString}`);
key = `${realName}_${keyString}`;
} while (contents.has(key));

contents.set(key, value);
return key;
},
Expand Down
32 changes: 32 additions & 0 deletions test/unitTests/more/registrar/test-registrar.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { test } from 'tape-promise/tape';
import { makeRegistrar } from '../../../../more/registrar/registrar';

test('Registrar creation', async t => {
try {
const registrarService = makeRegistrar('testnet');
const obj1 = {};
const obj2 = {};
const id1 = registrarService.register('myname', obj1);
t.assert(id1.match(/^myname_\d{4,}$/), 'id1 is correct format')
const id2 = registrarService.register('myname', obj2);
t.assert(id2.match(/^myname_\d{4,}$/), 'id2 is correct format')
t.isNot(id2, id1, 'ids for different objects are different');
const id1a = registrarService.register('myname', obj1);
t.assert(id1a.match(/^myname_\d{4,}$/), 'id1a is correct format')
t.isNot(id1a, id1, 'ids for same object are different');
const id1b = registrarService.register('othername', obj1);
t.assert(id1b.match(/^othername_\d{4,}$/), 'id1b is correct format')
const ret1 = registrarService.get(id1);
t.equals(ret1, obj1, 'returned obj1 is equal');
const ret2 = registrarService.get(id2);
t.equals(ret2, obj2, 'returned obj2 is equal');
const ret1a = registrarService.get(id1a);
t.equals(ret1a, obj1, 'returned obj1a is equal');
const ret1b = registrarService.get(id1b);
t.equals(ret1b, obj1, 'returned obj1b is equal');
} catch (e) {
t.isNot(e, e, 'unexpected exception');
} finally {
t.end();
}
});

0 comments on commit 772e907

Please sign in to comment.