From 08f4feb4ae896628f7cd336c5d0c32ac2aaa03c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tobias=20Nie=C3=9Fen?= Date: Thu, 19 Dec 2019 14:01:02 -0400 Subject: [PATCH] Improve coverage of lib/random.js --- lib/random.js | 3 +++ test/unit/random.js | 19 +++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/lib/random.js b/lib/random.js index 4e904d5..ce91568 100644 --- a/lib/random.js +++ b/lib/random.js @@ -16,6 +16,9 @@ function isIntegerTypedArray(o) { // Spec: https://www.w3.org/TR/WebCryptoAPI/#dfn-Crypto-method-getRandomValues module.exports.getRandomValues = (array) => { + if (!ArrayBuffer.isView(array)) + throw new TypeError(); + if (!isIntegerTypedArray(array)) throw new TypeMismatchError(); diff --git a/test/unit/random.js b/test/unit/random.js index ad9f80c..9df032c 100644 --- a/test/unit/random.js +++ b/test/unit/random.js @@ -25,4 +25,23 @@ describe('crypto.getRandomBytes', () => { const buf2 = getRandomValues(Buffer.alloc(1024)); assert(!buf1.equals(buf2)); }); + + it('should throw if the input is invalid', () => { + for (const notAnArrayBufferView of [undefined, null, 5, 'foo']) { + assert.throws(() => { + getRandomValues(notAnArrayBufferView); + }, /TypeError/); + } + + const buf = new ArrayBuffer(65544); + for (const View of [Float32Array, Float64Array]) { + assert.throws(() => { + getRandomValues(new View(buf)); + }, /TypeMismatchError/); + } + + assert.throws(() => { + getRandomValues(new Uint32Array(buf)); + }, /QuotaExceededError/); + }); });