diff --git a/more/registrar/registrar.js b/more/registrar/registrar.js index ed8db841fd6..2785c9bb6b3 100644 --- a/more/registrar/registrar.js +++ b/more/registrar/registrar.js @@ -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; }, diff --git a/test/unitTests/more/registrar/test-registrar.js b/test/unitTests/more/registrar/test-registrar.js new file mode 100644 index 00000000000..4072beb51ee --- /dev/null +++ b/test/unitTests/more/registrar/test-registrar.js @@ -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(); + } +});