From 098884808c70d9aec91ff7843e30d050476ce39c Mon Sep 17 00:00:00 2001 From: Quantum Date: Tue, 4 Dec 2018 19:49:47 -0500 Subject: [PATCH] Add some more unit tests --- src/generator.js | 11 ++++++--- tests/generator.js | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 3 deletions(-) create mode 100644 tests/generator.js diff --git a/src/generator.js b/src/generator.js index f912ed6..084767f 100644 --- a/src/generator.js +++ b/src/generator.js @@ -23,10 +23,15 @@ function pickWords (list, number) { return getWords(list, array) } -function pickChar (options) { +function getChar (choices, index) { + return choices[index % choices.length] +} + +function pickChar (choices) { const array = new Uint32Array(1) window.crypto.getRandomValues(array) - return options[array[0] % options.length] + const index = array[0] + return getChar(choices, index) } function generate (options) { @@ -61,5 +66,5 @@ function computeBits (options) { } module.exports = { - getWordList, getWords, capitalize, generate, lengthBits, computeBits + getWordList, getWords, capitalize, generate, getChar, lengthBits, computeBits } diff --git a/tests/generator.js b/tests/generator.js new file mode 100644 index 0000000..8991d2d --- /dev/null +++ b/tests/generator.js @@ -0,0 +1,59 @@ +const { getWordList, getWords, getChar, lengthBits } = require('../src/generator') +const words = require('../src/words') +const assert = require('assert').strict +const lists = ['small', 'medium', 'large'] + +describe('getWordList', () => { + lists.forEach(name => { + it(name, () => { + assert.equal(getWordList(name), words[name]) + }) + }) +}) + +describe('getWords', () => { + lists.forEach(name => { + it(`sanity: ${name}`, () => { + assert.deepEqual( + getWords(words[name], [0, 256, 1337, 2018]), + [words[name][0], words[name][256], words[name][1337], words[name][2018]] + ) + }) + }) + + lists.forEach(name => { + it(`all offsets: ${name}`, () => { + const len = words[name].length + ;[...Array(65536 / len)].forEach((_, i) => { + assert.deepEqual( + getWords(words[name], [i * len, i * len + 256, i * len + 1337, i * len + 2018]), + [words[name][0], words[name][256], words[name][1337], words[name][2018]] + ) + }) + }) + }) +}) + +describe('getChar', () => { + it('simple', () => { + const choices = ['0', '1', '2'] + assert.equal(getChar(choices, 0), '0') + assert.equal(getChar(choices, 1), '1') + assert.equal(getChar(choices, 2), '2') + assert.equal(getChar(choices, 3), '0') + assert.equal(getChar(choices, 4), '1') + assert.equal(getChar(choices, 5), '2') + }) +}) + +describe('lengthBits', () => { + it('simple', () => { + assert.equal(lengthBits(Array(1)), 0) + assert.equal(lengthBits(Array(2)), 1) + assert.equal(lengthBits(Array(4)), 2) + assert.equal(lengthBits(Array(1024)), 10) + assert.equal(lengthBits(Array(2048)), 11) + assert.equal(lengthBits(Array(4096)), 12) + assert.equal(lengthBits(Array(8192)), 13) + }) +})