diff options
author | Anna Henningsen <anna@addaleax.net> | 2018-09-05 17:32:34 +0200 |
---|---|---|
committer | Anna Henningsen <anna@addaleax.net> | 2018-09-24 22:19:08 +0200 |
commit | 1b274287c91fdd1c86d954b758569e2de7a43018 (patch) | |
tree | 8d386aec6a892289618e6c5308c8ab1007179b88 /test | |
parent | 06f6ac179c674bd5d2b26505327f64eaceeb7644 (diff) | |
download | android-node-v8-1b274287c91fdd1c86d954b758569e2de7a43018.tar.gz android-node-v8-1b274287c91fdd1c86d954b758569e2de7a43018.tar.bz2 android-node-v8-1b274287c91fdd1c86d954b758569e2de7a43018.zip |
test: add string-decoder fuzz test
PR-URL: https://github.com/nodejs/node/pull/22709
Fixes: https://github.com/nodejs/node/issues/22626
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Rich Trott <rtrott@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Diffstat (limited to 'test')
-rw-r--r-- | test/parallel/test-string-decoder-fuzz.js | 48 |
1 files changed, 48 insertions, 0 deletions
diff --git a/test/parallel/test-string-decoder-fuzz.js b/test/parallel/test-string-decoder-fuzz.js new file mode 100644 index 0000000000..d8d0188159 --- /dev/null +++ b/test/parallel/test-string-decoder-fuzz.js @@ -0,0 +1,48 @@ +'use strict'; +require('../common'); +const { StringDecoder } = require('string_decoder'); +const util = require('util'); +const assert = require('assert'); + +// Tests that, for random sequences of bytes, our StringDecoder gives the +// same result as a direction conversion using Buffer.toString(). +// In particular, it checks that StringDecoder aligns with V8’s own output. + +function rand(max) { + return Math.floor(Math.random() * max); +} + +function randBuf(maxLen) { + const buf = Buffer.allocUnsafe(rand(maxLen)); + for (let i = 0; i < buf.length; i++) + buf[i] = rand(256); + return buf; +} + +const encodings = [ + 'utf16le', 'utf8', 'ascii', 'hex', 'base64', 'latin1' +]; + +function runSingleFuzzTest() { + const enc = encodings[rand(encodings.length)]; + const sd = new StringDecoder(enc); + const bufs = []; + const strings = []; + + const N = rand(10); + for (let i = 0; i < N; ++i) { + const buf = randBuf(50); + bufs.push(buf); + strings.push(sd.write(buf)); + } + strings.push(sd.end()); + + assert.strictEqual(strings.join(''), Buffer.concat(bufs).toString(enc), + `Mismatch:\n${util.inspect(strings)}\n` + + util.inspect(bufs.map((buf) => buf.toString('hex'))) + + `\nfor encoding ${enc}`); +} + +const start = Date.now(); +while (Date.now() - start < 100) + runSingleFuzzTest(); |