diff --git a/benchmark/function_args.js b/benchmark/function_args.js index e7fb6636f..fdc9b8c2a 100644 --- a/benchmark/function_args.js +++ b/benchmark/function_args.js @@ -2,7 +2,7 @@ const path = require('path'); const Benchmark = require('benchmark'); const addonName = path.basename(__filename, '.js'); -[ addonName, addonName + '_noexcept' ] +[addonName, addonName + '_noexcept'] .forEach((addonName) => { const rootAddon = require('bindings')({ bindings: addonName, @@ -20,7 +20,7 @@ const addonName = path.basename(__filename, '.js'); implems.reduce((suite, implem) => { const fn = rootAddon[implem].noArgFunction; return suite.add(implem.padStart(maxNameLength, ' '), () => fn()); - }, new Benchmark.Suite) + }, new Benchmark.Suite()) .on('cycle', (event) => console.log(String(event.target))) .run(); @@ -28,7 +28,7 @@ const addonName = path.basename(__filename, '.js'); implems.reduce((suite, implem) => { const fn = rootAddon[implem].oneArgFunction; return suite.add(implem.padStart(maxNameLength, ' '), () => fn('x')); - }, new Benchmark.Suite) + }, new Benchmark.Suite()) .on('cycle', (event) => console.log(String(event.target))) .run(); @@ -36,7 +36,7 @@ const addonName = path.basename(__filename, '.js'); implems.reduce((suite, implem) => { const fn = rootAddon[implem].twoArgFunction; return suite.add(implem.padStart(maxNameLength, ' '), () => fn('x', 12)); - }, new Benchmark.Suite) + }, new Benchmark.Suite()) .on('cycle', (event) => console.log(String(event.target))) .run(); @@ -45,7 +45,7 @@ const addonName = path.basename(__filename, '.js'); const fn = rootAddon[implem].threeArgFunction; return suite.add(implem.padStart(maxNameLength, ' '), () => fn('x', 12, true)); - }, new Benchmark.Suite) + }, new Benchmark.Suite()) .on('cycle', (event) => console.log(String(event.target))) .run(); @@ -54,7 +54,7 @@ const addonName = path.basename(__filename, '.js'); const fn = rootAddon[implem].fourArgFunction; return suite.add(implem.padStart(maxNameLength, ' '), () => fn('x', 12, true, anObject)); - }, new Benchmark.Suite) + }, new Benchmark.Suite()) .on('cycle', (event) => console.log(String(event.target))) .run(); }); diff --git a/benchmark/index.js b/benchmark/index.js index e4c7391b1..e03d34420 100644 --- a/benchmark/index.js +++ b/benchmark/index.js @@ -6,7 +6,7 @@ const path = require('path'); let benchmarks = []; -if (!!process.env.npm_config_benchmarks) { +if (process.env.npm_config_benchmarks) { benchmarks = process.env.npm_config_benchmarks .split(';') .map((item) => (item + '.js')); diff --git a/benchmark/property_descriptor.js b/benchmark/property_descriptor.js index 848aaaf4a..d1e1f40a5 100644 --- a/benchmark/property_descriptor.js +++ b/benchmark/property_descriptor.js @@ -2,15 +2,15 @@ const path = require('path'); const Benchmark = require('benchmark'); const addonName = path.basename(__filename, '.js'); -[ addonName, addonName + '_noexcept' ] +[addonName, addonName + '_noexcept'] .forEach((addonName) => { const rootAddon = require('bindings')({ bindings: addonName, module_root: __dirname }); delete rootAddon.path; - const getters = new Benchmark.Suite; - const setters = new Benchmark.Suite; + const getters = new Benchmark.Suite(); + const setters = new Benchmark.Suite(); const maxNameLength = Object.keys(rootAddon) .reduce((soFar, value) => Math.max(soFar, value.length), 0); @@ -22,7 +22,7 @@ const addonName = path.basename(__filename, '.js'); }); setters.add(`${key} setter`.padStart(maxNameLength + 7), () => { rootAddon[key] = 5; - }) + }); }); getters diff --git a/test/addon.js b/test/addon.js index b9fca2f15..78abaf6f7 100644 --- a/test/addon.js +++ b/test/addon.js @@ -4,7 +4,7 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { assert.strictEqual(binding.addon.increment(), 43); assert.strictEqual(binding.addon.increment(), 44); assert.strictEqual(binding.addon.subObject.decrement(), 43); diff --git a/test/addon_build/index.js b/test/addon_build/index.js index c410bf3a8..49ccfe294 100644 --- a/test/addon_build/index.js +++ b/test/addon_build/index.js @@ -4,28 +4,28 @@ const { promisify } = require('util'); const exec = promisify(require('child_process').exec); const { copy, remove } = require('fs-extra'); const path = require('path'); -const assert = require('assert') +const assert = require('assert'); const ADDONS_FOLDER = path.join(__dirname, 'addons'); const addons = [ 'echo addon', 'echo-addon' -] +]; -async function beforeAll(addons) { - console.log(' >Preparing native addons to build') +async function beforeAll (addons) { + console.log(' >Preparing native addons to build'); for (const addon of addons) { await remove(path.join(ADDONS_FOLDER, addon)); await copy(path.join(__dirname, 'tpl'), path.join(ADDONS_FOLDER, addon)); } } -async function test(addon) { +async function test (addon) { console.log(` >Building addon: '${addon}'`); const { stderr, stdout } = await exec('npm install', { cwd: path.join(ADDONS_FOLDER, addon) - }) + }); console.log(` >Running test for: '${addon}'`); // Disabled the checks on stderr and stdout because of this issue on npm: // Stop using process.umask(): https://github.com/npm/cli/issues/1103 @@ -41,9 +41,9 @@ async function test(addon) { assert.strictEqual(binding.noexcept.echo(103), 103); } -module.exports = (async function() { +module.exports = (async function () { await beforeAll(addons); for (const addon of addons) { await test(addon); } -})() +})(); diff --git a/test/addon_build/tpl/index.js b/test/addon_build/tpl/index.js index b534b1997..566656ad8 100644 --- a/test/addon_build/tpl/index.js +++ b/test/addon_build/tpl/index.js @@ -1,9 +1,9 @@ -'use strict' +'use strict'; -const except = require('bindings')('addon') -const noexcept = require('bindings')('addon_noexcept') +const except = require('bindings')('addon'); +const noexcept = require('bindings')('addon_noexcept'); module.exports = { except, noexcept -} +}; diff --git a/test/addon_data.js b/test/addon_data.js index 1762d9663..6fdbdd977 100644 --- a/test/addon_data.js +++ b/test/addon_data.js @@ -8,7 +8,7 @@ module.exports = require('./common').runTestWithBindingPath(test); // Make sure the instance data finalizer is called at process exit. If the hint // is non-zero, it will be printed out by the child process. -function testFinalizer(bindingName, hint, expected) { +function testFinalizer (bindingName, hint, expected) { return new Promise((resolve) => { bindingName = bindingName.split('\\').join('\\\\'); const child = spawn(process.execPath, [ @@ -30,7 +30,7 @@ function testFinalizer(bindingName, hint, expected) { }); } -async function test(bindingName) { +async function test (bindingName) { const binding = require(bindingName).addon_data(0); // Make sure it is possible to get/set instance data. @@ -42,5 +42,5 @@ async function test(bindingName) { await testFinalizer(bindingName, 0, ['addon_data: Addon::~Addon']); await testFinalizer(bindingName, 42, - ['addon_data: Addon::~Addon', 'hint: 42']); + ['addon_data: Addon::~Addon', 'hint: 42']); } diff --git a/test/array_buffer.js b/test/array_buffer.js index 942686f2f..3e69b6836 100644 --- a/test/array_buffer.js +++ b/test/array_buffer.js @@ -5,7 +5,7 @@ const testUtil = require('./testUtil'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { return testUtil.runGCTests([ 'Internal ArrayBuffer', () => { @@ -64,6 +64,6 @@ function test(binding) { // Let C++ detach the ArrayBuffer. const extBuffer = binding.arraybuffer.createExternalBuffer(); binding.arraybuffer.checkDetachUpdatesData(extBuffer); - }, + } ]); } diff --git a/test/async_context.js b/test/async_context.js index d6a3fc5aa..7b1b580a6 100644 --- a/test/async_context.js +++ b/test/async_context.js @@ -5,9 +5,9 @@ const common = require('./common'); // we only check async hooks on 8.x an higher were // they are closer to working properly -const nodeVersion = process.versions.node.split('.')[0] -let async_hooks = undefined; -function checkAsyncHooks() { +const nodeVersion = process.versions.node.split('.')[0]; +let async_hooks; +function checkAsyncHooks () { if (nodeVersion >= 8) { if (async_hooks == undefined) { async_hooks = require('async_hooks'); @@ -19,7 +19,7 @@ function checkAsyncHooks() { module.exports = common.runTest(test); -function installAsyncHooksForTest() { +function installAsyncHooksForTest () { return new Promise((resolve, reject) => { let id; const events = []; @@ -38,23 +38,23 @@ function installAsyncHooksForTest() { }, 10); hook = async_hooks.createHook({ - init(asyncId, type, triggerAsyncId, resource) { + init (asyncId, type, triggerAsyncId, resource) { if (id === undefined && type === 'async_context_test') { id = asyncId; events.push({ eventName: 'init', type, triggerAsyncId, resource }); } }, - before(asyncId) { + before (asyncId) { if (asyncId === id) { events.push({ eventName: 'before' }); } }, - after(asyncId) { + after (asyncId) { if (asyncId === id) { events.push({ eventName: 'after' }); } }, - destroy(asyncId) { + destroy (asyncId) { if (asyncId === id) { events.push({ eventName: 'destroy' }); destroyed = true; @@ -64,7 +64,7 @@ function installAsyncHooksForTest() { }); } -function test(binding) { +function test (binding) { if (!checkAsyncHooks()) { return; } @@ -73,14 +73,16 @@ function test(binding) { const triggerAsyncId = async_hooks.executionAsyncId(); binding.asynccontext.makeCallback(common.mustCall(), { foo: 'foo' }); return hooks.then(actual => { - assert.deepStrictEqual(actual, [ - { eventName: 'init', - type: 'async_context_test', - triggerAsyncId: triggerAsyncId, - resource: { foo: 'foo' } }, - { eventName: 'before' }, - { eventName: 'after' }, - { eventName: 'destroy' } - ]); + assert.deepStrictEqual(actual, [ + { + eventName: 'init', + type: 'async_context_test', + triggerAsyncId: triggerAsyncId, + resource: { foo: 'foo' } + }, + { eventName: 'before' }, + { eventName: 'after' }, + { eventName: 'destroy' } + ]); }).catch(common.mustNotCall()); } diff --git a/test/async_progress_queue_worker.js b/test/async_progress_queue_worker.js index e7150012d..14ac31cc2 100644 --- a/test/async_progress_queue_worker.js +++ b/test/async_progress_queue_worker.js @@ -1,16 +1,16 @@ 'use strict'; -const common = require('./common') +const common = require('./common'); const assert = require('assert'); module.exports = common.runTest(test); -async function test({ asyncprogressqueueworker }) { +async function test ({ asyncprogressqueueworker }) { await success(asyncprogressqueueworker); await fail(asyncprogressqueueworker); } -function success(binding) { +function success (binding) { return new Promise((resolve, reject) => { const expected = [0, 1, 2, 3]; const actual = []; @@ -32,11 +32,11 @@ function success(binding) { }); } -function fail(binding) { +function fail (binding) { return new Promise((resolve, reject) => { const worker = binding.createWork(-1, common.mustCall((err) => { - assert.throws(() => { throw err }, /test error/); + assert.throws(() => { throw err; }, /test error/); resolve(); }), common.mustNotCall() diff --git a/test/async_progress_worker.js b/test/async_progress_worker.js index 2a81b204d..5e9940516 100644 --- a/test/async_progress_worker.js +++ b/test/async_progress_worker.js @@ -1,17 +1,17 @@ 'use strict'; -const common = require('./common') +const common = require('./common'); const assert = require('assert'); module.exports = common.runTest(test); -async function test({ asyncprogressworker }) { +async function test ({ asyncprogressworker }) { await success(asyncprogressworker); await fail(asyncprogressworker); await malignTest(asyncprogressworker); } -function success(binding) { +function success (binding) { return new Promise((resolve, reject) => { const expected = [0, 1, 2, 3]; const actual = []; @@ -32,11 +32,11 @@ function success(binding) { }); } -function fail(binding) { +function fail (binding) { return new Promise((resolve) => { binding.doWork(-1, common.mustCall((err) => { - assert.throws(() => { throw err }, /test error/) + assert.throws(() => { throw err; }, /test error/); resolve(); }), common.mustNotCall() @@ -44,7 +44,7 @@ function fail(binding) { }); } -function malignTest(binding) { +function malignTest (binding) { return new Promise((resolve, reject) => { binding.doMalignTest( common.mustCall((err) => { diff --git a/test/async_worker.js b/test/async_worker.js index 46ab14340..e94802e7e 100644 --- a/test/async_worker.js +++ b/test/async_worker.js @@ -4,10 +4,10 @@ const common = require('./common'); // we only check async hooks on 8.x an higher were // they are closer to working properly -const nodeVersion = process.versions.node.split('.')[0] -let async_hooks = undefined; -function checkAsyncHooks() { - if (nodeVersion >=8) { +const nodeVersion = process.versions.node.split('.')[0]; +let async_hooks; +function checkAsyncHooks () { + if (nodeVersion >= 8) { if (async_hooks == undefined) { async_hooks = require('async_hooks'); } @@ -18,7 +18,7 @@ function checkAsyncHooks() { module.exports = common.runTest(test); -function installAsyncHooksForTest() { +function installAsyncHooksForTest () { return new Promise((resolve, reject) => { let id; const events = []; @@ -26,34 +26,34 @@ function installAsyncHooksForTest() { * TODO(legendecas): investigate why resolving & disabling hooks in * destroy callback causing crash with case 'callbackscope.js'. */ - let hook; - let destroyed = false; - const interval = setInterval(() => { - if (destroyed) { - hook.disable(); - clearInterval(interval); - resolve(events); - } - }, 10); + let hook; + let destroyed = false; + const interval = setInterval(() => { + if (destroyed) { + hook.disable(); + clearInterval(interval); + resolve(events); + } + }, 10); hook = async_hooks.createHook({ - init(asyncId, type, triggerAsyncId, resource) { + init (asyncId, type, triggerAsyncId, resource) { if (id === undefined && type === 'TestResource') { id = asyncId; events.push({ eventName: 'init', type, triggerAsyncId, resource }); } }, - before(asyncId) { + before (asyncId) { if (asyncId === id) { events.push({ eventName: 'before' }); } }, - after(asyncId) { + after (asyncId) { if (asyncId === id) { events.push({ eventName: 'after' }); } }, - destroy(asyncId) { + destroy (asyncId) { if (asyncId === id) { events.push({ eventName: 'destroy' }); destroyed = true; @@ -63,7 +63,7 @@ function installAsyncHooksForTest() { }); } -async function test(binding) { +async function test (binding) { if (!checkAsyncHooks()) { await new Promise((resolve) => { binding.asyncworker.doWork(true, {}, function (e) { @@ -88,7 +88,7 @@ async function test(binding) { binding.asyncworker.doWorkWithResult(true, {}, function (succeed, succeedString) { assert(arguments.length == 2); assert(succeed); - assert(succeedString == "ok"); + assert(succeedString == 'ok'); assert.strictEqual(typeof this, 'object'); assert.strictEqual(this.data, 'test data'); resolve(); @@ -112,10 +112,12 @@ async function test(binding) { await hooks.then(actual => { assert.deepStrictEqual(actual, [ - { eventName: 'init', + { + eventName: 'init', type: 'TestResource', triggerAsyncId: triggerAsyncId, - resource: { foo: 'foo' } }, + resource: { foo: 'foo' } + }, { eventName: 'before' }, { eventName: 'after' }, { eventName: 'destroy' } @@ -131,7 +133,7 @@ async function test(binding) { function (succeed, succeedString) { assert(arguments.length == 2); assert(succeed); - assert(succeedString == "ok"); + assert(succeedString == 'ok'); assert.strictEqual(typeof this, 'object'); assert.strictEqual(this.data, 'test data'); resolve(); @@ -140,10 +142,12 @@ async function test(binding) { await hooks.then(actual => { assert.deepStrictEqual(actual, [ - { eventName: 'init', + { + eventName: 'init', type: 'TestResource', triggerAsyncId: triggerAsyncId, - resource: { foo: 'foo' } }, + resource: { foo: 'foo' } + }, { eventName: 'before' }, { eventName: 'after' }, { eventName: 'destroy' } @@ -166,10 +170,12 @@ async function test(binding) { await hooks.then(actual => { assert.deepStrictEqual(actual, [ - { eventName: 'init', + { + eventName: 'init', type: 'TestResource', triggerAsyncId: triggerAsyncId, - resource: { foo: 'foo' } }, + resource: { foo: 'foo' } + }, { eventName: 'before' }, { eventName: 'after' }, { eventName: 'destroy' } diff --git a/test/async_worker_nocallback.js b/test/async_worker_nocallback.js index d4e28ce6a..8e357772f 100644 --- a/test/async_worker_nocallback.js +++ b/test/async_worker_nocallback.js @@ -4,7 +4,7 @@ const common = require('./common'); module.exports = common.runTest(test); -async function test(binding) { +async function test (binding) { await binding.asyncworker.doWorkNoCallback(true, {}) .then(common.mustCall()).catch(common.mustNotCall()); diff --git a/test/async_worker_persistent.js b/test/async_worker_persistent.js index f4febac45..d3ce11e23 100644 --- a/test/async_worker_persistent.js +++ b/test/async_worker_persistent.js @@ -2,11 +2,11 @@ const assert = require('assert'); -function test(binding, succeed) { +function test (binding, succeed) { return new Promise((resolve) => // Can't pass an arrow function to doWork because that results in an // undefined context inside its body when the function gets called. - binding.doWork(succeed, function(e) { + binding.doWork(succeed, function (e) { setImmediate(() => { // If the work is supposed to fail, make sure there's an error. assert.strictEqual(succeed || e.message === 'test error', true); diff --git a/test/basic_types/array.js b/test/basic_types/array.js index a3e569453..a4bb69a66 100644 --- a/test/basic_types/array.js +++ b/test/basic_types/array.js @@ -3,8 +3,7 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - +function test (binding) { // create empty array const array = binding.basic_types_array.createArray(); assert.strictEqual(binding.basic_types_array.getLength(array), 0); @@ -15,7 +14,7 @@ function test(binding) { // set function test binding.basic_types_array.set(array, 0, 10); - binding.basic_types_array.set(array, 1, "test"); + binding.basic_types_array.set(array, 1, 'test'); binding.basic_types_array.set(array, 2, 3.0); // check length after set data @@ -23,7 +22,7 @@ function test(binding) { // get function test assert.strictEqual(binding.basic_types_array.get(array, 0), 10); - assert.strictEqual(binding.basic_types_array.get(array, 1), "test"); + assert.strictEqual(binding.basic_types_array.get(array, 1), 'test'); assert.strictEqual(binding.basic_types_array.get(array, 2), 3.0); // overwrite test diff --git a/test/basic_types/boolean.js b/test/basic_types/boolean.js index 04f38e56e..61f005ef9 100644 --- a/test/basic_types/boolean.js +++ b/test/basic_types/boolean.js @@ -4,7 +4,7 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { +function test (binding) { const bool1 = binding.basic_types_boolean.createBoolean(true); assert.strictEqual(bool1, true); @@ -31,5 +31,4 @@ function test(binding) { const bool8 = binding.basic_types_boolean.operatorBool(false); assert.strictEqual(bool8, false); - } diff --git a/test/basic_types/number.js b/test/basic_types/number.js index 592b6ada0..6c0113f14 100644 --- a/test/basic_types/number.js +++ b/test/basic_types/number.js @@ -4,7 +4,7 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { +function test (binding) { const MIN_INT32 = -2147483648; const MAX_INT32 = 2147483647; const MIN_UINT32 = 0; @@ -16,9 +16,9 @@ function test(binding) { const MIN_DOUBLE = binding.basic_types_number.minDouble(); const MAX_DOUBLE = binding.basic_types_number.maxDouble(); - function randomRangeTestForInteger(min, max, converter) { - for (let i = min; i < max; i+= Math.floor(Math.random() * max / 100)) { - assert.strictEqual(i, converter(i)); + function randomRangeTestForInteger (min, max, converter) { + for (let i = min; i < max; i += Math.floor(Math.random() * max / 100)) { + assert.strictEqual(i, converter(i)); } } @@ -96,19 +96,19 @@ function test(binding) { // Construction test { -    assert.strictEqual(binding.basic_types_number.createEmptyNumber(), true); -    randomRangeTestForInteger(MIN_INT32, MAX_INT32, binding.basic_types_number.createNumberFromExistingValue); -    assert.strictEqual(MIN_INT32, binding.basic_types_number.createNumberFromExistingValue(MIN_INT32)); -    assert.strictEqual(MAX_INT32, binding.basic_types_number.createNumberFromExistingValue(MAX_INT32)); -    randomRangeTestForInteger(MIN_UINT32, MAX_UINT32, binding.basic_types_number.createNumberFromExistingValue); -    assert.strictEqual(MIN_UINT32, binding.basic_types_number.createNumberFromExistingValue(MIN_UINT32)); -    assert.strictEqual(MAX_UINT32, binding.basic_types_number.createNumberFromExistingValue(MAX_UINT32)); -    randomRangeTestForInteger(MIN_INT64, MAX_INT64, binding.basic_types_number.createNumberFromExistingValue); -    assert.strictEqual(MIN_INT64, binding.basic_types_number.createNumberFromExistingValue(MIN_INT64)); -    assert.strictEqual(MAX_INT64, binding.basic_types_number.createNumberFromExistingValue(MAX_INT64)); -    assert.strictEqual(MIN_FLOAT, binding.basic_types_number.createNumberFromExistingValue(MIN_FLOAT)); -    assert.strictEqual(MAX_FLOAT, binding.basic_types_number.createNumberFromExistingValue(MAX_FLOAT)); -    assert.strictEqual(MIN_DOUBLE, binding.basic_types_number.createNumberFromExistingValue(MIN_DOUBLE)); -    assert.strictEqual(MAX_DOUBLE, binding.basic_types_number.createNumberFromExistingValue(MAX_DOUBLE)); + assert.strictEqual(binding.basic_types_number.createEmptyNumber(), true); + randomRangeTestForInteger(MIN_INT32, MAX_INT32, binding.basic_types_number.createNumberFromExistingValue); + assert.strictEqual(MIN_INT32, binding.basic_types_number.createNumberFromExistingValue(MIN_INT32)); + assert.strictEqual(MAX_INT32, binding.basic_types_number.createNumberFromExistingValue(MAX_INT32)); + randomRangeTestForInteger(MIN_UINT32, MAX_UINT32, binding.basic_types_number.createNumberFromExistingValue); + assert.strictEqual(MIN_UINT32, binding.basic_types_number.createNumberFromExistingValue(MIN_UINT32)); + assert.strictEqual(MAX_UINT32, binding.basic_types_number.createNumberFromExistingValue(MAX_UINT32)); + randomRangeTestForInteger(MIN_INT64, MAX_INT64, binding.basic_types_number.createNumberFromExistingValue); + assert.strictEqual(MIN_INT64, binding.basic_types_number.createNumberFromExistingValue(MIN_INT64)); + assert.strictEqual(MAX_INT64, binding.basic_types_number.createNumberFromExistingValue(MAX_INT64)); + assert.strictEqual(MIN_FLOAT, binding.basic_types_number.createNumberFromExistingValue(MIN_FLOAT)); + assert.strictEqual(MAX_FLOAT, binding.basic_types_number.createNumberFromExistingValue(MAX_FLOAT)); + assert.strictEqual(MIN_DOUBLE, binding.basic_types_number.createNumberFromExistingValue(MIN_DOUBLE)); + assert.strictEqual(MAX_DOUBLE, binding.basic_types_number.createNumberFromExistingValue(MAX_DOUBLE)); } } diff --git a/test/basic_types/value.js b/test/basic_types/value.js index 81a95cb02..984a19fea 100644 --- a/test/basic_types/value.js +++ b/test/basic_types/value.js @@ -4,33 +4,27 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { +function test (binding) { const externalValue = binding.basic_types_value.createExternal(); - function isObject(value) { + function isObject (value) { return (typeof value === 'object' && value !== externalValue) || (typeof value === 'function'); } - function detailedTypeOf(value) { + function detailedTypeOf (value) { const type = typeof value; - if (type !== 'object') - return type; + if (type !== 'object') { return type; } - if (value === null) - return 'null'; + if (value === null) { return 'null'; } - if (Array.isArray(value)) - return 'array'; + if (Array.isArray(value)) { return 'array'; } - if (value === externalValue) - return 'external'; + if (value === externalValue) { return 'external'; } - if (!value.constructor) - return type; + if (!value.constructor) { return type; } - if (value instanceof ArrayBuffer) - return 'arraybuffer'; + if (value instanceof ArrayBuffer) { return 'arraybuffer'; } if (ArrayBuffer.isView(value)) { if (value instanceof DataView) { @@ -40,13 +34,12 @@ function test(binding) { } } - if (value instanceof Promise) - return 'promise'; + if (value instanceof Promise) { return 'promise'; } return 'object'; } - function typeCheckerTest(typeChecker, expectedType) { + function typeCheckerTest (typeChecker, expectedType) { const testValueList = [ undefined, null, @@ -58,7 +51,7 @@ function test(binding) { new ArrayBuffer(10), new Int32Array(new ArrayBuffer(12)), {}, - function() {}, + function () {}, new Promise((resolve, reject) => {}), new DataView(new ArrayBuffer(12)), externalValue @@ -73,7 +66,7 @@ function test(binding) { }); } - function typeConverterTest(typeConverter, expectedType) { + function typeConverterTest (typeConverter, expectedType) { const testValueList = [ true, false, @@ -84,7 +77,7 @@ function test(binding) { new ArrayBuffer(10), new Int32Array(new ArrayBuffer(12)), {}, - function() {}, + function () {}, new Promise((resolve, reject) => {}) ]; diff --git a/test/bigint.js b/test/bigint.js index bc27d9501..3406b131e 100644 --- a/test/bigint.js +++ b/test/bigint.js @@ -4,13 +4,13 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { const { TestInt64, TestUint64, TestWords, IsLossless, - TestTooBigBigInt, + TestTooBigBigInt } = binding.bigint; [ @@ -24,7 +24,7 @@ function test(binding) { 986583n, -976675n, 98765432213456789876546896323445679887645323232436587988766545658n, - -4350987086545760976737453646576078997096876957864353245245769809n, + -4350987086545760976737453646576078997096876957864353245245769809n ].forEach((num) => { if (num > -(2n ** 63n) && num < 2n ** 63n) { assert.strictEqual(TestInt64(num), num); @@ -45,6 +45,6 @@ function test(binding) { assert.throws(TestTooBigBigInt, { name: /^(RangeError|Error)$/, - message: /^(Maximum BigInt size exceeded|Invalid argument)$/, + message: /^(Maximum BigInt size exceeded|Invalid argument)$/ }); } diff --git a/test/buffer.js b/test/buffer.js index 9ff5ec1be..8b915bea9 100644 --- a/test/buffer.js +++ b/test/buffer.js @@ -6,7 +6,7 @@ const safeBuffer = require('safe-buffer'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { return testUtil.runGCTests([ 'Internal Buffer', () => { @@ -34,8 +34,8 @@ function test(binding) { assert.strictEqual(0, binding.buffer.getFinalizeCount()); }, () => { - global.gc(); - assert.strictEqual(0, binding.buffer.getFinalizeCount()); + global.gc(); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); }, 'External Buffer with finalizer', @@ -46,24 +46,24 @@ function test(binding) { assert.strictEqual(0, binding.buffer.getFinalizeCount()); }, () => { - global.gc(); + global.gc(); }, () => { - assert.strictEqual(1, binding.buffer.getFinalizeCount()); + assert.strictEqual(1, binding.buffer.getFinalizeCount()); }, 'External Buffer with finalizer hint', () => { - const test = binding.buffer.createExternalBufferWithFinalizeHint(); - binding.buffer.checkBuffer(test); - assert.ok(test instanceof Buffer); - assert.strictEqual(0, binding.buffer.getFinalizeCount()); + const test = binding.buffer.createExternalBufferWithFinalizeHint(); + binding.buffer.checkBuffer(test); + assert.ok(test instanceof Buffer); + assert.strictEqual(0, binding.buffer.getFinalizeCount()); }, () => { - global.gc(); + global.gc(); }, () => { - assert.strictEqual(1, binding.buffer.getFinalizeCount()); - }, + assert.strictEqual(1, binding.buffer.getFinalizeCount()); + } ]); } diff --git a/test/callbackscope.js b/test/callbackscope.js index 739648202..4dd6083cb 100644 --- a/test/callbackscope.js +++ b/test/callbackscope.js @@ -3,9 +3,9 @@ const assert = require('assert'); // we only check async hooks on 8.x an higher were // they are closer to working properly -const nodeVersion = process.versions.node.split('.')[0] -let async_hooks = undefined; -function checkAsyncHooks() { +const nodeVersion = process.versions.node.split('.')[0]; +let async_hooks; +function checkAsyncHooks () { if (nodeVersion >= 8) { if (async_hooks == undefined) { async_hooks = require('async_hooks'); @@ -17,30 +17,27 @@ function checkAsyncHooks() { module.exports = require('./common').runTest(test); -function test(binding) { - if (!checkAsyncHooks()) - return; +function test (binding) { + if (!checkAsyncHooks()) { return; } let id; let insideHook = false; const hook = async_hooks.createHook({ - init(asyncId, type, triggerAsyncId, resource) { + init (asyncId, type, triggerAsyncId, resource) { if (id === undefined && type === 'callback_scope_test') { id = asyncId; } }, - before(asyncId) { - if (asyncId === id) - insideHook = true; + before (asyncId) { + if (asyncId === id) { insideHook = true; } }, - after(asyncId) { - if (asyncId === id) - insideHook = false; + after (asyncId) { + if (asyncId === id) { insideHook = false; } } }).enable(); return new Promise(resolve => { - binding.callbackscope.runInCallbackScope(function() { + binding.callbackscope.runInCallbackScope(function () { assert(insideHook); hook.disable(); resolve(); diff --git a/test/common/index.js b/test/common/index.js index 9f29c07a7..90d02b108 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -7,10 +7,10 @@ const noop = () => {}; const mustCallChecks = []; -function runCallChecks(exitCode) { +function runCallChecks (exitCode) { if (exitCode !== 0) return; - const failed = mustCallChecks.filter(function(context) { + const failed = mustCallChecks.filter(function (context) { if ('minimum' in context) { context.messageSegment = `at least ${context.minimum}`; return context.actual < context.minimum; @@ -20,25 +20,25 @@ function runCallChecks(exitCode) { } }); - failed.forEach(function(context) { + failed.forEach(function (context) { console.log('Mismatched %s function calls. Expected %s, actual %d.', - context.name, - context.messageSegment, - context.actual); + context.name, + context.messageSegment, + context.actual); console.log(context.stack.split('\n').slice(2).join('\n')); }); if (failed.length) process.exit(1); } -exports.mustCall = function(fn, exact) { +exports.mustCall = function (fn, exact) { return _mustCallInner(fn, exact, 'exact'); }; -exports.mustCallAtLeast = function(fn, minimum) { +exports.mustCallAtLeast = function (fn, minimum) { return _mustCallInner(fn, minimum, 'minimum'); }; -function _mustCallInner(fn, criteria, field) { +function _mustCallInner (fn, criteria, field) { if (typeof fn === 'number') { criteria = fn; fn = noop; @@ -49,8 +49,7 @@ function _mustCallInner(fn, criteria, field) { criteria = 1; } - if (typeof criteria !== 'number') - throw new TypeError(`Invalid ${field} value: ${criteria}`); + if (typeof criteria !== 'number') { throw new TypeError(`Invalid ${field} value: ${criteria}`); } const context = { [field]: criteria, @@ -64,50 +63,50 @@ function _mustCallInner(fn, criteria, field) { mustCallChecks.push(context); - return function() { + return function () { context.actual++; return fn.apply(this, arguments); }; } -exports.mustNotCall = function(msg) { - return function mustNotCall() { +exports.mustNotCall = function (msg) { + return function mustNotCall () { assert.fail(msg || 'function should not have been called'); }; }; -exports.runTest = async function(test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { +exports.runTest = async function (test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { buildType = buildType || process.config.target_defaults.default_configuration || 'Release'; const bindings = [ path.join(buildPathRoot, `../build/${buildType}/binding.node`), path.join(buildPathRoot, `../build/${buildType}/binding_noexcept.node`), - path.join(buildPathRoot, `../build/${buildType}/binding_noexcept_maybe.node`), + path.join(buildPathRoot, `../build/${buildType}/binding_noexcept_maybe.node`) ].map(it => require.resolve(it)); for (const item of bindings) { await Promise.resolve(test(require(item))) .finally(exports.mustCall()); } -} +}; -exports.runTestWithBindingPath = async function(test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { +exports.runTestWithBindingPath = async function (test, buildType, buildPathRoot = process.env.BUILD_PATH || '') { buildType = buildType || process.config.target_defaults.default_configuration || 'Release'; const bindings = [ path.join(buildPathRoot, `../build/${buildType}/binding.node`), path.join(buildPathRoot, `../build/${buildType}/binding_noexcept.node`), - path.join(buildPathRoot, `../build/${buildType}/binding_noexcept_maybe.node`), + path.join(buildPathRoot, `../build/${buildType}/binding_noexcept_maybe.node`) ].map(it => require.resolve(it)); for (const item of bindings) { await test(item); } -} +}; -exports.runTestWithBuildType = async function(test, buildType) { +exports.runTestWithBuildType = async function (test, buildType) { buildType = buildType || process.config.target_defaults.default_configuration || 'Release'; - await Promise.resolve(test(buildType)) - .finally(exports.mustCall()); -} + await Promise.resolve(test(buildType)) + .finally(exports.mustCall()); +}; diff --git a/test/dataview/dataview.js b/test/dataview/dataview.js index 1d476c44d..595612856 100644 --- a/test/dataview/dataview.js +++ b/test/dataview/dataview.js @@ -3,18 +3,18 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function testDataViewCreation(factory, arrayBuffer, offset, length) { +function test (binding) { + function testDataViewCreation (factory, arrayBuffer, offset, length) { const view = factory(arrayBuffer, offset, length); - offset = offset ? offset : 0; + offset = offset || 0; assert.ok(dataview.getArrayBuffer(view) instanceof ArrayBuffer); assert.strictEqual(dataview.getArrayBuffer(view), arrayBuffer); assert.strictEqual(dataview.getByteOffset(view), offset); assert.strictEqual(dataview.getByteLength(view), - length ? length : arrayBuffer.byteLength - offset); + length || arrayBuffer.byteLength - offset); } - function testInvalidRange(factory, arrayBuffer, offset, length) { + function testInvalidRange (factory, arrayBuffer, offset, length) { assert.throws(() => { factory(arrayBuffer, offset, length); }, RangeError); diff --git a/test/dataview/dataview_read_write.js b/test/dataview/dataview_read_write.js index fb8502a71..368a4e7f7 100644 --- a/test/dataview/dataview_read_write.js +++ b/test/dataview/dataview_read_write.js @@ -4,52 +4,52 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function expected(type, value) { +function test (binding) { + function expected (type, value) { return eval(`(new ${type}Array([${value}]))[0]`); } - function nativeReadDataView(dataview, type, offset, value) { + function nativeReadDataView (dataview, type, offset, value) { return eval(`binding.dataview_read_write.get${type}(dataview, offset)`); } - function nativeWriteDataView(dataview, type, offset, value) { + function nativeWriteDataView (dataview, type, offset, value) { eval(`binding.dataview_read_write.set${type}(dataview, offset, value)`); } - function isLittleEndian() { + function isLittleEndian () { const buffer = new ArrayBuffer(2); new DataView(buffer).setInt16(0, 256, true /* littleEndian */); return new Int16Array(buffer)[0] === 256; } - function jsReadDataView(dataview, type, offset, value) { + function jsReadDataView (dataview, type, offset, value) { return eval(`dataview.get${type}(offset, isLittleEndian())`); } - function jsWriteDataView(dataview, type, offset, value) { + function jsWriteDataView (dataview, type, offset, value) { eval(`dataview.set${type}(offset, value, isLittleEndian())`); } - function testReadData(dataview, type, offset, value) { + function testReadData (dataview, type, offset, value) { jsWriteDataView(dataview, type, offset, 0); assert.strictEqual(jsReadDataView(dataview, type, offset), 0); jsWriteDataView(dataview, type, offset, value); assert.strictEqual( - nativeReadDataView(dataview, type, offset), expected(type, value)); + nativeReadDataView(dataview, type, offset), expected(type, value)); } - function testWriteData(dataview, type, offset, value) { + function testWriteData (dataview, type, offset, value) { jsWriteDataView(dataview, type, offset, 0); assert.strictEqual(jsReadDataView(dataview, type, offset), 0); nativeWriteDataView(dataview, type, offset, value); assert.strictEqual( - jsReadDataView(dataview, type, offset), expected(type, value)); + jsReadDataView(dataview, type, offset), expected(type, value)); } - function testInvalidOffset(dataview, type, offset, value) { + function testInvalidOffset (dataview, type, offset, value) { assert.throws(() => { nativeReadDataView(dataview, type, offset); }, RangeError); diff --git a/test/date.js b/test/date.js index bd24291b8..86c8af6ac 100644 --- a/test/date.js +++ b/test/date.js @@ -4,12 +4,12 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { const { CreateDate, IsDate, ValueOf, - OperatorValue, + OperatorValue } = binding.date; assert.deepStrictEqual(CreateDate(0), new Date(0)); assert.strictEqual(IsDate(new Date(0)), true); diff --git a/test/env_cleanup.js b/test/env_cleanup.js index 48113caac..f695fccef 100644 --- a/test/env_cleanup.js +++ b/test/env_cleanup.js @@ -3,54 +3,53 @@ const assert = require('assert'); if (process.argv[2] === 'runInChildProcess') { - const binding_path = process.argv[3]; - const remove_hooks = process.argv[4] === 'true'; + const binding_path = process.argv[3]; + const remove_hooks = process.argv[4] === 'true'; - const binding = require(binding_path); - const actualAdded = binding.env_cleanup.addHooks(remove_hooks); - const expectedAdded = remove_hooks === true ? 0 : 8; - assert(actualAdded === expectedAdded, 'Incorrect number of hooks added'); -} -else { - module.exports = require('./common').runTestWithBindingPath(test); + const binding = require(binding_path); + const actualAdded = binding.env_cleanup.addHooks(remove_hooks); + const expectedAdded = remove_hooks === true ? 0 : 8; + assert(actualAdded === expectedAdded, 'Incorrect number of hooks added'); +} else { + module.exports = require('./common').runTestWithBindingPath(test); } -function test(bindingPath) { - for (const remove_hooks of [false, true]) { - const { status, output } = require('./napi_child').spawnSync( - process.execPath, - [ - __filename, - 'runInChildProcess', - bindingPath, - remove_hooks, - ], - { encoding: 'utf8' } - ); +function test (bindingPath) { + for (const remove_hooks of [false, true]) { + const { status, output } = require('./napi_child').spawnSync( + process.execPath, + [ + __filename, + 'runInChildProcess', + bindingPath, + remove_hooks + ], + { encoding: 'utf8' } + ); - const stdout = output[1].trim(); - /** + const stdout = output[1].trim(); + /** * There is no need to sort the lines, as per Node-API documentation: * > The hooks will be called in reverse order, i.e. the most recently * > added one will be called first. */ - const lines = stdout.split(/[\r\n]+/); + const lines = stdout.split(/[\r\n]+/); - assert(status === 0, `Process aborted with status ${status}`); + assert(status === 0, `Process aborted with status ${status}`); - if (remove_hooks) { - assert.deepStrictEqual(lines, [''], 'Child process had console output when none expected') - } else { - assert.deepStrictEqual(lines, [ - 'lambda cleanup()', - 'lambda cleanup(void)', - 'lambda cleanup(42)', - 'static cleanup()', - 'static cleanup()', - 'static cleanup(43)', - 'static cleanup(42)', - 'static cleanup(42)' - ], 'Child process console output mismisatch') - } + if (remove_hooks) { + assert.deepStrictEqual(lines, [''], 'Child process had console output when none expected'); + } else { + assert.deepStrictEqual(lines, [ + 'lambda cleanup()', + 'lambda cleanup(void)', + 'lambda cleanup(42)', + 'static cleanup()', + 'static cleanup()', + 'static cleanup(43)', + 'static cleanup(42)', + 'static cleanup(42)' + ], 'Child process console output mismisatch'); } + } } diff --git a/test/function.js b/test/function.js index 7536f62e8..32e32b919 100644 --- a/test/function.js +++ b/test/function.js @@ -8,71 +8,71 @@ module.exports = require('./common').runTest(binding => { testLambda(binding.function.lambda); }); -function test(binding) { +function test (binding) { assert.strictEqual(binding.emptyConstructor(true), true); assert.strictEqual(binding.emptyConstructor(false), false); let obj = {}; assert.deepStrictEqual(binding.voidCallback(obj), undefined); - assert.deepStrictEqual(obj, { "foo": "bar" }); + assert.deepStrictEqual(obj, { foo: 'bar' }); - assert.deepStrictEqual(binding.valueCallback(), { "foo": "bar" }); + assert.deepStrictEqual(binding.valueCallback(), { foo: 'bar' }); let args = null; let ret = null; let receiver = null; - function testFunction() { + function testFunction () { receiver = this; args = [].slice.call(arguments); return ret; } - function testConstructor() { + function testConstructor () { args = [].slice.call(arguments); } - function makeCallbackTestFunction(receiver, expectedOne, expectedTwo, expectedThree) { - return function callback(one, two, three) { + function makeCallbackTestFunction (receiver, expectedOne, expectedTwo, expectedThree) { + return function callback (one, two, three) { assert.strictEqual(this, receiver); assert.strictEqual(one, expectedOne); assert.strictEqual(two, expectedTwo); assert.strictEqual(three, expectedThree); - } + }; } ret = 4; assert.strictEqual(binding.callWithArgs(testFunction, 1, 2, 3), 4); assert.strictEqual(receiver, undefined); - assert.deepStrictEqual(args, [ 1, 2, 3 ]); + assert.deepStrictEqual(args, [1, 2, 3]); ret = 5; assert.strictEqual(binding.callWithVector(testFunction, 2, 3, 4), 5); assert.strictEqual(receiver, undefined); - assert.deepStrictEqual(args, [ 2, 3, 4 ]); + assert.deepStrictEqual(args, [2, 3, 4]); ret = 6; assert.strictEqual(binding.callWithReceiverAndArgs(testFunction, obj, 3, 4, 5), 6); assert.deepStrictEqual(receiver, obj); - assert.deepStrictEqual(args, [ 3, 4, 5 ]); + assert.deepStrictEqual(args, [3, 4, 5]); ret = 7; assert.strictEqual(binding.callWithReceiverAndVector(testFunction, obj, 4, 5, 6), 7); assert.deepStrictEqual(receiver, obj); - assert.deepStrictEqual(args, [ 4, 5, 6 ]); + assert.deepStrictEqual(args, [4, 5, 6]); ret = 8; assert.strictEqual(binding.callWithCStyleArray(testFunction, 5, 6, 7), ret); assert.deepStrictEqual(receiver, undefined); - assert.deepStrictEqual(args, [ 5, 6, 7 ]); + assert.deepStrictEqual(args, [5, 6, 7]); ret = 9; assert.strictEqual(binding.callWithReceiverAndCStyleArray(testFunction, obj, 6, 7, 8), ret); assert.deepStrictEqual(receiver, obj); - assert.deepStrictEqual(args, [ 6, 7, 8 ]); + assert.deepStrictEqual(args, [6, 7, 8]); ret = 10; assert.strictEqual(binding.callWithFunctionOperator(testFunction, 7, 8, 9), ret); assert.strictEqual(receiver, undefined); - assert.deepStrictEqual(args, [ 7, 8, 9 ]); + assert.deepStrictEqual(args, [7, 8, 9]); assert.throws(() => { binding.callWithInvalidReceiver(); @@ -80,33 +80,33 @@ function test(binding) { obj = binding.callConstructorWithArgs(testConstructor, 5, 6, 7); assert(obj instanceof testConstructor); - assert.deepStrictEqual(args, [ 5, 6, 7 ]); + assert.deepStrictEqual(args, [5, 6, 7]); obj = binding.callConstructorWithVector(testConstructor, 6, 7, 8); assert(obj instanceof testConstructor); - assert.deepStrictEqual(args, [ 6, 7, 8 ]); + assert.deepStrictEqual(args, [6, 7, 8]); obj = binding.callConstructorWithCStyleArray(testConstructor, 7, 8, 9); assert(obj instanceof testConstructor); - assert.deepStrictEqual(args, [ 7, 8, 9 ]); + assert.deepStrictEqual(args, [7, 8, 9]); obj = {}; assert.deepStrictEqual(binding.voidCallbackWithData(obj), undefined); - assert.deepStrictEqual(obj, { "foo": "bar", "data": 1 }); + assert.deepStrictEqual(obj, { foo: 'bar', data: 1 }); - assert.deepStrictEqual(binding.valueCallbackWithData(), { "foo": "bar", "data": 1 }); + assert.deepStrictEqual(binding.valueCallbackWithData(), { foo: 'bar', data: 1 }); assert.strictEqual(binding.voidCallback.name, 'voidCallback'); assert.strictEqual(binding.valueCallback.name, 'valueCallback'); - let testConstructCall = undefined; + let testConstructCall; binding.isConstructCall((result) => { testConstructCall = result; }); assert.ok(!testConstructCall); new binding.isConstructCall((result) => { testConstructCall = result; }); assert.ok(testConstructCall); obj = {}; - binding.makeCallbackWithArgs(makeCallbackTestFunction(obj, "1", "2", "3"), obj, "1", "2", "3"); + binding.makeCallbackWithArgs(makeCallbackTestFunction(obj, '1', '2', '3'), obj, '1', '2', '3'); binding.makeCallbackWithVector(makeCallbackTestFunction(obj, 4, 5, 6), obj, 4, 5, 6); binding.makeCallbackWithCStyleArray(makeCallbackTestFunction(obj, 7, 8, 9), obj, 7, 8, 9); assert.throws(() => { @@ -114,7 +114,7 @@ function test(binding) { }); } -function testLambda(binding) { +function testLambda (binding) { assert.ok(binding.lambdaWithNoCapture()); assert.ok(binding.lambdaWithCapture()); assert.ok(binding.lambdaWithMoveOnlyCapture()); diff --git a/test/function_reference.js b/test/function_reference.js index 3266f0031..04f2992f7 100644 --- a/test/function_reference.js +++ b/test/function_reference.js @@ -6,10 +6,10 @@ module.exports = require('./common').runTest(binding => { test(binding.functionreference); }); -function test(binding) { +function test (binding) { const e = new Error('foobar'); const functionMayThrow = () => { throw e; }; - const classMayThrow = class { constructor() { throw e; } }; + const classMayThrow = class { constructor () { throw e; } }; assert.throws(() => { binding.call(functionMayThrow); diff --git a/test/globalObject/global_object_delete_property.js b/test/globalObject/global_object_delete_property.js index c3f3dad95..c8fa68e55 100644 --- a/test/globalObject/global_object_delete_property.js +++ b/test/globalObject/global_object_delete_property.js @@ -4,58 +4,55 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - const KEY_TYPE = { - C_STR: 'KEY_AS_C_STRING', - CPP_STR: 'KEY_AS_CPP_STRING', - NAPI: 'KEY_AS_NAPI_VALUES', - INT_32: 'KEY_AS_INT_32_NUM' - }; - - function assertNotGlobalObjectHasNoProperty(key, keyType) - { - switch(keyType) - { - case KEY_TYPE.NAPI: - assert.notStrictEqual(binding.globalObject.hasPropertyWithNapiValue(key), true); - break; - - case KEY_TYPE.C_STR: - assert.notStrictEqual(binding.globalObject.hasPropertyWithCStyleString(key), true); - break; - - case KEY_TYPE.CPP_STR: - assert.notStrictEqual(binding.globalObject.hasPropertyWithCppStyleString(key), true); - break; - - case KEY_TYPE.INT_32: - assert.notStrictEqual(binding.globalObject.hasPropertyWithInt32(key), true); - break; - } +function test (binding) { + const KEY_TYPE = { + C_STR: 'KEY_AS_C_STRING', + CPP_STR: 'KEY_AS_CPP_STRING', + NAPI: 'KEY_AS_NAPI_VALUES', + INT_32: 'KEY_AS_INT_32_NUM' + }; + + function assertNotGlobalObjectHasNoProperty (key, keyType) { + switch (keyType) { + case KEY_TYPE.NAPI: + assert.notStrictEqual(binding.globalObject.hasPropertyWithNapiValue(key), true); + break; + + case KEY_TYPE.C_STR: + assert.notStrictEqual(binding.globalObject.hasPropertyWithCStyleString(key), true); + break; + + case KEY_TYPE.CPP_STR: + assert.notStrictEqual(binding.globalObject.hasPropertyWithCppStyleString(key), true); + break; + + case KEY_TYPE.INT_32: + assert.notStrictEqual(binding.globalObject.hasPropertyWithInt32(key), true); + break; } - - function assertErrMessageIsThrown(propertyCheckExistenceFunction, errMsg) { - assert.throws(() => { - propertyCheckExistenceFunction(undefined); - }, errMsg); - } - - binding.globalObject.createMockTestObject(); - - binding.globalObject.deletePropertyWithCStyleString('c_str_key'); - binding.globalObject.deletePropertyWithCppStyleString('cpp_string_key'); - binding.globalObject.deletePropertyWithCppStyleString('circular'); - binding.globalObject.deletePropertyWithInt32(15); - binding.globalObject.deletePropertyWithNapiValue('2'); - - - assertNotGlobalObjectHasNoProperty('c_str_key',KEY_TYPE.C_STR); - assertNotGlobalObjectHasNoProperty('cpp_string_key',KEY_TYPE.CPP_STR); - assertNotGlobalObjectHasNoProperty('circular',KEY_TYPE.CPP_STR); - assertNotGlobalObjectHasNoProperty(15,true); - assertNotGlobalObjectHasNoProperty('2', KEY_TYPE.NAPI); - - assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCppStyleString, 'Error: A string was expected'); - assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCStyleString, 'Error: A string was expected'); - assertErrMessageIsThrown(binding.globalObject.hasPropertyWithInt32, 'Error: A number was expected'); + } + + function assertErrMessageIsThrown (propertyCheckExistenceFunction, errMsg) { + assert.throws(() => { + propertyCheckExistenceFunction(undefined); + }, errMsg); + } + + binding.globalObject.createMockTestObject(); + + binding.globalObject.deletePropertyWithCStyleString('c_str_key'); + binding.globalObject.deletePropertyWithCppStyleString('cpp_string_key'); + binding.globalObject.deletePropertyWithCppStyleString('circular'); + binding.globalObject.deletePropertyWithInt32(15); + binding.globalObject.deletePropertyWithNapiValue('2'); + + assertNotGlobalObjectHasNoProperty('c_str_key', KEY_TYPE.C_STR); + assertNotGlobalObjectHasNoProperty('cpp_string_key', KEY_TYPE.CPP_STR); + assertNotGlobalObjectHasNoProperty('circular', KEY_TYPE.CPP_STR); + assertNotGlobalObjectHasNoProperty(15, true); + assertNotGlobalObjectHasNoProperty('2', KEY_TYPE.NAPI); + + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCppStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithInt32, 'Error: A number was expected'); } diff --git a/test/globalObject/global_object_get_property.js b/test/globalObject/global_object_get_property.js index 83b337368..ec72a8447 100644 --- a/test/globalObject/global_object_get_property.js +++ b/test/globalObject/global_object_get_property.js @@ -4,51 +4,50 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { +function test (binding) { const KEY_TYPE = { - C_STR: 'KEY_AS_C_STRING', - CPP_STR: 'KEY_AS_CPP_STRING', - NAPI: 'KEY_AS_NAPI_VALUES', - INT_32: 'KEY_AS_INT_32_NUM' - }; + C_STR: 'KEY_AS_C_STRING', + CPP_STR: 'KEY_AS_CPP_STRING', + NAPI: 'KEY_AS_NAPI_VALUES', + INT_32: 'KEY_AS_INT_32_NUM' + }; binding.globalObject.createMockTestObject(); - function assertGlobalObjectPropertyIs(key, attribute, keyType) { + function assertGlobalObjectPropertyIs (key, attribute, keyType) { let napiObjectAttr; - switch(keyType) - { - case KEY_TYPE.NAPI: - napiObjectAttr = binding.globalObject.getPropertyWithNapiValue(key); - assert.deepStrictEqual(attribute, napiObjectAttr); - break; - - case KEY_TYPE.C_STR: - napiObjectAttr = binding.globalObject.getPropertyWithCString(key); - assert.deepStrictEqual(attribute, napiObjectAttr); - break; - - case KEY_TYPE.CPP_STR: - napiObjectAttr = binding.globalObject.getPropertyWithCppString(key); - assert.deepStrictEqual(attribute, napiObjectAttr); - break; - - case KEY_TYPE.INT_32: - napiObjectAttr = binding.globalObject.getPropertyWithInt32(key); - assert.deepStrictEqual(attribute, napiObjectAttr); - break; - } + switch (keyType) { + case KEY_TYPE.NAPI: + napiObjectAttr = binding.globalObject.getPropertyWithNapiValue(key); + assert.deepStrictEqual(attribute, napiObjectAttr); + break; + + case KEY_TYPE.C_STR: + napiObjectAttr = binding.globalObject.getPropertyWithCString(key); + assert.deepStrictEqual(attribute, napiObjectAttr); + break; + + case KEY_TYPE.CPP_STR: + napiObjectAttr = binding.globalObject.getPropertyWithCppString(key); + assert.deepStrictEqual(attribute, napiObjectAttr); + break; + + case KEY_TYPE.INT_32: + napiObjectAttr = binding.globalObject.getPropertyWithInt32(key); + assert.deepStrictEqual(attribute, napiObjectAttr); + break; + } } - function assertErrMessageIsThrown(propertyFetchFunction, errMsg) { + function assertErrMessageIsThrown (propertyFetchFunction, errMsg) { assert.throws(() => { propertyFetchFunction(undefined); }, errMsg); } - assertGlobalObjectPropertyIs('2',global['2'], KEY_TYPE.NAPI); - assertGlobalObjectPropertyIs('c_str_key',global['c_str_key'],KEY_TYPE.C_STR); - assertGlobalObjectPropertyIs('cpp_string_key',global['cpp_string_key'],KEY_TYPE.CPP_STR); - assertGlobalObjectPropertyIs('circular',global['circular'],KEY_TYPE.CPP_STR); + assertGlobalObjectPropertyIs('2', global['2'], KEY_TYPE.NAPI); + assertGlobalObjectPropertyIs('c_str_key', global.c_str_key, KEY_TYPE.C_STR); + assertGlobalObjectPropertyIs('cpp_string_key', global.cpp_string_key, KEY_TYPE.CPP_STR); + assertGlobalObjectPropertyIs('circular', global.circular, KEY_TYPE.CPP_STR); assertGlobalObjectPropertyIs(15, global['15'], KEY_TYPE.INT_32); assertErrMessageIsThrown(binding.globalObject.getPropertyWithCString, 'Error: A string was expected'); diff --git a/test/globalObject/global_object_has_own_property.js b/test/globalObject/global_object_has_own_property.js index 30deeecdd..652c6b3fd 100644 --- a/test/globalObject/global_object_has_own_property.js +++ b/test/globalObject/global_object_has_own_property.js @@ -4,45 +4,43 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - const KEY_TYPE = { - C_STR: 'KEY_AS_C_STRING', - CPP_STR: 'KEY_AS_CPP_STRING', - NAPI: 'KEY_AS_NAPI_VALUES', - INT_32: 'KEY_AS_INT_32_NUM' - }; - - function assertGlobalObjectHasProperty(key, keyType) - { - switch(keyType) - { - case KEY_TYPE.NAPI: - assert.strictEqual(binding.globalObject.hasPropertyWithNapiValue(key), true); - break; - - case KEY_TYPE.C_STR: - assert.strictEqual(binding.globalObject.hasPropertyWithCStyleString(key), true); - break; - - case KEY_TYPE.CPP_STR: - assert.strictEqual(binding.globalObject.hasPropertyWithCppStyleString(key), true); - break; - } +function test (binding) { + const KEY_TYPE = { + C_STR: 'KEY_AS_C_STRING', + CPP_STR: 'KEY_AS_CPP_STRING', + NAPI: 'KEY_AS_NAPI_VALUES', + INT_32: 'KEY_AS_INT_32_NUM' + }; + + function assertGlobalObjectHasProperty (key, keyType) { + switch (keyType) { + case KEY_TYPE.NAPI: + assert.strictEqual(binding.globalObject.hasPropertyWithNapiValue(key), true); + break; + + case KEY_TYPE.C_STR: + assert.strictEqual(binding.globalObject.hasPropertyWithCStyleString(key), true); + break; + + case KEY_TYPE.CPP_STR: + assert.strictEqual(binding.globalObject.hasPropertyWithCppStyleString(key), true); + break; } - - function assertErrMessageIsThrown(propertyCheckExistenceFunction, errMsg) { - assert.throws(() => { - propertyCheckExistenceFunction(undefined); - }, errMsg); - } - - binding.globalObject.createMockTestObject(); - assertGlobalObjectHasProperty('c_str_key',KEY_TYPE.C_STR); - assertGlobalObjectHasProperty('cpp_string_key',KEY_TYPE.CPP_STR); - assertGlobalObjectHasProperty('circular',KEY_TYPE.CPP_STR); - assertGlobalObjectHasProperty('2', KEY_TYPE.NAPI); - - assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCppStyleString, 'Error: A string was expected'); - assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCStyleString, 'Error: A string was expected'); - assertErrMessageIsThrown(binding.globalObject.hasPropertyWithInt32, 'Error: A number was expected'); + } + + function assertErrMessageIsThrown (propertyCheckExistenceFunction, errMsg) { + assert.throws(() => { + propertyCheckExistenceFunction(undefined); + }, errMsg); + } + + binding.globalObject.createMockTestObject(); + assertGlobalObjectHasProperty('c_str_key', KEY_TYPE.C_STR); + assertGlobalObjectHasProperty('cpp_string_key', KEY_TYPE.CPP_STR); + assertGlobalObjectHasProperty('circular', KEY_TYPE.CPP_STR); + assertGlobalObjectHasProperty('2', KEY_TYPE.NAPI); + + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCppStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithCStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.hasPropertyWithInt32, 'Error: A number was expected'); } diff --git a/test/globalObject/global_object_set_property.js b/test/globalObject/global_object_set_property.js index d934efae9..ff4811c66 100644 --- a/test/globalObject/global_object_set_property.js +++ b/test/globalObject/global_object_set_property.js @@ -4,55 +4,53 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { +function test (binding) { const KEY_TYPE = { - C_STR: 'KEY_AS_C_STRING', - CPP_STR: 'KEY_AS_CPP_STRING', - NAPI: 'KEY_AS_NAPI_VALUES', - INT_32: 'KEY_AS_INT_32_NUM' - }; - - function setGlobalObjectKeyValue(key, value, keyType) { - switch(keyType) - { - case KEY_TYPE.CPP_STR: - binding.globalObject.setPropertyWithCppStyleString(key,value); - break; - - case KEY_TYPE.C_STR: - binding.globalObject.setPropertyWithCStyleString(key,value); - break; - - case KEY_TYPE.INT_32: - binding.globalObject.setPropertyWithInt32(key,value); - break; - - case KEY_TYPE.NAPI: - binding.globalObject.setPropertyWithNapiValue(key,value); - break; - } + C_STR: 'KEY_AS_C_STRING', + CPP_STR: 'KEY_AS_CPP_STRING', + NAPI: 'KEY_AS_NAPI_VALUES', + INT_32: 'KEY_AS_INT_32_NUM' + }; + + function setGlobalObjectKeyValue (key, value, keyType) { + switch (keyType) { + case KEY_TYPE.CPP_STR: + binding.globalObject.setPropertyWithCppStyleString(key, value); + break; + + case KEY_TYPE.C_STR: + binding.globalObject.setPropertyWithCStyleString(key, value); + break; + + case KEY_TYPE.INT_32: + binding.globalObject.setPropertyWithInt32(key, value); + break; + + case KEY_TYPE.NAPI: + binding.globalObject.setPropertyWithNapiValue(key, value); + break; } - - function assertErrMessageIsThrown(nativeObjectSetFunction, errMsg) { - assert.throws(() => { - nativeObjectSetFunction(undefined, 1); - }, errMsg); - } - - - setGlobalObjectKeyValue("cKey","cValue",KEY_TYPE.CPP_STR); - setGlobalObjectKeyValue(1,10,KEY_TYPE.INT_32); - setGlobalObjectKeyValue("napi_key","napi_value",KEY_TYPE.NAPI); - setGlobalObjectKeyValue("cppKey","cppValue",KEY_TYPE.CPP_STR); - setGlobalObjectKeyValue("circular",global,KEY_TYPE.NAPI); - - assert.deepStrictEqual(global["circular"], global); - assert.deepStrictEqual(global["cppKey"],"cppValue"); - assert.deepStrictEqual(global["napi_key"],"napi_value"); - assert.deepStrictEqual(global[1],10); - assert.deepStrictEqual(global["cKey"],"cValue"); - - assertErrMessageIsThrown(binding.globalObject.setPropertyWithCppStyleString, 'Error: A string was expected'); - assertErrMessageIsThrown(binding.globalObject.setPropertyWithCStyleString, 'Error: A string was expected'); - assertErrMessageIsThrown(binding.globalObject.setPropertyWithInt32, 'Error: A number was expected'); + } + + function assertErrMessageIsThrown (nativeObjectSetFunction, errMsg) { + assert.throws(() => { + nativeObjectSetFunction(undefined, 1); + }, errMsg); + } + + setGlobalObjectKeyValue('cKey', 'cValue', KEY_TYPE.CPP_STR); + setGlobalObjectKeyValue(1, 10, KEY_TYPE.INT_32); + setGlobalObjectKeyValue('napi_key', 'napi_value', KEY_TYPE.NAPI); + setGlobalObjectKeyValue('cppKey', 'cppValue', KEY_TYPE.CPP_STR); + setGlobalObjectKeyValue('circular', global, KEY_TYPE.NAPI); + + assert.deepStrictEqual(global.circular, global); + assert.deepStrictEqual(global.cppKey, 'cppValue'); + assert.deepStrictEqual(global.napi_key, 'napi_value'); + assert.deepStrictEqual(global[1], 10); + assert.deepStrictEqual(global.cKey, 'cValue'); + + assertErrMessageIsThrown(binding.globalObject.setPropertyWithCppStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.setPropertyWithCStyleString, 'Error: A string was expected'); + assertErrMessageIsThrown(binding.globalObject.setPropertyWithInt32, 'Error: A number was expected'); } diff --git a/test/handlescope.js b/test/handlescope.js index f8887f0a0..e216600ec 100644 --- a/test/handlescope.js +++ b/test/handlescope.js @@ -4,11 +4,11 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { assert.strictEqual(binding.handlescope.createScope(), 'scope'); assert.strictEqual(binding.handlescope.escapeFromScope(), 'inner-scope'); assert.strictEqual(binding.handlescope.stressEscapeFromScope(), 'inner-scope999999'); assert.throws(() => binding.handlescope.doubleEscapeFromScope(), - Error, - ' napi_escape_handle already called on scope'); + Error, + ' napi_escape_handle already called on scope'); } diff --git a/test/index.js b/test/index.js index c45807d40..8bafec8d8 100644 --- a/test/index.js +++ b/test/index.js @@ -4,7 +4,7 @@ const majorNodeVersion = process.versions.node.split('.')[0]; if (typeof global.gc !== 'function') { // Construct the correct (version-dependent) command-line args. - let args = ['--expose-gc']; + const args = ['--expose-gc']; const majorV8Version = process.versions.v8.split('.')[0]; if (majorV8Version < 9) { args.push('--no-concurrent-array-buffer-freeing'); @@ -15,7 +15,7 @@ if (typeof global.gc !== 'function') { args.push(__filename); const child = require('./napi_child').spawnSync(process.argv[0], args, { - stdio: 'inherit', + stdio: 'inherit' }); if (child.signal) { @@ -31,15 +31,14 @@ const fs = require('fs'); const path = require('path'); process.env.filter = require('../unit-test/matchModules').matchWildCards(process.env.filter); -let testModules = []; +const testModules = []; const filterCondition = process.env.filter || ''; -const filterConditionFiles = filterCondition.split(' ').length ? filterCondition.split(' ') : [filterCondition]; +const filterConditionFiles = filterCondition.split(' ').length ? filterCondition.split(' ') : [filterCondition]; - -function checkFilterCondition(fileName, parsedFilepath) { +function checkFilterCondition (fileName, parsedFilepath) { let result = false; - + if (!filterConditionFiles.length) result = true; if (filterConditionFiles.includes(parsedFilepath)) result = true; if (filterConditionFiles.includes(fileName)) result = true; @@ -48,10 +47,10 @@ function checkFilterCondition(fileName, parsedFilepath) { // TODO(RaisinTen): Update this when the test filenames // are changed into test_*.js. -function loadTestModules(currentDirectory = __dirname, pre = '') { +function loadTestModules (currentDirectory = __dirname, pre = '') { fs.readdirSync(currentDirectory).forEach((file) => { if (currentDirectory === __dirname && ( - file === 'binding.cc' || + file === 'binding.cc' || file === 'binding.gyp' || file === 'build' || file === 'common' || @@ -136,7 +135,7 @@ if (napiVersion < 8 && !filterConditionFiles.length) { testModules.splice(testModules.indexOf('object/object_freeze_seal'), 1); } -(async function() { +(async function () { console.log(`Testing with Node-API Version '${napiVersion}'.`); console.log('Starting test suite\n', testModules); @@ -145,7 +144,7 @@ if (napiVersion < 8 && !filterConditionFiles.length) { for (const name of testModules) { console.log(`Running test '${name}'`); await require('./' + name); - }; + } console.log('\nAll tests passed!'); })().catch((error) => { diff --git a/test/maybe/index.js b/test/maybe/index.js index ad562c9c9..f3d6fdf05 100644 --- a/test/maybe/index.js +++ b/test/maybe/index.js @@ -8,13 +8,13 @@ const napiChild = require('../napi_child'); module.exports = test(require(`../build/${buildType}/binding_noexcept_maybe.node`).maybe_check); -function test(binding) { +function test (binding) { if (process.argv.includes('child')) { child(binding); return; } const cp = napiChild.spawn(process.execPath, [__filename, 'child'], { - stdio: ['ignore', 'inherit', 'pipe'], + stdio: ['ignore', 'inherit', 'pipe'] }); cp.stderr.setEncoding('utf8'); let stderr = ''; @@ -31,8 +31,8 @@ function test(binding) { }); } -function child(binding) { +function child (binding) { binding.voidCallback(() => { throw new Error('foobar'); - }) + }); } diff --git a/test/memory_management.js b/test/memory_management.js index 707899e79..af5dbb0f0 100644 --- a/test/memory_management.js +++ b/test/memory_management.js @@ -4,6 +4,6 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { - assert.strictEqual(binding.memory_management.externalAllocatedMemory(), true) +function test (binding) { + assert.strictEqual(binding.memory_management.externalAllocatedMemory(), true); } diff --git a/test/movable_callbacks.js b/test/movable_callbacks.js index 3588295da..0ee81f6e4 100644 --- a/test/movable_callbacks.js +++ b/test/movable_callbacks.js @@ -5,7 +5,7 @@ const testUtil = require('./testUtil'); module.exports = require('./common').runTest(binding => test(binding.movable_callbacks)); -async function test(binding) { +async function test (binding) { await testUtil.runGCTests([ 'External', () => { diff --git a/test/name.js b/test/name.js index 717f1862f..ae224234c 100644 --- a/test/name.js +++ b/test/name.js @@ -4,13 +4,12 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { const expected = '123456789'; - assert.throws(binding.name.nullStringShouldThrow, { name: 'Error', - message: 'Error in native callback', + message: 'Error in native callback' }); assert.ok(binding.name.checkString(expected, 'utf8')); assert.ok(binding.name.checkString(expected, 'utf16')); diff --git a/test/napi_child.js b/test/napi_child.js index 76f0bc56a..e3f89fd0b 100644 --- a/test/napi_child.js +++ b/test/napi_child.js @@ -1,12 +1,12 @@ // Makes sure that child processes are spawned appropriately. -exports.spawnSync = function(command, args, options) { +exports.spawnSync = function (command, args, options) { if (require('../index').needsFlag) { args.splice(0, 0, '--napi-modules'); } return require('child_process').spawnSync(command, args, options); }; -exports.spawn = function(command, args, options) { +exports.spawn = function (command, args, options) { if (require('../index').needsFlag) { args.splice(0, 0, '--napi-modules'); } diff --git a/test/object/delete_property.js b/test/object/delete_property.js index 459298d8a..cfe607c02 100644 --- a/test/object/delete_property.js +++ b/test/object/delete_property.js @@ -4,10 +4,10 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function testDeleteProperty(nativeDeleteProperty) { +function test (binding) { + function testDeleteProperty (nativeDeleteProperty) { const obj = { one: 1, two: 2 }; - Object.defineProperty(obj, "three", {configurable: false, value: 3}); + Object.defineProperty(obj, 'three', { configurable: false, value: 3 }); assert.strictEqual(nativeDeleteProperty(obj, 'one'), true); assert.strictEqual(nativeDeleteProperty(obj, 'missing'), true); @@ -17,17 +17,17 @@ function test(binding) { assert.deepStrictEqual(obj, { two: 2 }); } - function testShouldThrowErrorIfKeyIsInvalid(nativeDeleteProperty) { + function testShouldThrowErrorIfKeyIsInvalid (nativeDeleteProperty) { assert.throws(() => { nativeDeleteProperty(undefined, 'test'); }, /Cannot convert undefined or null to object/); } - const testObj = { 15 : 42 , three: 3}; + const testObj = { 15: 42, three: 3 }; - binding.object.deletePropertyWithUint32(testObj,15); + binding.object.deletePropertyWithUint32(testObj, 15); - assert.strictEqual(testObj.hasOwnProperty(15),false); + assert.strictEqual(testObj.hasOwnProperty(15), false); testDeleteProperty(binding.object.deletePropertyWithNapiValue); testDeleteProperty(binding.object.deletePropertyWithNapiWrapperValue); diff --git a/test/object/finalizer.js b/test/object/finalizer.js index bf2fb189e..be6c98a32 100644 --- a/test/object/finalizer.js +++ b/test/object/finalizer.js @@ -5,11 +5,11 @@ const testUtil = require('../testUtil'); module.exports = require('../common').runTest(test); -function createWeakRef(binding, bindingToTest) { +function createWeakRef (binding, bindingToTest) { return binding.object[bindingToTest]({}); } -function test(binding) { +function test (binding) { let obj1; let obj2; return testUtil.runGCTests([ diff --git a/test/object/get_property.js b/test/object/get_property.js index d661bab4d..fd5e98773 100644 --- a/test/object/get_property.js +++ b/test/object/get_property.js @@ -4,26 +4,26 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function testGetProperty(nativeGetProperty) { +function test (binding) { + function testGetProperty (nativeGetProperty) { const obj = { test: 1 }; assert.strictEqual(nativeGetProperty(obj, 'test'), 1); } - function testShouldReturnUndefinedIfKeyIsNotPresent(nativeGetProperty) { + function testShouldReturnUndefinedIfKeyIsNotPresent (nativeGetProperty) { const obj = { }; assert.strictEqual(nativeGetProperty(obj, 'test'), undefined); } - function testShouldThrowErrorIfKeyIsInvalid(nativeGetProperty) { + function testShouldThrowErrorIfKeyIsInvalid (nativeGetProperty) { assert.throws(() => { nativeGetProperty(undefined, 'test'); }, /Cannot convert undefined or null to object/); } const testObject = { 42: 100 }; - const property = binding.object.getPropertyWithUint32(testObject, 42); - assert.strictEqual(property,100) + const property = binding.object.getPropertyWithUint32(testObject, 42); + assert.strictEqual(property, 100); const nativeFunctions = [ binding.object.getPropertyWithNapiValue, diff --git a/test/object/has_own_property.js b/test/object/has_own_property.js index fda74c3cb..1315a47d9 100644 --- a/test/object/has_own_property.js +++ b/test/object/has_own_property.js @@ -4,8 +4,8 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function testHasOwnProperty(nativeHasOwnProperty) { +function test (binding) { + function testHasOwnProperty (nativeHasOwnProperty) { const obj = { one: 1 }; Object.defineProperty(obj, 'two', { value: 2 }); @@ -16,7 +16,7 @@ function test(binding) { assert.strictEqual(nativeHasOwnProperty(obj, 'toString'), false); } - function testShouldThrowErrorIfKeyIsInvalid(nativeHasOwnProperty) { + function testShouldThrowErrorIfKeyIsInvalid (nativeHasOwnProperty) { assert.throws(() => { nativeHasOwnProperty(undefined, 'test'); }, /Cannot convert undefined or null to object/); diff --git a/test/object/has_property.js b/test/object/has_property.js index 722f00652..f2b3a8e3c 100644 --- a/test/object/has_property.js +++ b/test/object/has_property.js @@ -4,8 +4,8 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function testHasProperty(nativeHasProperty) { +function test (binding) { + function testHasProperty (nativeHasProperty) { const obj = { one: 1 }; Object.defineProperty(obj, 'two', { value: 2 }); @@ -16,14 +16,14 @@ function test(binding) { assert.strictEqual(nativeHasProperty(obj, 'toString'), true); } - function testShouldThrowErrorIfKeyIsInvalid(nativeHasProperty) { + function testShouldThrowErrorIfKeyIsInvalid (nativeHasProperty) { assert.throws(() => { nativeHasProperty(undefined, 'test'); }, /Cannot convert undefined or null to object/); } const objectWithInt32Key = { 12: 101 }; - assert.strictEqual(binding.object.hasPropertyWithUint32(objectWithInt32Key,12),true); + assert.strictEqual(binding.object.hasPropertyWithUint32(objectWithInt32Key, 12), true); testHasProperty(binding.object.hasPropertyWithNapiValue); testHasProperty(binding.object.hasPropertyWithNapiWrapperValue); diff --git a/test/object/object.js b/test/object/object.js index ef06ad2fc..e38fe6c5f 100644 --- a/test/object/object.js +++ b/test/object/object.js @@ -4,20 +4,20 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function assertPropertyIs(obj, key, attribute) { +function test (binding) { + function assertPropertyIs (obj, key, attribute) { const propDesc = Object.getOwnPropertyDescriptor(obj, key); assert.ok(propDesc); assert.ok(propDesc[attribute]); } - function assertPropertyIsNot(obj, key, attribute) { + function assertPropertyIsNot (obj, key, attribute) { const propDesc = Object.getOwnPropertyDescriptor(obj, key); assert.ok(propDesc); assert.ok(!propDesc[attribute]); } - function testDefineProperties(nameType) { + function testDefineProperties (nameType) { const obj = {}; binding.object.defineProperties(obj, nameType); @@ -107,7 +107,7 @@ function test(binding) { } { - const expected = { 'one': 1, 'two': 2, 'three': 3 }; + const expected = { one: 1, two: 2, three: 3 }; const actual = binding.object.constructorFromObject(expected); assert.deepStrictEqual(actual, expected); } @@ -121,8 +121,8 @@ function test(binding) { { const testSym = Symbol(); - const obj = { 'one': 1, 'two': 2, 'three': 3, [testSym]: 4 }; - var arr = binding.object.GetPropertyNames(obj); + const obj = { one: 1, two: 2, three: 3, [testSym]: 4 }; + const arr = binding.object.GetPropertyNames(obj); assert.deepStrictEqual(arr, ['one', 'two', 'three']); } @@ -149,7 +149,7 @@ function test(binding) { } { - function Ctor() {}; + function Ctor () {} assert.strictEqual(binding.object.instanceOf(new Ctor(), Ctor), true); assert.strictEqual(binding.object.instanceOf(new Ctor(), Object), true); diff --git a/test/object/object_deprecated.js b/test/object/object_deprecated.js index 00ee7b4e2..898a6dc40 100644 --- a/test/object/object_deprecated.js +++ b/test/object/object_deprecated.js @@ -4,23 +4,23 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { +function test (binding) { if (!('object_deprecated' in binding)) { return; } - function assertPropertyIs(obj, key, attribute) { + function assertPropertyIs (obj, key, attribute) { const propDesc = Object.getOwnPropertyDescriptor(obj, key); assert.ok(propDesc); assert.ok(propDesc[attribute]); } - function assertPropertyIsNot(obj, key, attribute) { + function assertPropertyIsNot (obj, key, attribute) { const propDesc = Object.getOwnPropertyDescriptor(obj, key); assert.ok(propDesc); assert.ok(!propDesc[attribute]); } - function testDefineProperties(nameType) { + function testDefineProperties (nameType) { const obj = {}; binding.object.defineProperties(obj, nameType); diff --git a/test/object/object_freeze_seal.js b/test/object/object_freeze_seal.js index 62c1c48f3..667af6a6f 100644 --- a/test/object/object_freeze_seal.js +++ b/test/object/object_freeze_seal.js @@ -4,58 +4,58 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - { - const obj = { x: 'a', y: 'b', z: 'c' }; - assert.strictEqual(binding.object_freeze_seal.freeze(obj), true); - assert.strictEqual(Object.isFrozen(obj), true); - assert.throws(() => { - obj.x = 10; - }, /Cannot assign to read only property 'x' of object '#/); - assert.throws(() => { - obj.w = 15; - }, /Cannot add property w, object is not extensible/); - assert.throws(() => { - delete obj.x; - }, /Cannot delete property 'x' of #/); - } - - { - const obj = new Proxy({ x: 'a', y: 'b', z: 'c' }, { - preventExtensions() { - throw new Error('foo'); - }, - }); - - assert.throws(() => { - binding.object_freeze_seal.freeze(obj); - }, /foo/); - } - - { - const obj = { x: 'a', y: 'b', z: 'c' }; - assert.strictEqual(binding.object_freeze_seal.seal(obj), true); - assert.strictEqual(Object.isSealed(obj), true); - assert.throws(() => { - obj.w = 'd'; - }, /Cannot add property w, object is not extensible/); - assert.throws(() => { - delete obj.x; - }, /Cannot delete property 'x' of #/); - // Sealed objects allow updating existing properties, - // so this should not throw. - obj.x = 'd'; - } - - { - const obj = new Proxy({ x: 'a', y: 'b', z: 'c' }, { - preventExtensions() { - throw new Error('foo'); - }, - }); - - assert.throws(() => { - binding.object_freeze_seal.seal(obj); - }, /foo/); - } +function test (binding) { + { + const obj = { x: 'a', y: 'b', z: 'c' }; + assert.strictEqual(binding.object_freeze_seal.freeze(obj), true); + assert.strictEqual(Object.isFrozen(obj), true); + assert.throws(() => { + obj.x = 10; + }, /Cannot assign to read only property 'x' of object '#/); + assert.throws(() => { + obj.w = 15; + }, /Cannot add property w, object is not extensible/); + assert.throws(() => { + delete obj.x; + }, /Cannot delete property 'x' of #/); + } + + { + const obj = new Proxy({ x: 'a', y: 'b', z: 'c' }, { + preventExtensions () { + throw new Error('foo'); + } + }); + + assert.throws(() => { + binding.object_freeze_seal.freeze(obj); + }, /foo/); + } + + { + const obj = { x: 'a', y: 'b', z: 'c' }; + assert.strictEqual(binding.object_freeze_seal.seal(obj), true); + assert.strictEqual(Object.isSealed(obj), true); + assert.throws(() => { + obj.w = 'd'; + }, /Cannot add property w, object is not extensible/); + assert.throws(() => { + delete obj.x; + }, /Cannot delete property 'x' of #/); + // Sealed objects allow updating existing properties, + // so this should not throw. + obj.x = 'd'; + } + + { + const obj = new Proxy({ x: 'a', y: 'b', z: 'c' }, { + preventExtensions () { + throw new Error('foo'); + } + }); + + assert.throws(() => { + binding.object_freeze_seal.seal(obj); + }, /foo/); + } } diff --git a/test/object/set_property.js b/test/object/set_property.js index 86fab3b75..5100b0e8b 100644 --- a/test/object/set_property.js +++ b/test/object/set_property.js @@ -4,14 +4,14 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function testSetProperty(nativeSetProperty) { +function test (binding) { + function testSetProperty (nativeSetProperty) { const obj = {}; assert.strictEqual(nativeSetProperty(obj, 'test', 1), true); assert.strictEqual(obj.test, 1); } - function testShouldThrowErrorIfKeyIsInvalid(nativeSetProperty) { + function testShouldThrowErrorIfKeyIsInvalid (nativeSetProperty) { assert.throws(() => { nativeSetProperty(undefined, 'test', 1); }, /Cannot convert undefined or null to object/); diff --git a/test/object/subscript_operator.js b/test/object/subscript_operator.js index 0caefe45b..4d0c544f3 100644 --- a/test/object/subscript_operator.js +++ b/test/object/subscript_operator.js @@ -4,8 +4,8 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -function test(binding) { - function testProperty(obj, key, value, nativeGetProperty, nativeSetProperty) { +function test (binding) { + function testProperty (obj, key, value, nativeGetProperty, nativeSetProperty) { nativeSetProperty(obj, key, value); assert.strictEqual(nativeGetProperty(obj, key), value); } diff --git a/test/object_reference.js b/test/object_reference.js index daecb5958..50e4e0eda 100644 --- a/test/object_reference.js +++ b/test/object_reference.js @@ -16,13 +16,13 @@ const testUtil = require('./testUtil'); module.exports = require('./common').runTest(test); -function test(binding) { - function testCastedEqual(testToCompare) { - var compare_test = ["hello", "world", "!"]; +function test (binding) { + function testCastedEqual (testToCompare) { + const compare_test = ['hello', 'world', '!']; if (testToCompare instanceof Array) { assert.deepEqual(compare_test, testToCompare); } else if (testToCompare instanceof String) { - assert.deepEqual("No Referenced Value", testToCompare); + assert.deepEqual('No Referenced Value', testToCompare); } else { assert.fail(); } @@ -32,11 +32,11 @@ function test(binding) { 'Weak Casted Array', () => { binding.objectreference.setCastedObjects(); - var test = binding.objectreference.getCastedFromValue("weak"); - var test2 = new Array(); - test2[0] = binding.objectreference.getCastedFromGetter("weak", 0); - test2[1] = binding.objectreference.getCastedFromGetter("weak", 1); - test2[2] = binding.objectreference.getCastedFromGetter("weak", 2); + const test = binding.objectreference.getCastedFromValue('weak'); + const test2 = new Array(); + test2[0] = binding.objectreference.getCastedFromGetter('weak', 0); + test2[1] = binding.objectreference.getCastedFromGetter('weak', 1); + test2[2] = binding.objectreference.getCastedFromGetter('weak', 2); testCastedEqual(test); testCastedEqual(test2); @@ -45,11 +45,11 @@ function test(binding) { 'Persistent Casted Array', () => { binding.objectreference.setCastedObjects(); - const test = binding.objectreference.getCastedFromValue("persistent"); + const test = binding.objectreference.getCastedFromValue('persistent'); const test2 = new Array(); - test2[0] = binding.objectreference.getCastedFromGetter("persistent", 0); - test2[1] = binding.objectreference.getCastedFromGetter("persistent", 1); - test2[2] = binding.objectreference.getCastedFromGetter("persistent", 2); + test2[0] = binding.objectreference.getCastedFromGetter('persistent', 0); + test2[1] = binding.objectreference.getCastedFromGetter('persistent', 1); + test2[2] = binding.objectreference.getCastedFromGetter('persistent', 2); assert.ok(test instanceof Array); assert.ok(test2 instanceof Array); @@ -62,9 +62,9 @@ function test(binding) { binding.objectreference.setCastedObjects(); const test = binding.objectreference.getCastedFromValue(); const test2 = new Array(); - test2[0] = binding.objectreference.getCastedFromGetter("reference", 0); - test2[1] = binding.objectreference.getCastedFromGetter("reference", 1); - test2[2] = binding.objectreference.getCastedFromGetter("reference", 2); + test2[0] = binding.objectreference.getCastedFromGetter('reference', 0); + test2[1] = binding.objectreference.getCastedFromGetter('reference', 1); + test2[2] = binding.objectreference.getCastedFromGetter('reference', 2); assert.ok(test instanceof Array); assert.ok(test2 instanceof Array); @@ -74,57 +74,57 @@ function test(binding) { 'Weak', () => { - binding.objectreference.setObjects("hello", "world"); - const test = binding.objectreference.getFromValue("weak"); - const test2 = binding.objectreference.getFromGetter("weak", "hello"); + binding.objectreference.setObjects('hello', 'world'); + const test = binding.objectreference.getFromValue('weak'); + const test2 = binding.objectreference.getFromGetter('weak', 'hello'); - assert.deepEqual({ hello: "world"}, test); - assert.equal("world", test2); - assert.equal(test["hello"], test2); + assert.deepEqual({ hello: 'world' }, test); + assert.equal('world', test2); + assert.equal(test.hello, test2); }, () => { - binding.objectreference.setObjects("hello", "world", "javascript"); - const test = binding.objectreference.getFromValue("weak"); - const test2 = binding.objectreference.getFromValue("weak", "hello"); + binding.objectreference.setObjects('hello', 'world', 'javascript'); + const test = binding.objectreference.getFromValue('weak'); + const test2 = binding.objectreference.getFromValue('weak', 'hello'); - assert.deepEqual({ hello: "world" }, test); - assert.deepEqual({ hello: "world" }, test2); + assert.deepEqual({ hello: 'world' }, test); + assert.deepEqual({ hello: 'world' }, test2); assert.equal(test, test2); }, () => { - binding.objectreference.setObjects(1, "hello world"); - const test = binding.objectreference.getFromValue("weak"); - const test2 = binding.objectreference.getFromGetter("weak", 1); + binding.objectreference.setObjects(1, 'hello world'); + const test = binding.objectreference.getFromValue('weak'); + const test2 = binding.objectreference.getFromGetter('weak', 1); - assert.deepEqual({ 1: "hello world" }, test); - assert.equal("hello world", test2); + assert.deepEqual({ 1: 'hello world' }, test); + assert.equal('hello world', test2); assert.equal(test[1], test2); }, () => { - binding.objectreference.setObjects(0, "hello"); - binding.objectreference.setObjects(1, "world"); - const test = binding.objectreference.getFromValue("weak"); - const test2 = binding.objectreference.getFromGetter("weak", 0); - const test3 = binding.objectreference.getFromGetter("weak", 1); + binding.objectreference.setObjects(0, 'hello'); + binding.objectreference.setObjects(1, 'world'); + const test = binding.objectreference.getFromValue('weak'); + const test2 = binding.objectreference.getFromGetter('weak', 0); + const test3 = binding.objectreference.getFromGetter('weak', 1); - assert.deepEqual({ 1: "world" }, test); + assert.deepEqual({ 1: 'world' }, test); assert.equal(undefined, test2); - assert.equal("world", test3); + assert.equal('world', test3); }, () => { - binding.objectreference.setObjects("hello", "world"); + binding.objectreference.setObjects('hello', 'world'); assert.doesNotThrow( () => { - var rcount = binding.objectreference.refObjects("weak"); + let rcount = binding.objectreference.refObjects('weak'); assert.equal(rcount, 1); - rcount = binding.objectreference.unrefObjects("weak"); + rcount = binding.objectreference.unrefObjects('weak'); assert.equal(rcount, 0); }, Error ); assert.throws( () => { - binding.objectreference.unrefObjects("weak"); + binding.objectreference.unrefObjects('weak'); }, Error ); @@ -132,63 +132,63 @@ function test(binding) { 'Persistent', () => { - binding.objectreference.setObjects("hello", "world"); - const test = binding.objectreference.getFromValue("persistent"); - const test2 = binding.objectreference.getFromGetter("persistent", "hello"); + binding.objectreference.setObjects('hello', 'world'); + const test = binding.objectreference.getFromValue('persistent'); + const test2 = binding.objectreference.getFromGetter('persistent', 'hello'); - assert.deepEqual({ hello: "world" }, test); - assert.equal("world", test2); - assert.equal(test["hello"], test2); + assert.deepEqual({ hello: 'world' }, test); + assert.equal('world', test2); + assert.equal(test.hello, test2); }, () => { - binding.objectreference.setObjects("hello", "world", "javascript"); - const test = binding.objectreference.getFromValue("persistent"); - const test2 = binding.objectreference.getFromValue("persistent", "hello"); + binding.objectreference.setObjects('hello', 'world', 'javascript'); + const test = binding.objectreference.getFromValue('persistent'); + const test2 = binding.objectreference.getFromValue('persistent', 'hello'); - assert.deepEqual({ hello: "world" }, test); - assert.deepEqual({ hello: "world" }, test2); + assert.deepEqual({ hello: 'world' }, test); + assert.deepEqual({ hello: 'world' }, test2); assert.deepEqual(test, test2); }, () => { - binding.objectreference.setObjects(1, "hello world"); - const test = binding.objectreference.getFromValue("persistent"); - const test2 = binding.objectreference.getFromGetter("persistent", 1); + binding.objectreference.setObjects(1, 'hello world'); + const test = binding.objectreference.getFromValue('persistent'); + const test2 = binding.objectreference.getFromGetter('persistent', 1); - assert.deepEqual({ 1: "hello world"}, test); - assert.equal("hello world", test2); + assert.deepEqual({ 1: 'hello world' }, test); + assert.equal('hello world', test2); assert.equal(test[1], test2); }, () => { - binding.objectreference.setObjects(0, "hello"); - binding.objectreference.setObjects(1, "world"); - const test = binding.objectreference.getFromValue("persistent"); - const test2 = binding.objectreference.getFromGetter("persistent", 0); - const test3 = binding.objectreference.getFromGetter("persistent", 1); + binding.objectreference.setObjects(0, 'hello'); + binding.objectreference.setObjects(1, 'world'); + const test = binding.objectreference.getFromValue('persistent'); + const test2 = binding.objectreference.getFromGetter('persistent', 0); + const test3 = binding.objectreference.getFromGetter('persistent', 1); - assert.deepEqual({ 1: "world"}, test); + assert.deepEqual({ 1: 'world' }, test); assert.equal(undefined, test2); - assert.equal("world", test3); + assert.equal('world', test3); }, () => { - binding.objectreference.setObjects("hello", "world"); + binding.objectreference.setObjects('hello', 'world'); assert.doesNotThrow( () => { - var rcount = binding.objectreference.unrefObjects("persistent"); + let rcount = binding.objectreference.unrefObjects('persistent'); assert.equal(rcount, 0); - rcount = binding.objectreference.refObjects("persistent"); + rcount = binding.objectreference.refObjects('persistent'); assert.equal(rcount, 1); - rcount = binding.objectreference.unrefObjects("persistent"); + rcount = binding.objectreference.unrefObjects('persistent'); assert.equal(rcount, 0); - rcount = binding.objectreference.refObjects("persistent"); + rcount = binding.objectreference.refObjects('persistent'); assert.equal(rcount, 1); - rcount = binding.objectreference.unrefObjects("persistent"); + rcount = binding.objectreference.unrefObjects('persistent'); assert.equal(rcount, 0); }, Error ); assert.throws( () => { - binding.objectreference.unrefObjects("persistent"); + binding.objectreference.unrefObjects('persistent'); }, Error ); @@ -196,64 +196,64 @@ function test(binding) { 'References', () => { - binding.objectreference.setObjects("hello", "world"); + binding.objectreference.setObjects('hello', 'world'); const test = binding.objectreference.getFromValue(); - const test2 = binding.objectreference.getFromGetter("hello"); + const test2 = binding.objectreference.getFromGetter('hello'); - assert.deepEqual({ hello: "world" }, test); - assert.equal("world", test2); - assert.equal(test["hello"], test2); + assert.deepEqual({ hello: 'world' }, test); + assert.equal('world', test2); + assert.equal(test.hello, test2); }, () => { - binding.objectreference.setObjects("hello", "world", "javascript"); + binding.objectreference.setObjects('hello', 'world', 'javascript'); const test = binding.objectreference.getFromValue(); - const test2 = binding.objectreference.getFromValue("hello"); + const test2 = binding.objectreference.getFromValue('hello'); - assert.deepEqual({ hello: "world" }, test); - assert.deepEqual({ hello: "world" }, test2); + assert.deepEqual({ hello: 'world' }, test); + assert.deepEqual({ hello: 'world' }, test2); assert.deepEqual(test, test2); }, () => { - binding.objectreference.setObjects(1, "hello world"); + binding.objectreference.setObjects(1, 'hello world'); const test = binding.objectreference.getFromValue(); const test2 = binding.objectreference.getFromGetter(1); - assert.deepEqual({ 1: "hello world"}, test); - assert.equal("hello world", test2); + assert.deepEqual({ 1: 'hello world' }, test); + assert.equal('hello world', test2); assert.equal(test[1], test2); }, () => { - binding.objectreference.setObjects(0, "hello"); - binding.objectreference.setObjects(1, "world"); + binding.objectreference.setObjects(0, 'hello'); + binding.objectreference.setObjects(1, 'world'); const test = binding.objectreference.getFromValue(); const test2 = binding.objectreference.getFromGetter(0); const test3 = binding.objectreference.getFromGetter(1); - assert.deepEqual({ 1: "world"}, test); + assert.deepEqual({ 1: 'world' }, test); assert.equal(undefined, test2); - assert.equal("world", test3); + assert.equal('world', test3); }, () => { - binding.objectreference.setObjects("hello", "world"); + binding.objectreference.setObjects('hello', 'world'); assert.doesNotThrow( () => { - var rcount = binding.objectreference.unrefObjects("references"); + let rcount = binding.objectreference.unrefObjects('references'); assert.equal(rcount, 1); - rcount = binding.objectreference.refObjects("references"); + rcount = binding.objectreference.refObjects('references'); assert.equal(rcount, 2); - rcount = binding.objectreference.unrefObjects("references"); + rcount = binding.objectreference.unrefObjects('references'); assert.equal(rcount, 1); - rcount = binding.objectreference.unrefObjects("references"); + rcount = binding.objectreference.unrefObjects('references'); assert.equal(rcount, 0); }, Error ); assert.throws( () => { - binding.objectreference.unrefObjects("references"); + binding.objectreference.unrefObjects('references'); }, Error ); } - ]) -}; + ]); +} diff --git a/test/objectwrap.js b/test/objectwrap.js index 2dcd12fd1..cb84c947b 100644 --- a/test/objectwrap.js +++ b/test/objectwrap.js @@ -5,7 +5,7 @@ const testUtil = require('./testUtil'); module.exports = require('./common').runTest(test); -async function test(binding) { +async function test (binding) { const Test = binding.objectwrap.Test; const testValue = (obj, clazz) => { @@ -107,19 +107,19 @@ async function test(binding) { // for..in: object and prototype { const keys = []; - for (let key in obj) { + for (const key in obj) { keys.push(key); } assert(keys.length == 6); // on prototype - assert(keys.includes("testGetSet")); - assert(keys.includes("testGetter")); - assert(keys.includes("testValue")); - assert(keys.includes("testMethod")); + assert(keys.includes('testGetSet')); + assert(keys.includes('testGetter')); + assert(keys.includes('testValue')); + assert(keys.includes('testMethod')); // on object only - assert(keys.includes("ownProperty")); - assert(keys.includes("ownPropertyT")); + assert(keys.includes('ownProperty')); + assert(keys.includes('ownPropertyT')); } }; @@ -135,7 +135,7 @@ async function test(binding) { obj.testSetter = 'iterator'; const values = []; - for (let item of obj) { + for (const item of obj) { values.push(item); } @@ -146,7 +146,7 @@ async function test(binding) { const testStaticValue = (clazz) => { assert.strictEqual(clazz.testStaticValue, 'value'); assert.strictEqual(clazz[clazz.kTestStaticValueInternal], 5); - } + }; const testStaticAccessor = (clazz) => { // read-only, write-only @@ -227,7 +227,7 @@ async function test(binding) { // for..in { const keys = []; - for (let key in clazz) { + for (const key in clazz) { keys.push(key); } @@ -240,21 +240,21 @@ async function test(binding) { } }; - async function testFinalize(clazz) { + async function testFinalize (clazz) { let finalizeCalled = false; await testUtil.runGCTests([ 'test finalize', () => { - const finalizeCb = function(called) { + const finalizeCb = function (called) { finalizeCalled = called; }; - //Scope Test instance so that it can be gc'd. + // Scope Test instance so that it can be gc'd. (() => { new Test(finalizeCb); })(); }, () => assert.strictEqual(finalizeCalled, true) ]); - }; + } const testObj = (obj, clazz) => { testValue(obj, clazz); @@ -264,16 +264,16 @@ async function test(binding) { testEnumerables(obj, clazz); testConventions(obj, clazz); - } + }; - async function testClass(clazz) { + async function testClass (clazz) { testStaticValue(clazz); testStaticAccessor(clazz); testStaticMethod(clazz); testStaticEnumerables(clazz); await testFinalize(clazz); - }; + } // `Test` is needed for accessing exposed symbols testObj(new Test(), Test); diff --git a/test/objectwrap_constructor_exception.js b/test/objectwrap_constructor_exception.js index 6a5e469f6..2fbed8144 100644 --- a/test/objectwrap_constructor_exception.js +++ b/test/objectwrap_constructor_exception.js @@ -3,7 +3,7 @@ const assert = require('assert'); const testUtil = require('./testUtil'); -function test(binding) { +function test (binding) { return testUtil.runGCTests([ 'objectwrap constructor exception', () => { diff --git a/test/objectwrap_multiple_inheritance.js b/test/objectwrap_multiple_inheritance.js index d4d2282b4..526490478 100644 --- a/test/objectwrap_multiple_inheritance.js +++ b/test/objectwrap_multiple_inheritance.js @@ -8,6 +8,6 @@ const test = bindingName => { const testmi = new TestMI(); assert.strictEqual(testmi.test, 0); -} +}; module.exports = require('./common').runTestWithBindingPath(test); diff --git a/test/objectwrap_worker_thread.js b/test/objectwrap_worker_thread.js index e5cfdb81a..7b3ac83b5 100644 --- a/test/objectwrap_worker_thread.js +++ b/test/objectwrap_worker_thread.js @@ -4,7 +4,7 @@ const { Worker, isMainThread, workerData } = require('worker_threads'); module.exports = require('./common').runTestWithBuildType(test); -async function test(buildType) { +async function test (buildType) { if (isMainThread) { const buildType = process.config.target_defaults.default_configuration; const worker = new Worker(__filename, { workerData: buildType }); diff --git a/test/promise.js b/test/promise.js index f681a2e0e..6db019d82 100644 --- a/test/promise.js +++ b/test/promise.js @@ -5,7 +5,7 @@ const common = require('./common'); module.exports = common.runTest(test); -async function test(binding) { +async function test (binding) { assert.strictEqual(binding.promise.isPromise({}), false); const resolving = binding.promise.resolvePromise('resolved'); diff --git a/test/reference.js b/test/reference.js index 8c56ceabf..34fe85172 100644 --- a/test/reference.js +++ b/test/reference.js @@ -5,10 +5,10 @@ const testUtil = require('./testUtil'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { return testUtil.runGCTests([ 'test reference', () => binding.reference.createWeakArray(), () => assert.strictEqual(true, binding.reference.accessWeakArrayEmpty()) ]); -}; +} diff --git a/test/run_script.js b/test/run_script.js index 711ab1035..61f0bda47 100644 --- a/test/run_script.js +++ b/test/run_script.js @@ -5,7 +5,7 @@ const testUtil = require('./testUtil'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { return testUtil.runGCTests([ 'Plain C string', () => { @@ -21,7 +21,7 @@ function test(binding) { 'JavaScript string', () => { - const sum = binding.run_script.jsString("1 + 2 + 3"); + const sum = binding.run_script.jsString('1 + 2 + 3'); assert.strictEqual(sum, 1 + 2 + 3); }, @@ -37,8 +37,8 @@ function test(binding) { 'With context', () => { - const a = 1, b = 2, c = 3; - const sum = binding.run_script.withContext("a + b + c", { a, b, c }); + const a = 1; const b = 2; const c = 3; + const sum = binding.run_script.withContext('a + b + c', { a, b, c }); assert.strictEqual(sum, a + b + c); } ]); diff --git a/test/symbol.js b/test/symbol.js index 7601feb2f..6282a75e1 100644 --- a/test/symbol.js +++ b/test/symbol.js @@ -5,69 +5,61 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); - -function test(binding) -{ - const majorNodeVersion = process.versions.node.split('.')[0]; - - let wellKnownSymbolFunctions = ['asyncIterator','hasInstance','isConcatSpreadable', 'iterator','match','replace','search','split','species','toPrimitive','toStringTag','unscopables']; - if (majorNodeVersion >= 12) { - wellKnownSymbolFunctions.push('matchAll'); - } - - function assertCanCreateSymbol(symbol) - { - assert(binding.symbol.createNewSymbolWithCppStr(symbol) !== null); - assert(binding.symbol.createNewSymbolWithCStr(symbol) !== null); - assert(binding.symbol.createNewSymbolWithNapi(symbol) !== null); - } - - function assertSymbolAreUnique(symbol) - { - const symbolOne = binding.symbol.createNewSymbolWithCppStr(symbol); - const symbolTwo = binding.symbol.createNewSymbolWithCppStr(symbol); - - assert(symbolOne !== symbolTwo); - } - - function assertSymbolIsWellknown(symbol) - { - const symbOne = binding.symbol.getWellKnownSymbol(symbol); - const symbTwo = binding.symbol.getWellKnownSymbol(symbol); - assert(symbOne && symbTwo); - assert(symbOne === symbTwo); - } - - function assertSymbolIsNotWellknown(symbol) - { - const symbolTest = binding.symbol.getWellKnownSymbol(symbol); - assert(symbolTest === undefined); - } - - function assertCanCreateOrFetchGlobalSymbols(symbol, fetchFunction) - { - const symbOne = fetchFunction(symbol); - const symbTwo = fetchFunction(symbol); - assert(symbOne && symbTwo); - assert(symbOne === symbTwo); - } - - assertCanCreateSymbol("testing"); - assertSymbolAreUnique("symbol"); - assertSymbolIsNotWellknown("testing"); - - for(const wellknownProperty of wellKnownSymbolFunctions) - { - assertSymbolIsWellknown(wellknownProperty); - } - - assertCanCreateOrFetchGlobalSymbols("data", binding.symbol.getSymbolFromGlobalRegistry); - assertCanCreateOrFetchGlobalSymbols("CppKey", binding.symbol.getSymbolFromGlobalRegistryWithCppKey); - assertCanCreateOrFetchGlobalSymbols("CKey", binding.symbol.getSymbolFromGlobalRegistryWithCKey); - - assert(binding.symbol.createNewSymbolWithNoArgs() === undefined); - - assert(binding.symbol.testNullSymbolCanBeCreated() === binding.symbol.testNullSymbolCanBeCreated()); - assert(binding.symbol.testUndefinedSymbolCanBeCreated() === binding.symbol.testUndefinedSymbolCanBeCreated()); - assert(binding.symbol.testUndefinedSymbolCanBeCreated() !== binding.symbol.testNullSymbolCanBeCreated()); +function test (binding) { + const majorNodeVersion = process.versions.node.split('.')[0]; + + const wellKnownSymbolFunctions = ['asyncIterator', 'hasInstance', 'isConcatSpreadable', 'iterator', 'match', 'replace', 'search', 'split', 'species', 'toPrimitive', 'toStringTag', 'unscopables']; + if (majorNodeVersion >= 12) { + wellKnownSymbolFunctions.push('matchAll'); + } + + function assertCanCreateSymbol (symbol) { + assert(binding.symbol.createNewSymbolWithCppStr(symbol) !== null); + assert(binding.symbol.createNewSymbolWithCStr(symbol) !== null); + assert(binding.symbol.createNewSymbolWithNapi(symbol) !== null); + } + + function assertSymbolAreUnique (symbol) { + const symbolOne = binding.symbol.createNewSymbolWithCppStr(symbol); + const symbolTwo = binding.symbol.createNewSymbolWithCppStr(symbol); + + assert(symbolOne !== symbolTwo); + } + + function assertSymbolIsWellknown (symbol) { + const symbOne = binding.symbol.getWellKnownSymbol(symbol); + const symbTwo = binding.symbol.getWellKnownSymbol(symbol); + assert(symbOne && symbTwo); + assert(symbOne === symbTwo); + } + + function assertSymbolIsNotWellknown (symbol) { + const symbolTest = binding.symbol.getWellKnownSymbol(symbol); + assert(symbolTest === undefined); + } + + function assertCanCreateOrFetchGlobalSymbols (symbol, fetchFunction) { + const symbOne = fetchFunction(symbol); + const symbTwo = fetchFunction(symbol); + assert(symbOne && symbTwo); + assert(symbOne === symbTwo); + } + + assertCanCreateSymbol('testing'); + assertSymbolAreUnique('symbol'); + assertSymbolIsNotWellknown('testing'); + + for (const wellknownProperty of wellKnownSymbolFunctions) { + assertSymbolIsWellknown(wellknownProperty); + } + + assertCanCreateOrFetchGlobalSymbols('data', binding.symbol.getSymbolFromGlobalRegistry); + assertCanCreateOrFetchGlobalSymbols('CppKey', binding.symbol.getSymbolFromGlobalRegistryWithCppKey); + assertCanCreateOrFetchGlobalSymbols('CKey', binding.symbol.getSymbolFromGlobalRegistryWithCKey); + + assert(binding.symbol.createNewSymbolWithNoArgs() === undefined); + + assert(binding.symbol.testNullSymbolCanBeCreated() === binding.symbol.testNullSymbolCanBeCreated()); + assert(binding.symbol.testUndefinedSymbolCanBeCreated() === binding.symbol.testUndefinedSymbolCanBeCreated()); + assert(binding.symbol.testUndefinedSymbolCanBeCreated() !== binding.symbol.testNullSymbolCanBeCreated()); } diff --git a/test/testUtil.js b/test/testUtil.js index b8777e781..470ba8144 100644 --- a/test/testUtil.js +++ b/test/testUtil.js @@ -1,9 +1,9 @@ // Run each test function in sequence, // with an async delay and GC call between each. -function tick(x) { +function tick (x) { return new Promise((resolve) => { - setImmediate(function ontick() { + setImmediate(function ontick () { if (--x === 0) { resolve(); } else { @@ -11,9 +11,9 @@ function tick(x) { } }); }); -}; +} -async function runGCTests(tests) { +async function runGCTests (tests) { // Break up test list into a list of lists of the form // [ [ 'test name', function() {}, ... ], ..., ]. const testList = []; @@ -27,7 +27,7 @@ async function runGCTests(tests) { } for (const test of testList) { - await (async function(test) { + await (async function (test) { let title; for (let i = 0; i < test.length; i++) { if (i === 0) { @@ -50,5 +50,5 @@ async function runGCTests(tests) { } module.exports = { - runGCTests, + runGCTests }; diff --git a/test/threadsafe_function/threadsafe_function.js b/test/threadsafe_function/threadsafe_function.js index 5236f28ea..573c33649 100644 --- a/test/threadsafe_function/threadsafe_function.js +++ b/test/threadsafe_function/threadsafe_function.js @@ -5,8 +5,8 @@ const common = require('../common'); module.exports = common.runTest(test); -async function test(binding) { - const expectedArray = (function(arrayLength) { +async function test (binding) { + const expectedArray = (function (arrayLength) { const result = []; for (let index = 0; index < arrayLength; index++) { result.push(arrayLength - 1 - index); @@ -14,15 +14,16 @@ async function test(binding) { return result; })(binding.threadsafe_function.ARRAY_LENGTH); - function testWithJSMarshaller({ + function testWithJSMarshaller ({ threadStarter, quitAfter, abort, maxQueueSize, - launchSecondary }) { + launchSecondary + }) { return new Promise((resolve) => { const array = []; - binding.threadsafe_function[threadStarter](function testCallback(value) { + binding.threadsafe_function[threadStarter](function testCallback (value) { array.push(value); if (array.length === quitAfter) { binding.threadsafe_function.stopThread(common.mustCall(() => { @@ -39,9 +40,9 @@ async function test(binding) { }); } - await new Promise(function testWithoutJSMarshaller(resolve) { + await new Promise(function testWithoutJSMarshaller (resolve) { let callCount = 0; - binding.threadsafe_function.startThreadNoNative(function testCallback() { + binding.threadsafe_function.startThreadNoNative(function testCallback () { callCount++; // The default call-into-JS implementation passes no arguments. @@ -65,7 +66,7 @@ async function test(binding) { maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, quitAfter: binding.threadsafe_function.ARRAY_LENGTH }), - expectedArray, + expectedArray ); // Start the thread in blocking mode with an infinite queue, and assert that @@ -76,7 +77,7 @@ async function test(binding) { maxQueueSize: 0, quitAfter: binding.threadsafe_function.ARRAY_LENGTH }), - expectedArray, + expectedArray ); // Start the thread in non-blocking mode, and assert that all values are @@ -87,7 +88,7 @@ async function test(binding) { maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, quitAfter: binding.threadsafe_function.ARRAY_LENGTH }), - expectedArray, + expectedArray ); // Start the thread in blocking mode, and assert that all values are passed. @@ -98,7 +99,7 @@ async function test(binding) { maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, quitAfter: 1 }), - expectedArray, + expectedArray ); // Start the thread in blocking mode with an infinite queue, and assert that @@ -109,10 +110,9 @@ async function test(binding) { maxQueueSize: 0, quitAfter: 1 }), - expectedArray, + expectedArray ); - // Start the thread in non-blocking mode, and assert that all values are // passed. Quit early, but let the thread finish. assert.deepStrictEqual( @@ -121,7 +121,7 @@ async function test(binding) { maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, quitAfter: 1 }), - expectedArray, + expectedArray ); // Start the thread in blocking mode, and assert that all values are passed. @@ -134,7 +134,7 @@ async function test(binding) { maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, launchSecondary: true }), - expectedArray, + expectedArray ); // Start the thread in non-blocking mode, and assert that all values are @@ -147,7 +147,7 @@ async function test(binding) { maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, launchSecondary: true }), - expectedArray, + expectedArray ); // Start the thread in blocking mode, and assert that it could not finish. @@ -159,7 +159,7 @@ async function test(binding) { maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, abort: true })).indexOf(0), - -1, + -1 ); // Start the thread in blocking mode with an infinite queue, and assert that @@ -171,7 +171,7 @@ async function test(binding) { maxQueueSize: 0, abort: true })).indexOf(0), - -1, + -1 ); // Start the thread in non-blocking mode, and assert that it could not finish. @@ -183,6 +183,6 @@ async function test(binding) { maxQueueSize: binding.threadsafe_function.MAX_QUEUE_SIZE, abort: true })).indexOf(0), - -1, + -1 ); } diff --git a/test/threadsafe_function/threadsafe_function_ctx.js b/test/threadsafe_function/threadsafe_function_ctx.js index 94ea01fb4..258e220b1 100644 --- a/test/threadsafe_function/threadsafe_function_ctx.js +++ b/test/threadsafe_function/threadsafe_function_ctx.js @@ -4,7 +4,7 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -async function test(binding) { +async function test (binding) { const ctx = { }; const tsfn = new binding.threadsafe_function_ctx.TSFNWrap(ctx); assert(tsfn.getContext() === ctx); diff --git a/test/threadsafe_function/threadsafe_function_existing_tsfn.js b/test/threadsafe_function/threadsafe_function_existing_tsfn.js index f45978762..8de71f72c 100644 --- a/test/threadsafe_function/threadsafe_function_existing_tsfn.js +++ b/test/threadsafe_function/threadsafe_function_existing_tsfn.js @@ -4,11 +4,11 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -async function test(binding) { +async function test (binding) { const testCall = binding.threadsafe_function_existing_tsfn.testCall; - assert.strictEqual(typeof await testCall({ blocking: true, data: true }), "number"); - assert.strictEqual(typeof await testCall({ blocking: true, data: false }), "undefined"); - assert.strictEqual(typeof await testCall({ blocking: false, data: true }), "number"); - assert.strictEqual(typeof await testCall({ blocking: false, data: false }), "undefined"); + assert.strictEqual(typeof await testCall({ blocking: true, data: true }), 'number'); + assert.strictEqual(typeof await testCall({ blocking: true, data: false }), 'undefined'); + assert.strictEqual(typeof await testCall({ blocking: false, data: true }), 'number'); + assert.strictEqual(typeof await testCall({ blocking: false, data: false }), 'undefined'); } diff --git a/test/threadsafe_function/threadsafe_function_ptr.js b/test/threadsafe_function/threadsafe_function_ptr.js index 189081615..d646682d1 100644 --- a/test/threadsafe_function/threadsafe_function_ptr.js +++ b/test/threadsafe_function/threadsafe_function_ptr.js @@ -2,6 +2,6 @@ module.exports = require('../common').runTest(test); -function test(binding) { +function test (binding) { binding.threadsafe_function_ptr.test({}, () => {}); } diff --git a/test/threadsafe_function/threadsafe_function_sum.js b/test/threadsafe_function/threadsafe_function_sum.js index 64f2b4513..63225449d 100644 --- a/test/threadsafe_function/threadsafe_function_sum.js +++ b/test/threadsafe_function/threadsafe_function_sum.js @@ -33,15 +33,15 @@ module.exports = require('../common').runTest(test); /** @param {number[]} N */ const sum = (N) => N.reduce((sum, n) => sum + n, 0); -function test(binding) { - async function check(bindingFunction) { +function test (binding) { + async function check (bindingFunction) { const calls = []; const result = await bindingFunction(THREAD_COUNT, Array.prototype.push.bind(calls)); assert.ok(result); assert.equal(sum(calls), EXPECTED_SUM); } - async function checkAcquire() { + async function checkAcquire () { const calls = []; const { promise, createThread, stopThreads } = binding.threadsafe_function_sum.testAcquire(Array.prototype.push.bind(calls)); for (let i = 0; i < THREAD_COUNT; i++) { diff --git a/test/threadsafe_function/threadsafe_function_unref.js b/test/threadsafe_function/threadsafe_function_unref.js index 85aa85dc3..8fc72d39f 100644 --- a/test/threadsafe_function/threadsafe_function_unref.js +++ b/test/threadsafe_function/threadsafe_function_unref.js @@ -19,7 +19,7 @@ if (isMainProcess) { test(process.argv[2]); } -function test(bindingFile) { +function test (bindingFile) { if (isMainProcess) { // Main process return new Promise((resolve, reject) => { @@ -27,21 +27,21 @@ function test(bindingFile) { '--expose-gc', __filename, bindingFile ], { stdio: 'inherit' }); - let timeout = setTimeout( function() { + let timeout = setTimeout(function () { child.kill(); timeout = 0; - reject(new Error("Expected child to die")); + reject(new Error('Expected child to die')); }, 5000); - child.on("error", (err) => { + child.on('error', (err) => { clearTimeout(timeout); timeout = 0; reject(new Error(err)); - }) + }); - child.on("close", (code) => { + child.on('close', (code) => { if (timeout) clearTimeout(timeout); - assert.strictEqual(code, 0, "Expected return value 0"); + assert.strictEqual(code, 0, 'Expected return value 0'); resolve(); }); }); diff --git a/test/thunking_manual.js b/test/thunking_manual.js index f1a93e296..784c7959d 100644 --- a/test/thunking_manual.js +++ b/test/thunking_manual.js @@ -5,13 +5,13 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { - console.log("Thunking: Performing initial GC"); +function test (binding) { + console.log('Thunking: Performing initial GC'); global.gc(); - console.log("Thunking: Creating test object"); + console.log('Thunking: Creating test object'); let object = binding.thunking_manual.createTestObject(); object = null; - console.log("Thunking: About to GC\n--------"); + console.log('Thunking: About to GC\n--------'); global.gc(); - console.log("--------\nThunking: GC complete"); + console.log('--------\nThunking: GC complete'); } diff --git a/test/typed_threadsafe_function/typed_threadsafe_function.js b/test/typed_threadsafe_function/typed_threadsafe_function.js index 51bbf2f73..6ef2876d5 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function.js +++ b/test/typed_threadsafe_function/typed_threadsafe_function.js @@ -5,7 +5,7 @@ const common = require('../common'); module.exports = common.runTest(test); -async function test(binding) { +async function test (binding) { const expectedArray = (function (arrayLength) { const result = []; for (let index = 0; index < arrayLength; index++) { @@ -14,15 +14,16 @@ async function test(binding) { return result; })(binding.typed_threadsafe_function.ARRAY_LENGTH); - function testWithJSMarshaller({ + function testWithJSMarshaller ({ threadStarter, quitAfter, abort, maxQueueSize, - launchSecondary }) { + launchSecondary + }) { return new Promise((resolve) => { const array = []; - binding.typed_threadsafe_function[threadStarter](function testCallback(value) { + binding.typed_threadsafe_function[threadStarter](function testCallback (value) { array.push(value); if (array.length === quitAfter) { binding.typed_threadsafe_function.stopThread(common.mustCall(() => { @@ -39,9 +40,9 @@ async function test(binding) { }); } - await new Promise(function testWithoutJSMarshaller(resolve) { + await new Promise(function testWithoutJSMarshaller (resolve) { let callCount = 0; - binding.typed_threadsafe_function.startThreadNoNative(function testCallback() { + binding.typed_threadsafe_function.startThreadNoNative(function testCallback () { callCount++; // The default call-into-JS implementation passes no arguments. @@ -54,7 +55,7 @@ async function test(binding) { }); } }, false /* abort */, false /* launchSecondary */, - binding.typed_threadsafe_function.MAX_QUEUE_SIZE); + binding.typed_threadsafe_function.MAX_QUEUE_SIZE); }); // Start the thread in blocking mode, and assert that all values are passed. @@ -65,7 +66,7 @@ async function test(binding) { maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, quitAfter: binding.typed_threadsafe_function.ARRAY_LENGTH }), - expectedArray, + expectedArray ); // Start the thread in blocking mode with an infinite queue, and assert that @@ -76,7 +77,7 @@ async function test(binding) { maxQueueSize: 0, quitAfter: binding.typed_threadsafe_function.ARRAY_LENGTH }), - expectedArray, + expectedArray ); // Start the thread in non-blocking mode, and assert that all values are @@ -87,7 +88,7 @@ async function test(binding) { maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, quitAfter: binding.typed_threadsafe_function.ARRAY_LENGTH }), - expectedArray, + expectedArray ); // Start the thread in blocking mode, and assert that all values are passed. @@ -98,7 +99,7 @@ async function test(binding) { maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, quitAfter: 1 }), - expectedArray, + expectedArray ); // Start the thread in blocking mode with an infinite queue, and assert that @@ -109,10 +110,9 @@ async function test(binding) { maxQueueSize: 0, quitAfter: 1 }), - expectedArray, + expectedArray ); - // Start the thread in non-blocking mode, and assert that all values are // passed. Quit early, but let the thread finish. assert.deepStrictEqual( @@ -121,7 +121,7 @@ async function test(binding) { maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, quitAfter: 1 }), - expectedArray, + expectedArray ); // Start the thread in blocking mode, and assert that all values are passed. @@ -134,7 +134,7 @@ async function test(binding) { maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, launchSecondary: true }), - expectedArray, + expectedArray ); // Start the thread in non-blocking mode, and assert that all values are @@ -147,7 +147,7 @@ async function test(binding) { maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, launchSecondary: true }), - expectedArray, + expectedArray ); // Start the thread in blocking mode, and assert that it could not finish. @@ -159,7 +159,7 @@ async function test(binding) { maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, abort: true })).indexOf(0), - -1, + -1 ); // Start the thread in blocking mode with an infinite queue, and assert that @@ -171,7 +171,7 @@ async function test(binding) { maxQueueSize: 0, abort: true })).indexOf(0), - -1, + -1 ); // Start the thread in non-blocking mode, and assert that it could not finish. @@ -183,6 +183,6 @@ async function test(binding) { maxQueueSize: binding.typed_threadsafe_function.MAX_QUEUE_SIZE, abort: true })).indexOf(0), - -1, + -1 ); } diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js b/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js index f43da1d38..b8c842bc6 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js +++ b/test/typed_threadsafe_function/typed_threadsafe_function_ctx.js @@ -4,7 +4,7 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -async function test(binding) { +async function test (binding) { const ctx = { }; const tsfn = new binding.typed_threadsafe_function_ctx.TSFNWrap(ctx); assert(tsfn.getContext() === ctx); diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.js b/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.js index bd37824ad..17185a86b 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.js +++ b/test/typed_threadsafe_function/typed_threadsafe_function_existing_tsfn.js @@ -4,11 +4,11 @@ const assert = require('assert'); module.exports = require('../common').runTest(test); -async function test(binding) { +async function test (binding) { const testCall = binding.typed_threadsafe_function_existing_tsfn.testCall; - assert.strictEqual(typeof await testCall({ blocking: true, data: true }), "number"); - assert.strictEqual(typeof await testCall({ blocking: true, data: false }), "undefined"); - assert.strictEqual(typeof await testCall({ blocking: false, data: true }), "number"); - assert.strictEqual(typeof await testCall({ blocking: false, data: false }), "undefined"); + assert.strictEqual(typeof await testCall({ blocking: true, data: true }), 'number'); + assert.strictEqual(typeof await testCall({ blocking: true, data: false }), 'undefined'); + assert.strictEqual(typeof await testCall({ blocking: false, data: true }), 'number'); + assert.strictEqual(typeof await testCall({ blocking: false, data: false }), 'undefined'); } diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js b/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js index 36b146c23..d0e82d213 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js +++ b/test/typed_threadsafe_function/typed_threadsafe_function_ptr.js @@ -2,6 +2,6 @@ module.exports = require('../common').runTest(test); -function test(binding) { +function test (binding) { binding.typed_threadsafe_function_ptr.test({}, () => {}); } diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_sum.js b/test/typed_threadsafe_function/typed_threadsafe_function_sum.js index 59e667000..0a59bba72 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_sum.js +++ b/test/typed_threadsafe_function/typed_threadsafe_function_sum.js @@ -33,15 +33,15 @@ module.exports = require('../common').runTest(test); /** @param {number[]} N */ const sum = (N) => N.reduce((sum, n) => sum + n, 0); -function test(binding) { - async function check(bindingFunction) { +function test (binding) { + async function check (bindingFunction) { const calls = []; const result = await bindingFunction(THREAD_COUNT, Array.prototype.push.bind(calls)); assert.ok(result); assert.equal(sum(calls), EXPECTED_SUM); } - async function checkAcquire() { + async function checkAcquire () { const calls = []; const { promise, createThread, stopThreads } = binding.typed_threadsafe_function_sum.testAcquire(Array.prototype.push.bind(calls)); for (let i = 0; i < THREAD_COUNT; i++) { diff --git a/test/typed_threadsafe_function/typed_threadsafe_function_unref.js b/test/typed_threadsafe_function/typed_threadsafe_function_unref.js index aafc5e0e0..058cba390 100644 --- a/test/typed_threadsafe_function/typed_threadsafe_function_unref.js +++ b/test/typed_threadsafe_function/typed_threadsafe_function_unref.js @@ -19,7 +19,7 @@ if (isMainProcess) { test(process.argv[2]); } -function test(bindingFile) { +function test (bindingFile) { if (isMainProcess) { // Main process return new Promise((resolve, reject) => { @@ -27,21 +27,21 @@ function test(bindingFile) { '--expose-gc', __filename, bindingFile ], { stdio: 'inherit' }); - let timeout = setTimeout( function() { + let timeout = setTimeout(function () { child.kill(); timeout = 0; - reject(new Error("Expected child to die")); + reject(new Error('Expected child to die')); }, 5000); - child.on("error", (err) => { + child.on('error', (err) => { clearTimeout(timeout); timeout = 0; reject(new Error(err)); - }) + }); - child.on("close", (code) => { + child.on('close', (code) => { if (timeout) clearTimeout(timeout); - assert.strictEqual(code, 0, "Expected return value 0"); + assert.strictEqual(code, 0, 'Expected return value 0'); resolve(); }); }); diff --git a/test/typedarray-bigint.js b/test/typedarray-bigint.js index e96a51f63..1c3174525 100644 --- a/test/typedarray-bigint.js +++ b/test/typedarray-bigint.js @@ -4,10 +4,10 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { [ ['bigint64', BigInt64Array], - ['biguint64', BigUint64Array], + ['biguint64', BigUint64Array] ].forEach(([type, Constructor]) => { try { const length = 4; diff --git a/test/typedarray.js b/test/typedarray.js index 5d0fb4a27..f1088814c 100644 --- a/test/typedarray.js +++ b/test/typedarray.js @@ -4,17 +4,17 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function test(binding) { +function test (binding) { const testData = [ - [ 'int8', Int8Array ], - [ 'uint8', Uint8Array ], - [ 'uint8_clamped', Uint8ClampedArray ], - [ 'int16', Int16Array ], - [ 'uint16', Uint16Array ], - [ 'int32', Int32Array ], - [ 'uint32', Uint32Array ], - [ 'float32', Float32Array ], - [ 'float64', Float64Array ], + ['int8', Int8Array], + ['uint8', Uint8Array], + ['uint8_clamped', Uint8ClampedArray], + ['int16', Int16Array], + ['uint16', Uint16Array], + ['int32', Int32Array], + ['uint32', Uint32Array], + ['float32', Float32Array], + ['float64', Float64Array] ]; testData.forEach(data => { diff --git a/test/version_management.js b/test/version_management.js index 6bb1b189b..06d4f9c94 100644 --- a/test/version_management.js +++ b/test/version_management.js @@ -4,28 +4,26 @@ const assert = require('assert'); module.exports = require('./common').runTest(test); -function parseVersion() { - const expected = {}; - expected.napi = parseInt(process.versions.napi); - expected.release = process.release.name; - const nodeVersion = process.versions.node.split('.'); - expected.major = parseInt(nodeVersion[0]); - expected.minor = parseInt(nodeVersion[1]); - expected.patch = parseInt(nodeVersion[2]); - return expected; +function parseVersion () { + const expected = {}; + expected.napi = parseInt(process.versions.napi); + expected.release = process.release.name; + const nodeVersion = process.versions.node.split('.'); + expected.major = parseInt(nodeVersion[0]); + expected.minor = parseInt(nodeVersion[1]); + expected.patch = parseInt(nodeVersion[2]); + return expected; } -function test(binding) { +function test (binding) { + const expected = parseVersion(); - const expected = parseVersion(); - - const napiVersion = binding.version_management.getNapiVersion(); - assert.strictEqual(napiVersion, expected.napi); - - const nodeVersion = binding.version_management.getNodeVersion(); - assert.strictEqual(nodeVersion.major, expected.major); - assert.strictEqual(nodeVersion.minor, expected.minor); - assert.strictEqual(nodeVersion.patch, expected.patch); - assert.strictEqual(nodeVersion.release, expected.release); + const napiVersion = binding.version_management.getNapiVersion(); + assert.strictEqual(napiVersion, expected.napi); + const nodeVersion = binding.version_management.getNodeVersion(); + assert.strictEqual(nodeVersion.major, expected.major); + assert.strictEqual(nodeVersion.minor, expected.minor); + assert.strictEqual(nodeVersion.patch, expected.patch); + assert.strictEqual(nodeVersion.release, expected.release); } diff --git a/tools/check-napi.js b/tools/check-napi.js index 48fdfc077..e5c572589 100644 --- a/tools/check-napi.js +++ b/tools/check-napi.js @@ -8,12 +8,12 @@ const child_process = require('child_process'); // Read the output of the command, break it into lines, and use the reducer to // decide whether the file is an N-API module or not. -function checkFile(file, command, argv, reducer) { +function checkFile (file, command, argv, reducer) { const child = child_process.spawn(command, argv, { stdio: ['inherit', 'pipe', 'inherit'] }); let leftover = ''; - let isNapi = undefined; + let isNapi; child.stdout.on('data', (chunk) => { if (isNapi === undefined) { chunk = (leftover + chunk.toString()).split(/[\r\n]+/); @@ -27,11 +27,11 @@ function checkFile(file, command, argv, reducer) { child.on('close', (code, signal) => { if ((code === null && signal !== null) || (code !== 0)) { console.log( - command + ' exited with code: ' + code + ' and signal: ' + signal); + command + ' exited with code: ' + code + ' and signal: ' + signal); } else { // Green if it's a N-API module, red otherwise. console.log( - '\x1b[' + (isNapi ? '42' : '41') + 'm' + + '\x1b[' + (isNapi ? '42' : '41') + 'm' + (isNapi ? ' N-API' : 'Not N-API') + '\x1b[0m: ' + file); } @@ -39,7 +39,7 @@ function checkFile(file, command, argv, reducer) { } // Use nm -a to list symbols. -function checkFileUNIX(file) { +function checkFileUNIX (file) { checkFile(file, 'nm', ['-a', file], (soFar, line) => { if (soFar === undefined) { line = line.match(/([0-9a-f]*)? ([a-zA-Z]) (.*$)/); @@ -54,7 +54,7 @@ function checkFileUNIX(file) { } // Use dumpbin /imports to list symbols. -function checkFileWin32(file) { +function checkFileWin32 (file) { checkFile(file, 'dumpbin', ['/imports', file], (soFar, line) => { if (soFar === undefined) { line = line.match(/([0-9a-f]*)? +([a-zA-Z0-9]) (.*$)/); @@ -68,16 +68,16 @@ function checkFileWin32(file) { // Descend into a directory structure and pass each file ending in '.node' to // one of the above checks, depending on the OS. -function recurse(top) { +function recurse (top) { fs.readdir(top, (error, items) => { if (error) { - throw ("error reading directory " + top + ": " + error); + throw ('error reading directory ' + top + ': ' + error); } items.forEach((item) => { item = path.join(top, item); fs.stat(item, ((item) => (error, stats) => { if (error) { - throw ("error about " + item + ": " + error); + throw ('error about ' + item + ': ' + error); } if (stats.isDirectory()) { recurse(item); @@ -86,9 +86,9 @@ function recurse(top) { // artefacts of node-addon-api having identified a version of // Node.js that ships with a correct implementation of N-API. path.basename(item) !== 'nothing.node') { - process.platform === 'win32' ? - checkFileWin32(item) : - checkFileUNIX(item); + process.platform === 'win32' + ? checkFileWin32(item) + : checkFileUNIX(item); } })(item)); }); diff --git a/tools/clang-format.js b/tools/clang-format.js index e97098336..92e0c6bed 100644 --- a/tools/clang-format.js +++ b/tools/clang-format.js @@ -6,7 +6,7 @@ const path = require('path'); const filesToCheck = ['*.h', '*.cc']; const CLANG_FORMAT_START = process.env.CLANG_FORMAT_START || 'main'; -function main(args) { +function main (args) { let fix = false; while (args.length > 0) { switch (args[0]) { @@ -18,7 +18,7 @@ function main(args) { args.shift(); } - let clangFormatPath = path.dirname(require.resolve('clang-format')); + const clangFormatPath = path.dirname(require.resolve('clang-format')); const options = ['--binary=node_modules/.bin/clang-format', '--style=file']; if (fix) { options.push(CLANG_FORMAT_START); diff --git a/tools/conversion.js b/tools/conversion.js index 5aef2c3ff..896c27ab3 100755 --- a/tools/conversion.js +++ b/tools/conversion.js @@ -1,6 +1,6 @@ #! /usr/bin/env node -'use strict' +'use strict'; const fs = require('fs'); const path = require('path'); @@ -15,255 +15,246 @@ if (!dir) { const NodeApiVersion = require('../package.json').version; const disable = args[1]; -if (disable != "--disable" && dir != "--disable") { +if (disable != '--disable' && dir != '--disable') { var ConfigFileOperations = { 'package.json': [ - [ /([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'], - [ /[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, '' ] + [/([ ]*)"dependencies": {/g, '$1"dependencies": {\n$1 "node-addon-api": "' + NodeApiVersion + '",'], + [/[ ]*"nan": *"[^"]+"(,|)[\n\r]/g, ''] ], 'binding.gyp': [ - [ /([ ]*)'include_dirs': \[/g, '$1\'include_dirs\': [\n$1 \'\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {' ], - [ /Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);\s+(\w+)\.Reset\((\1)\);\s+\1->SetClassName\((Nan::String::New|Nan::New<(v8::)*String>)\("(.+?)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$6", {'], - [ /Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {' ], - [ /Nan::New\(([\w\d:]+)\)->GetFunction\(\)/g, 'Napi::Function::New(env, $1)' ], - [ /Nan::New\(([\w\d:]+)\)->GetFunction()/g, 'Napi::Function::New(env, $1);' ], - [ /Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)' ], - [ /Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)' ], + [/v8::Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {'], + [/Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);\s+(\w+)\.Reset\((\1)\);\s+\1->SetClassName\((Nan::String::New|Nan::New<(v8::)*String>)\("(.+?)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$6", {'], + [/Local\s+(\w+)\s*=\s*Nan::New\([\w\d:]+\);(?:\w+->Reset\(\1\))?\s+\1->SetClassName\(Nan::String::New\("(\w+)"\)\);/g, 'Napi::Function $1 = DefineClass(env, "$2", {'], + [/Nan::New\(([\w\d:]+)\)->GetFunction\(\)/g, 'Napi::Function::New(env, $1)'], + [/Nan::New\(([\w\d:]+)\)->GetFunction()/g, 'Napi::Function::New(env, $1);'], + [/Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)'], + [/Nan::New\(([\w\d:]+)\)/g, 'Napi::Function::New(env, $1)'], // FunctionTemplate to FunctionReference - [ /Nan::Persistent<(v8::)*FunctionTemplate>/g, 'Napi::FunctionReference' ], - [ /Nan::Persistent<(v8::)*Function>/g, 'Napi::FunctionReference' ], - [ /v8::Local/g, 'Napi::FunctionReference' ], - [ /Local/g, 'Napi::FunctionReference' ], - [ /v8::FunctionTemplate/g, 'Napi::FunctionReference' ], - [ /FunctionTemplate/g, 'Napi::FunctionReference' ], - - - [ /([ ]*)Nan::SetPrototypeMethod\(\w+, "(\w+)", (\w+)\);/g, '$1InstanceMethod("$2", &$3),' ], - [ /([ ]*)(?:\w+\.Reset\(\w+\);\s+)?\(target\)\.Set\("(\w+)",\s*Nan::GetFunction\((\w+)\)\);/gm, + [/Nan::Persistent<(v8::)*FunctionTemplate>/g, 'Napi::FunctionReference'], + [/Nan::Persistent<(v8::)*Function>/g, 'Napi::FunctionReference'], + [/v8::Local/g, 'Napi::FunctionReference'], + [/Local/g, 'Napi::FunctionReference'], + [/v8::FunctionTemplate/g, 'Napi::FunctionReference'], + [/FunctionTemplate/g, 'Napi::FunctionReference'], + + [/([ ]*)Nan::SetPrototypeMethod\(\w+, "(\w+)", (\w+)\);/g, '$1InstanceMethod("$2", &$3),'], + [/([ ]*)(?:\w+\.Reset\(\w+\);\s+)?\(target\)\.Set\("(\w+)",\s*Nan::GetFunction\((\w+)\)\);/gm, '});\n\n' + '$1constructor = Napi::Persistent($3);\n' + '$1constructor.SuppressDestruct();\n' + - '$1target.Set("$2", $3);' ], - + '$1target.Set("$2", $3);'], // TODO: Other attribute combinations - [ /static_cast\(ReadOnly\s*\|\s*DontDelete\)/gm, - 'static_cast(napi_enumerable | napi_configurable)' ], + [/static_cast\(ReadOnly\s*\|\s*DontDelete\)/gm, + 'static_cast(napi_enumerable | napi_configurable)'], - [ /([\w\d:<>]+?)::Cast\((.+?)\)/g, '$2.As<$1>()' ], + [/([\w\d:<>]+?)::Cast\((.+?)\)/g, '$2.As<$1>()'], - [ /\*Nan::Utf8String\(([^)]+)\)/g, '$1->As().Utf8Value().c_str()' ], - [ /Nan::Utf8String +(\w+)\(([^)]+)\)/g, 'std::string $1 = $2.As()' ], - [ /Nan::Utf8String/g, 'std::string' ], + [/\*Nan::Utf8String\(([^)]+)\)/g, '$1->As().Utf8Value().c_str()'], + [/Nan::Utf8String +(\w+)\(([^)]+)\)/g, 'std::string $1 = $2.As()'], + [/Nan::Utf8String/g, 'std::string'], - [ /v8::String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)' ], - [ /String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)' ], - [ /\.length\(\)/g, '.Length()' ], + [/v8::String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)'], + [/String::Utf8Value (.+?)\((.+?)\)/g, 'Napi::String $1(env, $2)'], + [/\.length\(\)/g, '.Length()'], - [ /Nan::MakeCallback\(([^,]+),[\s\\]+([^,]+),/gm, '$2.MakeCallback($1,' ], + [/Nan::MakeCallback\(([^,]+),[\s\\]+([^,]+),/gm, '$2.MakeCallback($1,'], - [ /class\s+(\w+)\s*:\s*public\s+Nan::ObjectWrap/g, 'class $1 : public Napi::ObjectWrap<$1>' ], - [ /(\w+)\(([^\)]*)\)\s*:\s*Nan::ObjectWrap\(\)\s*(,)?/gm, '$1($2) : Napi::ObjectWrap<$1>()$3' ], + [/class\s+(\w+)\s*:\s*public\s+Nan::ObjectWrap/g, 'class $1 : public Napi::ObjectWrap<$1>'], + [/(\w+)\(([^\)]*)\)\s*:\s*Nan::ObjectWrap\(\)\s*(,)?/gm, '$1($2) : Napi::ObjectWrap<$1>()$3'], // HandleOKCallback to OnOK - [ /HandleOKCallback/g, 'OnOK' ], + [/HandleOKCallback/g, 'OnOK'], // HandleErrorCallback to OnError - [ /HandleErrorCallback/g, 'OnError' ], + [/HandleErrorCallback/g, 'OnError'], // ex. .As() to .As() - [ /\.As\(\)/g, '.As()' ], - [ /\.As<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As()' ], + [/\.As\(\)/g, '.As()'], + [/\.As<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>\(\)/g, '.As()'], // ex. Nan::New(info[0]) to Napi::Number::New(info[0]) - [ /Nan::New<(v8::)*Integer>\((.+?)\)/g, 'Napi::Number::New(env, $2)' ], - [ /Nan::New\(([0-9\.]+)\)/g, 'Napi::Number::New(env, $1)' ], - [ /Nan::New<(v8::)*String>\("(.+?)"\)/g, 'Napi::String::New(env, "$2")' ], - [ /Nan::New\("(.+?)"\)/g, 'Napi::String::New(env, "$1")' ], - [ /Nan::New<(v8::)*(.+?)>\(\)/g, 'Napi::$2::New(env)' ], - [ /Nan::New<(.+?)>\(\)/g, 'Napi::$1::New(env)' ], - [ /Nan::New<(v8::)*(.+?)>\(/g, 'Napi::$2::New(env, ' ], - [ /Nan::New<(.+?)>\(/g, 'Napi::$1::New(env, ' ], - [ /Nan::NewBuffer\(/g, 'Napi::Buffer::New(env, ' ], + [/Nan::New<(v8::)*Integer>\((.+?)\)/g, 'Napi::Number::New(env, $2)'], + [/Nan::New\(([0-9\.]+)\)/g, 'Napi::Number::New(env, $1)'], + [/Nan::New<(v8::)*String>\("(.+?)"\)/g, 'Napi::String::New(env, "$2")'], + [/Nan::New\("(.+?)"\)/g, 'Napi::String::New(env, "$1")'], + [/Nan::New<(v8::)*(.+?)>\(\)/g, 'Napi::$2::New(env)'], + [/Nan::New<(.+?)>\(\)/g, 'Napi::$1::New(env)'], + [/Nan::New<(v8::)*(.+?)>\(/g, 'Napi::$2::New(env, '], + [/Nan::New<(.+?)>\(/g, 'Napi::$1::New(env, '], + [/Nan::NewBuffer\(/g, 'Napi::Buffer::New(env, '], // TODO: Properly handle this - [ /Nan::New\(/g, 'Napi::New(env, ' ], + [/Nan::New\(/g, 'Napi::New(env, '], - [ /\.IsInt32\(\)/g, '.IsNumber()' ], - [ /->IsInt32\(\)/g, '.IsNumber()' ], + [/\.IsInt32\(\)/g, '.IsNumber()'], + [/->IsInt32\(\)/g, '.IsNumber()'], - - [ /(.+?)->BooleanValue\(\)/g, '$1.As().Value()' ], - [ /(.+?)->Int32Value\(\)/g, '$1.As().Int32Value()' ], - [ /(.+?)->Uint32Value\(\)/g, '$1.As().Uint32Value()' ], - [ /(.+?)->IntegerValue\(\)/g, '$1.As().Int64Value()' ], - [ /(.+?)->NumberValue\(\)/g, '$1.As().DoubleValue()' ], + [/(.+?)->BooleanValue\(\)/g, '$1.As().Value()'], + [/(.+?)->Int32Value\(\)/g, '$1.As().Int32Value()'], + [/(.+?)->Uint32Value\(\)/g, '$1.As().Uint32Value()'], + [/(.+?)->IntegerValue\(\)/g, '$1.As().Int64Value()'], + [/(.+?)->NumberValue\(\)/g, '$1.As().DoubleValue()'], // ex. Nan::To(info[0]) to info[0].Value() - [ /Nan::To\((.+?)\)/g, '$2.To()' ], - [ /Nan::To<(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To()' ], + [/Nan::To\((.+?)\)/g, '$2.To()'], + [/Nan::To<(Boolean|String|Number|Object|Array|Symbol|Function)>\((.+?)\)/g, '$2.To()'], // ex. Nan::To(info[0]) to info[0].As().Value() - [ /Nan::To\((.+?)\)/g, '$1.As().Value()' ], + [/Nan::To\((.+?)\)/g, '$1.As().Value()'], // ex. Nan::To(info[0]) to info[0].As().Int32Value() - [ /Nan::To\((.+?)\)/g, '$1.As().Int32Value()' ], + [/Nan::To\((.+?)\)/g, '$1.As().Int32Value()'], // ex. Nan::To(info[0]) to info[0].As().Int32Value() - [ /Nan::To\((.+?)\)/g, '$1.As().Int32Value()' ], + [/Nan::To\((.+?)\)/g, '$1.As().Int32Value()'], // ex. Nan::To(info[0]) to info[0].As().Uint32Value() - [ /Nan::To\((.+?)\)/g, '$1.As().Uint32Value()' ], + [/Nan::To\((.+?)\)/g, '$1.As().Uint32Value()'], // ex. Nan::To(info[0]) to info[0].As().Int64Value() - [ /Nan::To\((.+?)\)/g, '$1.As().Int64Value()' ], + [/Nan::To\((.+?)\)/g, '$1.As().Int64Value()'], // ex. Nan::To(info[0]) to info[0].As().FloatValue() - [ /Nan::To\((.+?)\)/g, '$1.As().FloatValue()' ], + [/Nan::To\((.+?)\)/g, '$1.As().FloatValue()'], // ex. Nan::To(info[0]) to info[0].As().DoubleValue() - [ /Nan::To\((.+?)\)/g, '$1.As().DoubleValue()' ], - - [ /Nan::New\((\w+)\)->HasInstance\((\w+)\)/g, '$2.InstanceOf($1.Value())' ], + [/Nan::To\((.+?)\)/g, '$1.As().DoubleValue()'], - [ /Nan::Has\(([^,]+),\s*/gm, '($1).Has(' ], - [ /\.Has\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Has($1)' ], - [ /\.Has\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Has($1)' ], + [/Nan::New\((\w+)\)->HasInstance\((\w+)\)/g, '$2.InstanceOf($1.Value())'], - [ /Nan::Get\(([^,]+),\s*/gm, '($1).Get(' ], - [ /\.Get\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Get($1)' ], - [ /\.Get\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Get($1)' ], + [/Nan::Has\(([^,]+),\s*/gm, '($1).Has('], + [/\.Has\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Has($1)'], + [/\.Has\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Has($1)'], - [ /Nan::Set\(([^,]+),\s*/gm, '($1).Set(' ], - [ /\.Set\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\s*,/gm, '.Set($1,' ], - [ /\.Set\([\s|\\]*Nan::New\(([^)]+)\)\s*,/gm, '.Set($1,' ], + [/Nan::Get\(([^,]+),\s*/gm, '($1).Get('], + [/\.Get\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\)/gm, '.Get($1)'], + [/\.Get\([\s|\\]*Nan::New\(([^)]+)\)\)/gm, '.Get($1)'], + [/Nan::Set\(([^,]+),\s*/gm, '($1).Set('], + [/\.Set\([\s|\\]*Nan::New<(v8::)*String>\(([^)]+)\)\s*,/gm, '.Set($1,'], + [/\.Set\([\s|\\]*Nan::New\(([^)]+)\)\s*,/gm, '.Set($1,'], // ex. node::Buffer::HasInstance(info[0]) to info[0].IsBuffer() - [ /node::Buffer::HasInstance\((.+?)\)/g, '$1.IsBuffer()' ], + [/node::Buffer::HasInstance\((.+?)\)/g, '$1.IsBuffer()'], // ex. node::Buffer::Length(info[0]) to info[0].Length() - [ /node::Buffer::Length\((.+?)\)/g, '$1.As>().Length()' ], + [/node::Buffer::Length\((.+?)\)/g, '$1.As>().Length()'], // ex. node::Buffer::Data(info[0]) to info[0].Data() - [ /node::Buffer::Data\((.+?)\)/g, '$1.As>().Data()' ], - [ /Nan::CopyBuffer\(/g, 'Napi::Buffer::Copy(env, ' ], + [/node::Buffer::Data\((.+?)\)/g, '$1.As>().Data()'], + [/Nan::CopyBuffer\(/g, 'Napi::Buffer::Copy(env, '], // Nan::AsyncQueueWorker(worker) - [ /Nan::AsyncQueueWorker\((.+)\);/g, '$1.Queue();' ], - [ /Nan::(Undefined|Null|True|False)\(\)/g, 'env.$1()' ], + [/Nan::AsyncQueueWorker\((.+)\);/g, '$1.Queue();'], + [/Nan::(Undefined|Null|True|False)\(\)/g, 'env.$1()'], // Nan::ThrowError(error) to Napi::Error::New(env, error).ThrowAsJavaScriptException() - [ /([ ]*)return Nan::Throw(\w*?)Error\((.+?)\);/g, '$1Napi::$2Error::New(env, $3).ThrowAsJavaScriptException();\n$1return env.Null();' ], - [ /Nan::Throw(\w*?)Error\((.+?)\);\n(\s*)return;/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n$3return env.Null();' ], - [ /Nan::Throw(\w*?)Error\((.+?)\);/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n' ], + [/([ ]*)return Nan::Throw(\w*?)Error\((.+?)\);/g, '$1Napi::$2Error::New(env, $3).ThrowAsJavaScriptException();\n$1return env.Null();'], + [/Nan::Throw(\w*?)Error\((.+?)\);\n(\s*)return;/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n$3return env.Null();'], + [/Nan::Throw(\w*?)Error\((.+?)\);/g, 'Napi::$1Error::New(env, $2).ThrowAsJavaScriptException();\n'], // Nan::RangeError(error) to Napi::RangeError::New(env, error) - [ /Nan::(\w*?)Error\((.+)\)/g, 'Napi::$1Error::New(env, $2)' ], + [/Nan::(\w*?)Error\((.+)\)/g, 'Napi::$1Error::New(env, $2)'], - [ /Nan::Set\((.+?),\n* *(.+?),\n* *(.+?),\n* *(.+?)\)/g, '$1.Set($2, $3, $4)' ], + [/Nan::Set\((.+?),\n* *(.+?),\n* *(.+?),\n* *(.+?)\)/g, '$1.Set($2, $3, $4)'], - [ /Nan::(Escapable)?HandleScope\s+(\w+)\s*;/g, 'Napi::$1HandleScope $2(env);' ], - [ /Nan::(Escapable)?HandleScope/g, 'Napi::$1HandleScope' ], - [ /Nan::ForceSet\(([^,]+), ?/g, '$1->DefineProperty(' ], - [ /\.ForceSet\(Napi::String::New\(env, "(\w+)"\),\s*?/g, '.DefineProperty("$1", ' ], + [/Nan::(Escapable)?HandleScope\s+(\w+)\s*;/g, 'Napi::$1HandleScope $2(env);'], + [/Nan::(Escapable)?HandleScope/g, 'Napi::$1HandleScope'], + [/Nan::ForceSet\(([^,]+), ?/g, '$1->DefineProperty('], + [/\.ForceSet\(Napi::String::New\(env, "(\w+)"\),\s*?/g, '.DefineProperty("$1", '], // [ /Nan::GetPropertyNames\(([^,]+)\)/, '$1->GetPropertyNames()' ], - [ /Nan::Equals\(([^,]+),/g, '$1.StrictEquals(' ], - - - [ /(.+)->Set\(/g, '$1.Set\(' ], - - - [ /Nan::Callback/g, 'Napi::FunctionReference' ], - + [/Nan::Equals\(([^,]+),/g, '$1.StrictEquals('], - [ /Nan::Persistent/g, 'Napi::ObjectReference' ], - [ /Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target/g, 'Napi::Env& env, Napi::Object& target' ], + [/(.+)->Set\(/g, '$1.Set\('], - [ /(\w+)\*\s+(\w+)\s*=\s*Nan::ObjectWrap::Unwrap<\w+>\(info\.This\(\)\);/g, '$1* $2 = this;' ], - [ /Nan::ObjectWrap::Unwrap<(\w+)>\((.*)\);/g, '$2.Unwrap<$1>();' ], + [/Nan::Callback/g, 'Napi::FunctionReference'], - [ /Nan::NAN_METHOD_RETURN_TYPE/g, 'void' ], - [ /NAN_INLINE/g, 'inline' ], + [/Nan::Persistent/g, 'Napi::ObjectReference'], + [/Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target/g, 'Napi::Env& env, Napi::Object& target'], - [ /Nan::NAN_METHOD_ARGS_TYPE/g, 'const Napi::CallbackInfo&' ], - [ /NAN_METHOD\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], - [ /static\s*NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)' ], - [ /NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)' ], - [ /static\s*NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)' ], - [ /NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)' ], - [ /void Init\((v8::)*Local<(v8::)*Object> exports\)/g, 'Napi::Object Init(Napi::Env env, Napi::Object exports)' ], - [ /NAN_MODULE_INIT\(([\w\d:]+?)\);/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports);' ], - [ /NAN_MODULE_INIT\(([\w\d:]+?)\)/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports)' ], + [/(\w+)\*\s+(\w+)\s*=\s*Nan::ObjectWrap::Unwrap<\w+>\(info\.This\(\)\);/g, '$1* $2 = this;'], + [/Nan::ObjectWrap::Unwrap<(\w+)>\((.*)\);/g, '$2.Unwrap<$1>();'], + [/Nan::NAN_METHOD_RETURN_TYPE/g, 'void'], + [/NAN_INLINE/g, 'inline'], - [ /::(Init(?:ialize)?)\(target\)/g, '::$1(env, target, module)' ], - [ /constructor_template/g, 'constructor' ], + [/Nan::NAN_METHOD_ARGS_TYPE/g, 'const Napi::CallbackInfo&'], + [/NAN_METHOD\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], + [/static\s*NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], + [/NAN_GETTER\(([\w\d:]+?)\)/g, 'Napi::Value $1(const Napi::CallbackInfo& info)'], + [/static\s*NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)'], + [/NAN_SETTER\(([\w\d:]+?)\)/g, 'void $1(const Napi::CallbackInfo& info, const Napi::Value& value)'], + [/void Init\((v8::)*Local<(v8::)*Object> exports\)/g, 'Napi::Object Init(Napi::Env env, Napi::Object exports)'], + [/NAN_MODULE_INIT\(([\w\d:]+?)\);/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports);'], + [/NAN_MODULE_INIT\(([\w\d:]+?)\)/g, 'Napi::Object $1(Napi::Env env, Napi::Object exports)'], - [ /Nan::FunctionCallbackInfo<(v8::)?Value>[ ]*& [ ]*info\)[ ]*{\n*([ ]*)/gm, 'Napi::CallbackInfo& info) {\n$2Napi::Env env = info.Env();\n$2' ], - [ /Nan::FunctionCallbackInfo<(v8::)*Value>\s*&\s*info\);/g, 'Napi::CallbackInfo& info);' ], - [ /Nan::FunctionCallbackInfo<(v8::)*Value>\s*&/g, 'Napi::CallbackInfo&' ], + [/::(Init(?:ialize)?)\(target\)/g, '::$1(env, target, module)'], + [/constructor_template/g, 'constructor'], - [ /Buffer::HasInstance\(([^)]+)\)/g, '$1.IsBuffer()' ], + [/Nan::FunctionCallbackInfo<(v8::)?Value>[ ]*& [ ]*info\)[ ]*{\n*([ ]*)/gm, 'Napi::CallbackInfo& info) {\n$2Napi::Env env = info.Env();\n$2'], + [/Nan::FunctionCallbackInfo<(v8::)*Value>\s*&\s*info\);/g, 'Napi::CallbackInfo& info);'], + [/Nan::FunctionCallbackInfo<(v8::)*Value>\s*&/g, 'Napi::CallbackInfo&'], - [ /info\[(\d+)\]->/g, 'info[$1].' ], - [ /info\[([\w\d]+)\]->/g, 'info[$1].' ], - [ /info\.This\(\)->/g, 'info.This().' ], - [ /->Is(Object|String|Int32|Number)\(\)/g, '.Is$1()' ], - [ /info.GetReturnValue\(\).SetUndefined\(\)/g, 'return env.Undefined()' ], - [ /info\.GetReturnValue\(\)\.Set\(((\n|.)+?)\);/g, 'return $1;' ], + [/Buffer::HasInstance\(([^)]+)\)/g, '$1.IsBuffer()'], + [/info\[(\d+)\]->/g, 'info[$1].'], + [/info\[([\w\d]+)\]->/g, 'info[$1].'], + [/info\.This\(\)->/g, 'info.This().'], + [/->Is(Object|String|Int32|Number)\(\)/g, '.Is$1()'], + [/info.GetReturnValue\(\).SetUndefined\(\)/g, 'return env.Undefined()'], + [/info\.GetReturnValue\(\)\.Set\(((\n|.)+?)\);/g, 'return $1;'], // ex. Local to Napi::Value - [ /v8::Local/g, 'Napi::$1' ], - [ /Local<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1' ], + [/v8::Local/g, 'Napi::$1'], + [/Local<(Value|Boolean|String|Number|Object|Array|Symbol|External|Function)>/g, 'Napi::$1'], // Declare an env in helper functions that take a Napi::Value - [ /(\w+)\(Napi::Value (\w+)(,\s*[^\()]+)?\)\s*{\n*([ ]*)/gm, '$1(Napi::Value $2$3) {\n$4Napi::Env env = $2.Env();\n$4' ], + [/(\w+)\(Napi::Value (\w+)(,\s*[^\()]+)?\)\s*{\n*([ ]*)/gm, '$1(Napi::Value $2$3) {\n$4Napi::Env env = $2.Env();\n$4'], // delete #include and/or - [ /#include +(<|")(?:node|nan).h("|>)/g, "#include $1napi.h$2\n#include $1uv.h$2" ], + [/#include +(<|")(?:node|nan).h("|>)/g, '#include $1napi.h$2\n#include $1uv.h$2'], // NODE_MODULE to NODE_API_MODULE - [ /NODE_MODULE/g, 'NODE_API_MODULE' ], - [ /Nan::/g, 'Napi::' ], - [ /nan.h/g, 'napi.h' ], + [/NODE_MODULE/g, 'NODE_API_MODULE'], + [/Nan::/g, 'Napi::'], + [/nan.h/g, 'napi.h'], // delete .FromJust() - [ /\.FromJust\(\)/g, '' ], + [/\.FromJust\(\)/g, ''], // delete .ToLocalCheck() - [ /\.ToLocalChecked\(\)/g, '' ], - [ /^.*->SetInternalFieldCount\(.*$/gm, '' ], + [/\.ToLocalChecked\(\)/g, ''], + [/^.*->SetInternalFieldCount\(.*$/gm, ''], // replace using node; and/or using v8; to using Napi; - [ /using (node|v8);/g, 'using Napi;' ], - [ /using namespace (node|Nan|v8);/g, 'using namespace Napi;' ], + [/using (node|v8);/g, 'using Napi;'], + [/using namespace (node|Nan|v8);/g, 'using namespace Napi;'], // delete using v8::Local; - [ /using v8::Local;\n/g, '' ], + [/using v8::Local;\n/g, ''], // replace using v8::XXX; with using Napi::XXX - [ /using v8::([A-Za-z]+);/g, 'using Napi::$1;' ], + [/using v8::([A-Za-z]+);/g, 'using Napi::$1;'] ]; -var paths = listFiles(dir); -paths.forEach(function(dirEntry) { - var filename = dirEntry.split('\\').pop().split('/').pop(); +const paths = listFiles(dir); +paths.forEach(function (dirEntry) { + const filename = dirEntry.split('\\').pop().split('/').pop(); // Check whether the file is a source file or a config file // then execute function accordingly - var sourcePattern = /.+\.h|.+\.cc|.+\.cpp/; + const sourcePattern = /.+\.h|.+\.cc|.+\.cpp/; if (sourcePattern.test(filename)) { convertFile(dirEntry, SourceFileOperations); } else if (ConfigFileOperations[filename] != null) { @@ -271,12 +262,12 @@ paths.forEach(function(dirEntry) { } }); -function listFiles(dir, filelist) { - var files = fs.readdirSync(dir); +function listFiles (dir, filelist) { + const files = fs.readdirSync(dir); filelist = filelist || []; - files.forEach(function(file) { + files.forEach(function (file) { if (file === 'node_modules') { - return + return; } if (fs.statSync(path.join(dir, file)).isDirectory()) { @@ -288,21 +279,21 @@ function listFiles(dir, filelist) { return filelist; } -function convert(content, operations) { - for (let i = 0; i < operations.length; i ++) { - let operation = operations[i]; +function convert (content, operations) { + for (let i = 0; i < operations.length; i++) { + const operation = operations[i]; content = content.replace(operation[0], operation[1]); } return content; } -function convertFile(fileName, operations) { - fs.readFile(fileName, "utf-8", function (err, file) { +function convertFile (fileName, operations) { + fs.readFile(fileName, 'utf-8', function (err, file) { if (err) throw err; file = convert(file, operations); - fs.writeFile(fileName, file, function(err){ + fs.writeFile(fileName, file, function (err) { if (err) throw err; }); }); diff --git a/unit-test/binding-file-template.js b/unit-test/binding-file-template.js index eebcfa642..341779857 100644 --- a/unit-test/binding-file-template.js +++ b/unit-test/binding-file-template.js @@ -1,27 +1,27 @@ -module.exports.generateFileContent = function(configs) { +module.exports.generateFileContent = function (bindingConfigurations) { const content = []; const inits = []; const exports = []; - for (let config of configs) { + for (const config of bindingConfigurations) { inits.push(`Object Init${config.objectName}(Env env);`); exports.push(`exports.Set(\"${config.propertyName}\", Init${config.objectName}(env));`); } - content.push("#include \"napi.h\""); - content.push("using namespace Napi;"); + content.push('#include "napi.h"'); + content.push('using namespace Napi;'); - //content.push("Object InitName(Env env);"); + // content.push("Object InitName(Env env);"); inits.forEach(init => content.push(init)); - content.push("Object Init(Env env, Object exports) {"); + content.push('Object Init(Env env, Object exports) {'); - //content.push("exports.Set(\"name\", InitName(env));"); + // content.push("exports.Set(\"name\", InitName(env));"); exports.forEach(exp => content.push(exp)); - content.push("return exports;"); - content.push("}"); - content.push("NODE_API_MODULE(addon, Init);"); + content.push('return exports;'); + content.push('}'); + content.push('NODE_API_MODULE(addon, Init);'); return Promise.resolve(content.join('\r\n')); -} +}; diff --git a/unit-test/exceptions.js b/unit-test/exceptions.js index 8dd788c5c..1e807f42e 100644 --- a/unit-test/exceptions.js +++ b/unit-test/exceptions.js @@ -1,20 +1,20 @@ module.exports = { - 'nouns': { - 'constructor': 'constructor', - 'threadsafe': 'threadSafe', - 'objectwrap': 'objectWrap', + nouns: { + constructor: 'constructor', + threadsafe: 'threadSafe', + objectwrap: 'objectWrap' }, - 'exportNames': { - 'AsyncWorkerPersistent': 'PersistentAsyncWorker', + exportNames: { + AsyncWorkerPersistent: 'PersistentAsyncWorker' }, - 'propertyNames': { - 'async_worker_persistent': 'persistentasyncworker', - 'objectwrap_constructor_exception':'objectwrapConstructorException', + propertyNames: { + async_worker_persistent: 'persistentasyncworker', + objectwrap_constructor_exception: 'objectwrapConstructorException' }, - 'skipBinding': [ + skipBinding: [ 'global_object_delete_property', 'global_object_get_property', 'global_object_has_own_property', - 'global_object_set_property', + 'global_object_set_property' ] -}; \ No newline at end of file +}; diff --git a/unit-test/generate-binding-cc.js b/unit-test/generate-binding-cc.js index 7cde10d51..fc1538777 100644 --- a/unit-test/generate-binding-cc.js +++ b/unit-test/generate-binding-cc.js @@ -7,17 +7,17 @@ const generateFileContent = require('./binding-file-template').generateFileConte const buildDirs = listOfTestModules.dirs; const buildFiles = listOfTestModules.files; -function generateBindingConfigurations() { - const configs = []; - +function generateBindingConfigurations () { const testFilesToBind = process.argv.slice(2); console.log('test modules to bind: ', testFilesToBind); + const configs = []; + testFilesToBind.forEach((file) => { const configName = file.split('.cc')[0]; if (buildDirs[configName]) { - for (let file of buildDirs[configName]) { + for (const file of buildDirs[configName]) { if (exceptions.skipBinding.includes(file)) continue; configs.push(buildFiles[file]); } @@ -31,11 +31,38 @@ function generateBindingConfigurations() { return Promise.resolve(configs); } -function writeToBindingFile(content) { - const generatedFilePath = path.join(__dirname, 'generated', 'binding.cc' ); - fs.writeFileSync(generatedFilePath , "" ); - fs.writeFileSync(generatedFilePath, content, { flag: "a" } ); - console.log('generated binding file ', generatedFilePath, new Date()); +function writeToBindingFile (content) { + const generatedFilePath = path.join(__dirname, 'generated', 'binding.cc'); + fs.writeFileSync(generatedFilePath, ''); + fs.writeFileSync(generatedFilePath, content, { flag: 'a' }); + console.log('generated binding file ', generatedFilePath, new Date()); } generateBindingConfigurations().then(generateFileContent).then(writeToBindingFile); + +/** + * + * Test cases + * @fires only when run directly from terminal + * + * + * + */ +if (require.main === module) { + const assert = require('assert'); + + const setArgsAndCall = (fn, filterCondition) => { process.argv = [null, null, ...filterCondition.split(' ')]; return fn(); }; + const assertPromise = (promise, expectedVal) => promise.then((val) => assert.deepEqual(val, expectedVal)).catch(console.log); + + const expectedVal = [{ + dir: '', + objectName: 'AsyncProgressWorker', + propertyName: 'async_progress_worker' + }, + { + dir: '', + objectName: 'PersistentAsyncWorker', + propertyName: 'persistentasyncworker' + }]; + assertPromise(setArgsAndCall(generateBindingConfigurations, 'async_progress_worker async_worker_persistent'), expectedVal); +} diff --git a/unit-test/injectTestParams.js b/unit-test/injectTestParams.js index 3e1a36263..e61eab5af 100644 --- a/unit-test/injectTestParams.js +++ b/unit-test/injectTestParams.js @@ -4,22 +4,33 @@ const listOfTestModules = require('./listOfTestModules'); const buildDirs = listOfTestModules.dirs; const buildFiles = listOfTestModules.files; +/** + * + * @returns : list of files to compile by node-gyp + * @param : none + * @requires : picks `filter` parameter from process.env + * This function is used as an utility method to inject a list of files to compile into binding.gyp + * + * + */ module.exports.filesToCompile = function () { + !fs.existsSync('./generated/') && fs.mkdirSync('./generated/', { recursive: true }); + const filterCondition = require('./matchModules').matchWildCards(process.env.filter || ''); - let files_to_compile = './generated/binding.cc test_helper.h'; - let conditions = filterCondition.split(' ').length ? filterCondition.split(' ') : [filterCondition]; - let files = []; + const files_to_compile = './generated/binding.cc test_helper.h'; + const conditions = filterCondition.split(' ').length ? filterCondition.split(' ') : [filterCondition]; + const files = []; - for (let matchCondition of conditions) { + for (const matchCondition of conditions) { if (buildDirs[matchCondition.toLowerCase()]) { - for (let file of buildDirs[matchCondition.toLowerCase()] ) { + for (const file of buildDirs[matchCondition.toLowerCase()]) { const config = buildFiles[file]; - const separator = config.dir.length ? '/' : '' + const separator = config.dir.length ? '/' : ''; files.push(config.dir + separator + file); } } else if (buildFiles[matchCondition.toLowerCase()]) { const config = buildFiles[matchCondition.toLowerCase()]; - const separator = config.dir.length ? '/' : '' + const separator = config.dir.length ? '/' : ''; files.push(config.dir + separator + matchCondition.toLowerCase()); } } @@ -32,13 +43,27 @@ module.exports.filesToCompile = function () { return `${files_to_compile} ${addedFiles}`; }; +/** + * @returns list of test files to bind exported init functions + * @param : none + * @requires : picks `filter` parameter from process.env + * This function is used as an utility method by the generateBindingCC step in binding.gyp + * + */ module.exports.filesForBinding = function () { const filterCondition = require('./matchModules').matchWildCards(process.env.filter || ''); fs.writeFileSync(__dirname + '/generated/bindingList', filterCondition); return filterCondition; }; - +/** + * + * Test cases + * @fires only when run directly from terminal + * + * + * + */ if (require.main === module) { const assert = require('assert'); @@ -60,10 +85,10 @@ if (require.main === module) { '../test/typed_threadsafe_function/typed_threadsafe_function_ptr.cc', '../test/typed_threadsafe_function/typed_threadsafe_function_sum.cc', '../test/typed_threadsafe_function/typed_threadsafe_function_unref.cc' - ] + ]; assert.strictEqual(setEnvAndCall(exports.filesToCompile, 'threadsafe_function typed_threadsafe_function'), expectedFilesToMatch.join(' ')); assert.strictEqual(setEnvAndCall(exports.filesToCompile, 'objectwrap'), './generated/binding.cc test_helper.h ../test/objectwrap.cc'); - console.log('ALL tests passed') + console.log('ALL tests passed'); } diff --git a/unit-test/listOfTestModules.js b/unit-test/listOfTestModules.js index 20b712224..788aea81a 100644 --- a/unit-test/listOfTestModules.js +++ b/unit-test/listOfTestModules.js @@ -5,7 +5,7 @@ const exceptions = require('./exceptions'); const buildFiles = {}; const buidDirs = {}; -function getExportObjectName(fileName) { +function getExportObjectName (fileName) { fileName = fileName.split('_').map(token => exceptions.nouns[token] ? exceptions.nouns[token] : token).join('_'); const str = fileName.replace(/(\_\w)/g, (k) => k[1].toUpperCase()); const exportObjectName = str.charAt(0).toUpperCase() + str.substring(1); @@ -15,14 +15,14 @@ function getExportObjectName(fileName) { return exportObjectName; } -function getExportPropertyName(fileName) { +function getExportPropertyName (fileName) { if (exceptions.propertyNames[fileName.toLowerCase()]) { return exceptions.propertyNames[fileName.toLowerCase()]; } return fileName; } -function listOfTestModules(currentDirectory = __dirname + '/../test', pre = '') { +function listOfTestModules (currentDirectory = __dirname + '/../test', pre = '') { fs.readdirSync(currentDirectory).forEach((file) => { if (file === 'binding.cc' || file === 'binding.gyp' || @@ -31,17 +31,17 @@ function listOfTestModules(currentDirectory = __dirname + '/../test', pre = '') file === 'thunking_manual.cc' || file === 'addon_build' || file[0] === '.') { - return; + return; } const absoluteFilepath = path.join(currentDirectory, file); const fileName = file.toLowerCase().replace('.cc', ''); if (fs.statSync(absoluteFilepath).isDirectory()) { - buidDirs[fileName] = [] + buidDirs[fileName] = []; listOfTestModules(absoluteFilepath, pre + file + '/'); } else { if (!file.toLowerCase().endsWith('.cc')) return; if (currentDirectory.trim().split('/test/').length > 1) { - buidDirs[currentDirectory.split('/test/')[1].toLowerCase()].push(fileName) + buidDirs[currentDirectory.split('/test/')[1].toLowerCase()].push(fileName); } const relativePath = (currentDirectory.split(`${fileName}.cc`)[0]).split('/test/')[1] || ''; buildFiles[fileName] = { dir: relativePath, propertyName: getExportPropertyName(fileName), objectName: getExportObjectName(fileName) }; @@ -55,16 +55,23 @@ module.exports = { files: buildFiles }; - +/** + * + * Test cases + * @fires only when run directly from terminal + * + * + * + */ if (require.main === module) { - const assert = require('assert') - assert.strictEqual(getExportObjectName('objectwrap_constructor_exception'), 'ObjectWrapConstructorException') - assert.strictEqual(getExportObjectName('typed_threadsafe_function'), 'TypedThreadSafeFunction') - assert.strictEqual(getExportObjectName('objectwrap_removewrap'), 'ObjectWrapRemovewrap') - assert.strictEqual(getExportObjectName('function_reference'), 'FunctionReference') - assert.strictEqual(getExportObjectName('async_worker'), 'AsyncWorker') - assert.strictEqual(getExportObjectName('async_progress_worker'), 'AsyncProgressWorker') - assert.strictEqual(getExportObjectName('async_worker_persistent'), 'PersistentAsyncWorker') + const assert = require('assert'); + assert.strictEqual(getExportObjectName('objectwrap_constructor_exception'), 'ObjectWrapConstructorException'); + assert.strictEqual(getExportObjectName('typed_threadsafe_function'), 'TypedThreadSafeFunction'); + assert.strictEqual(getExportObjectName('objectwrap_removewrap'), 'ObjectWrapRemovewrap'); + assert.strictEqual(getExportObjectName('function_reference'), 'FunctionReference'); + assert.strictEqual(getExportObjectName('async_worker'), 'AsyncWorker'); + assert.strictEqual(getExportObjectName('async_progress_worker'), 'AsyncProgressWorker'); + assert.strictEqual(getExportObjectName('async_worker_persistent'), 'PersistentAsyncWorker'); - console.log('ALL tests passed') + console.log('ALL tests passed'); } diff --git a/unit-test/matchModules.js b/unit-test/matchModules.js index 8ce531cba..935370d92 100644 --- a/unit-test/matchModules.js +++ b/unit-test/matchModules.js @@ -2,28 +2,27 @@ const listOfTestModules = require('./listOfTestModules'); const buildDirs = listOfTestModules.dirs; const buildFiles = listOfTestModules.files; -function isWildcard(filter) { +function isWildcard (filter) { if (filter.includes('*')) return true; return false; } -function filterBy(wildcard, item) { - return new RegExp('^' + wildcard.replace(/\*/g, '.*') + '$').test(item) +function filterBy (wildcard, item) { + return new RegExp('^' + wildcard.replace(/\*/g, '.*') + '$').test(item); } -function matchWildCards(filterCondition) { - let conditions = filterCondition.split(' ').length ? filterCondition.split(' ') : [filterCondition]; - let matches = []; +function matchWildCards (filterCondition) { + const conditions = filterCondition.split(' ').length ? filterCondition.split(' ') : [filterCondition]; + const matches = []; - for (let filter of conditions) { + for (const filter of conditions) { if (isWildcard(filter)) { const matchedDirs = Object.keys(buildDirs).filter(e => filterBy(filter, e)); if (matchedDirs.length) { matches.push(matchedDirs.join(' ')); } else { const matchedModules = Object.keys(buildFiles).filter(e => filterBy(filter, e)); - if (matchedModules.length) - matches.push(matchedModules.join(' ')); + if (matchedModules.length) { matches.push(matchedModules.join(' ')); } } } else { matches.push(filter); @@ -35,24 +34,32 @@ function matchWildCards(filterCondition) { module.exports.matchWildCards = matchWildCards; +/** + * + * Test cases + * @fires only when run directly from terminal + * + * + * + */ if (require.main === module) { - const assert = require('assert') - - assert.strictEqual(matchWildCards('typed*ex'), 'typed*ex') - assert.strictEqual(matchWildCards('typed*ex*'), 'typed_threadsafe_function_existing_tsfn') - assert.strictEqual(matchWildCards('async*'), 'async_context async_progress_queue_worker async_progress_worker async_worker async_worker_persistent') - assert.strictEqual(matchWildCards('typed*func'), 'typed*func') - assert.strictEqual(matchWildCards('typed*func*'), 'typed_threadsafe_function') - assert.strictEqual(matchWildCards('typed*function'), 'typed_threadsafe_function') - assert.strictEqual(matchWildCards('object*inh'), 'object*inh') - assert.strictEqual(matchWildCards('object*inh*'), 'objectwrap_multiple_inheritance') - assert.strictEqual(matchWildCards('*remove*'), 'objectwrap_removewrap') - assert.strictEqual(matchWildCards('*function'), 'threadsafe_function typed_threadsafe_function') - assert.strictEqual(matchWildCards('**function'), 'threadsafe_function typed_threadsafe_function') - assert.strictEqual(matchWildCards('a*w*p*'), 'async_worker_persistent') - assert.strictEqual(matchWildCards('fun*ref'), 'fun*ref') - assert.strictEqual(matchWildCards('fun*ref*'), 'function_reference') - assert.strictEqual(matchWildCards('*reference'), 'function_reference object_reference reference') - - console.log('ALL tests passed') + const assert = require('assert'); + + assert.strictEqual(matchWildCards('typed*ex'), 'typed*ex'); + assert.strictEqual(matchWildCards('typed*ex*'), 'typed_threadsafe_function_existing_tsfn'); + assert.strictEqual(matchWildCards('async*'), 'async_context async_progress_queue_worker async_progress_worker async_worker async_worker_persistent'); + assert.strictEqual(matchWildCards('typed*func'), 'typed*func'); + assert.strictEqual(matchWildCards('typed*func*'), 'typed_threadsafe_function'); + assert.strictEqual(matchWildCards('typed*function'), 'typed_threadsafe_function'); + assert.strictEqual(matchWildCards('object*inh'), 'object*inh'); + assert.strictEqual(matchWildCards('object*inh*'), 'objectwrap_multiple_inheritance'); + assert.strictEqual(matchWildCards('*remove*'), 'objectwrap_removewrap'); + assert.strictEqual(matchWildCards('*function'), 'threadsafe_function typed_threadsafe_function'); + assert.strictEqual(matchWildCards('**function'), 'threadsafe_function typed_threadsafe_function'); + assert.strictEqual(matchWildCards('a*w*p*'), 'async_worker_persistent'); + assert.strictEqual(matchWildCards('fun*ref'), 'fun*ref'); + assert.strictEqual(matchWildCards('fun*ref*'), 'function_reference'); + assert.strictEqual(matchWildCards('*reference'), 'function_reference object_reference reference'); + + console.log('ALL tests passed'); } diff --git a/unit-test/spawnTask.js b/unit-test/spawnTask.js index b14776481..20695fbe6 100644 --- a/unit-test/spawnTask.js +++ b/unit-test/spawnTask.js @@ -1,7 +1,7 @@ -const { spawn } = require("child_process"); +const { spawn } = require('child_process'); module.exports.runChildProcess = async function (command, options) { - const childProcess = spawn("node", [command], options); + const childProcess = spawn('node', [command], options); childProcess.stdout.on('data', data => { console.log(`${data}`); @@ -20,4 +20,4 @@ module.exports.runChildProcess = async function (command, options) { resolve(); }); }); -} +}; diff --git a/unit-test/test.js b/unit-test/test.js index 5d5667f04..9fa49174e 100644 --- a/unit-test/test.js +++ b/unit-test/test.js @@ -2,21 +2,21 @@ const path = require('path'); const runChildProcess = require('./spawnTask').runChildProcess; -const executeTests = async function() { +const executeTests = async function () { try { const workingDir = path.join(__dirname, '../'); const relativeBuildPath = path.join('../', 'unit-test'); const buildPath = path.join(__dirname, './unit-test'); - const envVars = { ...process.env, REL_BUILD_PATH: relativeBuildPath, BUILD_PATH: buildPath}; + const envVars = { ...process.env, REL_BUILD_PATH: relativeBuildPath, BUILD_PATH: buildPath }; console.log('Starting to run tests in ', buildPath, new Date()); - await runChildProcess('test', {cwd: workingDir, env: envVars}); + await runChildProcess('test', { cwd: workingDir, env: envVars }); console.log('Completed running tests', new Date()); - } catch(e) { + } catch (e) { console.log('Error occured running tests', new Date()); } -} +}; executeTests();