diff --git a/.eslintrc.yaml b/.eslintrc.yaml index 934c60d5dec558..69c5af9d305a3c 100644 --- a/.eslintrc.yaml +++ b/.eslintrc.yaml @@ -44,6 +44,7 @@ rules: # http://eslint.org/docs/rules/#best-practices accessor-pairs: error dot-location: [error, property] + dot-notation: error eqeqeq: [error, smart] no-fallthrough: error no-global-assign: error diff --git a/README.md b/README.md index e537407c8685bd..7acb759ee6f31d 100644 --- a/README.md +++ b/README.md @@ -427,7 +427,7 @@ For more information about the governance of the Node.js project, see * [misterdjules](https://github.com/misterdjules) - **Julien Gilli** <jgilli@nodejs.org> * [mmarchini](https://github.com/mmarchini) - -**Matheus Marchini** <matheus@sthima.com> +**Matheus Marchini** <matheus@sthima.com> * [mscdex](https://github.com/mscdex) - **Brian White** <mscdex@mscdex.net> * [MylesBorins](https://github.com/MylesBorins) - diff --git a/benchmark/misc/object-property-bench.js b/benchmark/misc/object-property-bench.js index d6afd4e9c0bcbb..fb27f0e5b83d62 100644 --- a/benchmark/misc/object-property-bench.js +++ b/benchmark/misc/object-property-bench.js @@ -1,5 +1,7 @@ 'use strict'; +/* eslint-disable dot-notation */ + const common = require('../common.js'); const bench = common.createBenchmark(main, { diff --git a/deps/node-inspect/.eslintrc b/deps/node-inspect/.eslintrc index c731203df64fd7..b6d45aa499655b 100644 --- a/deps/node-inspect/.eslintrc +++ b/deps/node-inspect/.eslintrc @@ -5,7 +5,7 @@ env: es6: true parserOptions: - ecmaVersion: 2016 + ecmaVersion: 2017 rules: # Possible Errors diff --git a/deps/node-inspect/.npmrc b/deps/node-inspect/.npmrc index 38f11c645a0019..b7c8444fee52a6 100644 --- a/deps/node-inspect/.npmrc +++ b/deps/node-inspect/.npmrc @@ -1 +1,2 @@ registry=https://registry.npmjs.org +package-lock=false diff --git a/deps/node-inspect/CHANGELOG.md b/deps/node-inspect/CHANGELOG.md index 0db3a7842eb15d..44ae510efefd90 100644 --- a/deps/node-inspect/CHANGELOG.md +++ b/deps/node-inspect/CHANGELOG.md @@ -1,3 +1,17 @@ +### 1.11.5 + +* Fix eslint issues - **[@jkrems](https://github.com/jkrems)** [#63](https://github.com/nodejs/node-inspect/pull/63) + - [`2adadbc`](https://github.com/nodejs/node-inspect/commit/2adadbc1086d2e374c425acbf96260a122705db2) **style:** Fix eslint issues + - [`a6d2f88`](https://github.com/nodejs/node-inspect/commit/a6d2f882c026409696a1b063ff40ceba7e1ddb86) **doc:** Remove redundant newline at the end + + +### 1.11.4 + +* Handle blocked port - **[@jkrems](https://github.com/jkrems)** [#62](https://github.com/nodejs/node-inspect/pull/62) + - [`3388969`](https://github.com/nodejs/node-inspect/commit/3388969d0032a78ff0cdb8146f170b978ec13b7b) **chore:** Disable package-lock + - [`d278b23`](https://github.com/nodejs/node-inspect/commit/d278b233ae5e11a2b62d01ccbaae594f39b32a96) **fix:** Stop asking to report a blocked port - see: [#60](https://github.com/nodejs/node-inspect/issues/60) + + ### 1.11.3 * [`93caa0f`](https://github.com/nodejs/node-inspect/commit/93caa0f5267c7ab452b258d3b03329a0bb5ac7f7) **docs:** Add missing oc in protocol diff --git a/deps/node-inspect/lib/_inspect.js b/deps/node-inspect/lib/_inspect.js index d846efbe6a4a52..305e49915a467b 100644 --- a/deps/node-inspect/lib/_inspect.js +++ b/deps/node-inspect/lib/_inspect.js @@ -42,6 +42,13 @@ const [ InspectClient, createRepl ] = const debuglog = util.debuglog('inspect'); +class StartupError extends Error { + constructor(message) { + super(message); + this.name = 'StartupError'; + } +} + function portIsFree(host, port, timeout = 2000) { if (port === 0) return Promise.resolve(); // Binding to a random port. @@ -51,7 +58,7 @@ function portIsFree(host, port, timeout = 2000) { return new Promise((resolve, reject) => { setTimeout(() => { didTimeOut = true; - reject(new Error( + reject(new StartupError( `Timeout (${timeout}) waiting for ${host}:${port} to be free`)); }, timeout); @@ -346,10 +353,14 @@ function startInspect(argv = process.argv.slice(2), stdin.resume(); function handleUnexpectedError(e) { - console.error('There was an internal error in node-inspect. ' + - 'Please report this bug.'); - console.error(e.message); - console.error(e.stack); + if (!(e instanceof StartupError)) { + console.error('There was an internal error in node-inspect. ' + + 'Please report this bug.'); + console.error(e.message); + console.error(e.stack); + } else { + console.error(e.message); + } if (inspector.child) inspector.child.kill(); process.exit(1); } diff --git a/deps/node-inspect/package.json b/deps/node-inspect/package.json index d25376b5d4bb96..eddc14debc4066 100644 --- a/deps/node-inspect/package.json +++ b/deps/node-inspect/package.json @@ -1,6 +1,6 @@ { "name": "node-inspect", - "version": "1.11.3", + "version": "1.11.5", "description": "Node Inspect", "license": "MIT", "main": "lib/_inspect.js", diff --git a/deps/node-inspect/test/cli/invalid-args.test.js b/deps/node-inspect/test/cli/invalid-args.test.js index c831d799a0bdc5..c1aaeb6a9ce750 100644 --- a/deps/node-inspect/test/cli/invalid-args.test.js +++ b/deps/node-inspect/test/cli/invalid-args.test.js @@ -1,4 +1,7 @@ 'use strict'; +const Path = require('path'); +const { createServer } = require('net'); + const { test } = require('tap'); const startCLI = require('./start-cli'); @@ -23,3 +26,29 @@ test('launch w/ invalid host:port', (t) => { t.equal(code, 1, 'exits with non-zero exit code'); }); }); + +test('launch w/ unavailable port', async (t) => { + const blocker = createServer((socket) => socket.end()); + const port = await new Promise((resolve, reject) => { + blocker.on('error', reject); + blocker.listen(0, '127.0.0.1', () => resolve(blocker.address().port)); + }); + + try { + const script = Path.join('examples', 'three-lines.js'); + const cli = startCLI([`--port=${port}`, script]); + const code = await cli.quit(); + + t.notMatch( + cli.output, + 'report this bug', + 'Omits message about reporting this as a bug'); + t.match( + cli.output, + `waiting for 127.0.0.1:${port} to be free`, + 'Tells the user that the port wasn\'t available'); + t.equal(code, 1, 'exits with non-zero exit code'); + } finally { + blocker.close(); + } +}); diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index 9754480e86c8b7..0fcab08efa4b10 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 6 #define V8_MINOR_VERSION 2 #define V8_BUILD_NUMBER 414 -#define V8_PATCH_LEVEL 64 +#define V8_PATCH_LEVEL 65 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/js/intl.js b/deps/v8/src/js/intl.js index 5a423450d8a340..a02e464a235ee1 100644 --- a/deps/v8/src/js/intl.js +++ b/deps/v8/src/js/intl.js @@ -135,18 +135,11 @@ var AVAILABLE_LOCALES = { */ var DEFAULT_ICU_LOCALE = UNDEFINED; -function GetDefaultICULocaleJS(service) { +function GetDefaultICULocaleJS() { if (IS_UNDEFINED(DEFAULT_ICU_LOCALE)) { DEFAULT_ICU_LOCALE = %GetDefaultICULocale(); } - // Check that this is a valid default for this service, - // otherwise fall back to "und" - // TODO(littledan,jshin): AvailableLocalesOf sometimes excludes locales - // which don't require tailoring, but work fine with root data. Look into - // exposing this fact in ICU or the way Chrome bundles data. - return (IS_UNDEFINED(service) || - HAS_OWN_PROPERTY(getAvailableLocalesOf(service), DEFAULT_ICU_LOCALE)) - ? DEFAULT_ICU_LOCALE : "und"; + return DEFAULT_ICU_LOCALE; } /** @@ -417,6 +410,48 @@ function resolveLocale(service, requestedLocales, options) { } +/** + * Look up the longest non-empty prefix of |locale| that is an element of + * |availableLocales|. Returns undefined when the |locale| is completely + * unsupported by |availableLocales|. + */ +function bestAvailableLocale(availableLocales, locale) { + do { + if (!IS_UNDEFINED(availableLocales[locale])) { + return locale; + } + // Truncate locale if possible. + var pos = %StringLastIndexOf(locale, '-'); + if (pos === -1) { + break; + } + locale = %_Call(StringSubstring, locale, 0, pos); + } while (true); + + return UNDEFINED; +} + + +/** + * Try to match any mutation of |requestedLocale| against |availableLocales|. + */ +function attemptSingleLookup(availableLocales, requestedLocale) { + // Remove all extensions. + var noExtensionsLocale = %RegExpInternalReplace( + GetAnyExtensionRE(), requestedLocale, ''); + var availableLocale = bestAvailableLocale( + availableLocales, requestedLocale); + if (!IS_UNDEFINED(availableLocale)) { + // Return the resolved locale and extension. + var extensionMatch = %regexp_internal_match( + GetUnicodeExtensionRE(), requestedLocale); + var extension = IS_NULL(extensionMatch) ? '' : extensionMatch[0]; + return {locale: availableLocale, extension: extension}; + } + return UNDEFINED; +} + + /** * Returns best matched supported locale and extension info using basic * lookup algorithm. @@ -429,31 +464,25 @@ function lookupMatcher(service, requestedLocales) { var availableLocales = getAvailableLocalesOf(service); for (var i = 0; i < requestedLocales.length; ++i) { - // Remove all extensions. - var locale = %RegExpInternalReplace( - GetAnyExtensionRE(), requestedLocales[i], ''); - do { - if (!IS_UNDEFINED(availableLocales[locale])) { - // Return the resolved locale and extension. - var extensionMatch = %regexp_internal_match( - GetUnicodeExtensionRE(), requestedLocales[i]); - var extension = IS_NULL(extensionMatch) ? '' : extensionMatch[0]; - return {locale: locale, extension: extension, position: i}; - } - // Truncate locale if possible. - var pos = %StringLastIndexOf(locale, '-'); - if (pos === -1) { - break; - } - locale = %_Call(StringSubstring, locale, 0, pos); - } while (true); + var result = attemptSingleLookup(availableLocales, requestedLocales[i]); + if (!IS_UNDEFINED(result)) { + return result; + } + } + + var defLocale = GetDefaultICULocaleJS(); + + // While ECMA-402 returns defLocale directly, we have to check if it is + // supported, as such support is not guaranteed. + var result = attemptSingleLookup(availableLocales, defLocale); + if (!IS_UNDEFINED(result)) { + return result; } // Didn't find a match, return default. return { - locale: GetDefaultICULocaleJS(service), - extension: '', - position: -1 + locale: 'und', + extension: '' }; } diff --git a/deps/v8/test/intl/assert.js b/deps/v8/test/intl/assert.js index d8cc85849f463a..c11e7c0bbf8914 100644 --- a/deps/v8/test/intl/assert.js +++ b/deps/v8/test/intl/assert.js @@ -132,6 +132,16 @@ function assertFalse(value, user_message = '') { } +/** + * Throws if value is null. + */ +function assertNotNull(value, user_message = '') { + if (value === null) { + fail("not null", value, user_message); + } +} + + /** * Runs code() and asserts that it throws the specified exception. */ @@ -189,3 +199,34 @@ function assertInstanceof(obj, type) { (actualTypeName ? ' but of < ' + actualTypeName + '>' : '')); } } + + +/** + * Split a BCP 47 language tag into locale and extension. + */ +function splitLanguageTag(tag) { + var extRe = /(-[0-9A-Za-z](-[0-9A-Za-z]{2,8})+)+$/; + var match = %regexp_internal_match(extRe, tag); + if (match) { + return { locale: tag.slice(0, match.index), extension: match[0] }; + } + + return { locale: tag, extension: '' }; +} + + +/** + * Throw if |parent| is not a more general language tag of |child|, nor |child| + * itself, per BCP 47 rules. + */ +function assertLanguageTag(child, parent) { + var childSplit = splitLanguageTag(child); + var parentSplit = splitLanguageTag(parent); + + // Do not compare extensions at this moment, as %GetDefaultICULocale() + // doesn't always output something we support. + if (childSplit.locale !== parentSplit.locale && + !childSplit.locale.startsWith(parentSplit.locale + '-')) { + fail(child, parent, 'language tag comparison'); + } +} diff --git a/deps/v8/test/intl/break-iterator/default-locale.js b/deps/v8/test/intl/break-iterator/default-locale.js index d8d5aeadb27510..e1a42a100a6b0f 100644 --- a/deps/v8/test/intl/break-iterator/default-locale.js +++ b/deps/v8/test/intl/break-iterator/default-locale.js @@ -37,8 +37,8 @@ assertFalse(options.locale === 'und'); assertFalse(options.locale === ''); assertFalse(options.locale === undefined); -// Then check for equality. -assertEquals(options.locale, %GetDefaultICULocale()); +// Then check for legitimacy. +assertLanguageTag(%GetDefaultICULocale(), options.locale); var iteratorNone = new Intl.v8BreakIterator(); assertEquals(options.locale, iteratorNone.resolvedOptions().locale); diff --git a/deps/v8/test/intl/break-iterator/wellformed-unsupported-locale.js b/deps/v8/test/intl/break-iterator/wellformed-unsupported-locale.js index 5ac8fbcd41583f..ffa44aef081eaf 100644 --- a/deps/v8/test/intl/break-iterator/wellformed-unsupported-locale.js +++ b/deps/v8/test/intl/break-iterator/wellformed-unsupported-locale.js @@ -29,4 +29,4 @@ var iterator = Intl.v8BreakIterator(['xx']); -assertEquals(iterator.resolvedOptions().locale, %GetDefaultICULocale()); +assertLanguageTag(%GetDefaultICULocale(), iterator.resolvedOptions().locale); diff --git a/deps/v8/test/intl/collator/default-locale.js b/deps/v8/test/intl/collator/default-locale.js index db9b1e73304114..5fc6ff4665c903 100644 --- a/deps/v8/test/intl/collator/default-locale.js +++ b/deps/v8/test/intl/collator/default-locale.js @@ -37,8 +37,8 @@ assertFalse(options.locale === 'und'); assertFalse(options.locale === ''); assertFalse(options.locale === undefined); -// Then check for equality. -assertEquals(options.locale, %GetDefaultICULocale()); +// Then check for legitimacy. +assertLanguageTag(%GetDefaultICULocale(), options.locale); var collatorNone = new Intl.Collator(); assertEquals(options.locale, collatorNone.resolvedOptions().locale); @@ -48,5 +48,8 @@ var collatorBraket = new Intl.Collator({}); assertEquals(options.locale, collatorBraket.resolvedOptions().locale); var collatorWithOptions = new Intl.Collator(undefined, {usage: 'search'}); -assertEquals(%GetDefaultICULocale() + '-u-co-search', - collatorWithOptions.resolvedOptions().locale); +assertLanguageTag(%GetDefaultICULocale(), + collatorWithOptions.resolvedOptions().locale); +assertNotNull( + %regexp_internal_match(/-u(-[a-zA-Z]+-[a-zA-Z]+)*-co-search/, + collatorWithOptions.resolvedOptions().locale)); diff --git a/deps/v8/test/intl/collator/wellformed-unsupported-locale.js b/deps/v8/test/intl/collator/wellformed-unsupported-locale.js index 3963d47a61ff85..ad89e3e2203e31 100644 --- a/deps/v8/test/intl/collator/wellformed-unsupported-locale.js +++ b/deps/v8/test/intl/collator/wellformed-unsupported-locale.js @@ -29,4 +29,4 @@ var collator = Intl.Collator(['xx']); -assertEquals(collator.resolvedOptions().locale, %GetDefaultICULocale()); +assertLanguageTag(%GetDefaultICULocale(), collator.resolvedOptions().locale); diff --git a/deps/v8/test/intl/date-format/default-locale.js b/deps/v8/test/intl/date-format/default-locale.js index 8e9b7fcec3e16e..2d79e895b54c38 100644 --- a/deps/v8/test/intl/date-format/default-locale.js +++ b/deps/v8/test/intl/date-format/default-locale.js @@ -37,8 +37,8 @@ assertFalse(options.locale === 'und'); assertFalse(options.locale === ''); assertFalse(options.locale === undefined); -// Then check for equality. -assertEquals(options.locale, %GetDefaultICULocale()); +// Then check for legitimacy. +assertLanguageTag(%GetDefaultICULocale(), options.locale); var dtfNone = new Intl.DateTimeFormat(); assertEquals(options.locale, dtfNone.resolvedOptions().locale); diff --git a/deps/v8/test/intl/date-format/wellformed-unsupported-locale.js b/deps/v8/test/intl/date-format/wellformed-unsupported-locale.js index 6f063abbd1a07c..b81216483250af 100644 --- a/deps/v8/test/intl/date-format/wellformed-unsupported-locale.js +++ b/deps/v8/test/intl/date-format/wellformed-unsupported-locale.js @@ -29,4 +29,4 @@ var dtf = Intl.DateTimeFormat(['xx']); -assertEquals(dtf.resolvedOptions().locale, %GetDefaultICULocale()); +assertLanguageTag(%GetDefaultICULocale(), dtf.resolvedOptions().locale); diff --git a/deps/v8/test/intl/number-format/default-locale.js b/deps/v8/test/intl/number-format/default-locale.js index cd67ba724f140f..a24aec23332786 100644 --- a/deps/v8/test/intl/number-format/default-locale.js +++ b/deps/v8/test/intl/number-format/default-locale.js @@ -37,8 +37,8 @@ assertFalse(options.locale === 'und'); assertFalse(options.locale === ''); assertFalse(options.locale === undefined); -// Then check for equality. -assertEquals(options.locale, %GetDefaultICULocale()); +// Then check for legitimacy. +assertLanguageTag(%GetDefaultICULocale(), options.locale); var nfNone = new Intl.NumberFormat(); assertEquals(options.locale, nfNone.resolvedOptions().locale); diff --git a/deps/v8/test/intl/number-format/wellformed-unsupported-locale.js b/deps/v8/test/intl/number-format/wellformed-unsupported-locale.js index 195eba4c19e09b..c51753928eeb87 100644 --- a/deps/v8/test/intl/number-format/wellformed-unsupported-locale.js +++ b/deps/v8/test/intl/number-format/wellformed-unsupported-locale.js @@ -29,4 +29,4 @@ var nf = Intl.NumberFormat(['xx']); -assertEquals(nf.resolvedOptions().locale, %GetDefaultICULocale()); +assertLanguageTag(%GetDefaultICULocale(), nf.resolvedOptions().locale); diff --git a/deps/v8/test/mjsunit/regress/regress-6288.js b/deps/v8/test/mjsunit/regress/regress-6288.js index 337af54c1a8303..5f550c31c8b72d 100644 --- a/deps/v8/test/mjsunit/regress/regress-6288.js +++ b/deps/v8/test/mjsunit/regress/regress-6288.js @@ -8,6 +8,6 @@ // DateTimeFormat but not Collation if (this.Intl) { - assertEquals('und', Intl.Collator().resolvedOptions().locale); + assertEquals('pt', Intl.Collator().resolvedOptions().locale); assertEquals('pt-BR', Intl.DateTimeFormat().resolvedOptions().locale); } diff --git a/deps/v8/tools/gen-postmortem-metadata.py b/deps/v8/tools/gen-postmortem-metadata.py index 22f0afbef31790..c8cff792c41155 100644 --- a/deps/v8/tools/gen-postmortem-metadata.py +++ b/deps/v8/tools/gen-postmortem-metadata.py @@ -212,6 +212,9 @@ 'value': 'Context::EXTENSION_INDEX' }, { 'name': 'context_min_slots', 'value': 'Context::MIN_CONTEXT_SLOTS' }, + { 'name': 'context_idx_embedder_data', + 'value': 'Internals::kContextEmbedderDataIndex' }, + { 'name': 'namedictionaryshape_prefix_size', 'value': 'NameDictionaryShape::kPrefixSize' }, @@ -231,7 +234,9 @@ { 'name': 'unseedednumberdictionaryshape_prefix_size', 'value': 'UnseededNumberDictionaryShape::kPrefixSize' }, { 'name': 'unseedednumberdictionaryshape_entry_size', - 'value': 'UnseededNumberDictionaryShape::kEntrySize' } + 'value': 'UnseededNumberDictionaryShape::kEntrySize' }, + + { 'name': 'type_JSError__JS_ERROR_TYPE', 'value': 'JS_ERROR_TYPE' }, ]; # diff --git a/doc/.eslintrc.yaml b/doc/.eslintrc.yaml index 8038836fe310db..c8c1612e3a100b 100644 --- a/doc/.eslintrc.yaml +++ b/doc/.eslintrc.yaml @@ -12,3 +12,6 @@ rules: no-var: error prefer-const: error prefer-rest-params: error + + # Stylistic Issues + no-multiple-empty-lines: [error, {max: 1, maxEOF: 0, maxBOF: 0}] diff --git a/doc/api/async_hooks.md b/doc/api/async_hooks.md index c2abd5b78bade7..1982205faccf10 100644 --- a/doc/api/async_hooks.md +++ b/doc/api/async_hooks.md @@ -301,10 +301,10 @@ and document their own resource objects. For example, such a resource object could contain the SQL query being executed. In the case of Promises, the `resource` object will have `promise` property -that refers to the Promise that is being initialized, and a `parentId` property -set to the `asyncId` of a parent Promise, if there is one, and `undefined` +that refers to the Promise that is being initialized, and a `isChainedPromise` +property, set to `true` if the promise has a parent promise, and `false` otherwise. For example, in the case of `b = a.then(handler)`, `a` is considered -a parent Promise of `b`. +a parent Promise of `b`. Here, `b` is considered a chained promise. *Note*: In some cases the resource object is reused for performance reasons, it is thus not safe to use it as a key in a `WeakMap` or add properties to it. diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 6f31cbdc55cf3e..18209a81d264a1 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -497,7 +497,6 @@ console.log(buf1.toString()); // Prints: this is a tC)st console.log(buf1.toString('ascii')); - const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex'); // Prints: this is a tést @@ -906,7 +905,6 @@ console.log(buf1.toString()); // Prints: this is a tC)st console.log(buf1.toString('ascii')); - const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); // Prints: this is a tést @@ -1366,7 +1364,6 @@ console.log(buf.indexOf(Buffer.from('a buffer example'))); // Prints: 8 console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); - const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); // Prints: 4 @@ -1477,7 +1474,6 @@ console.log(buf.lastIndexOf('buffer', 5)); // Prints: -1 console.log(buf.lastIndexOf('buffer', 4)); - const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2'); // Prints: 6 @@ -2000,7 +1996,6 @@ buf1.swap16(); // Prints: console.log(buf1); - const buf2 = Buffer.from([0x1, 0x2, 0x3]); // Throws an exception: RangeError: Buffer size must be a multiple of 16-bits @@ -2030,7 +2025,6 @@ buf1.swap32(); // Prints: console.log(buf1); - const buf2 = Buffer.from([0x1, 0x2, 0x3]); // Throws an exception: RangeError: Buffer size must be a multiple of 32-bits @@ -2060,7 +2054,6 @@ buf1.swap64(); // Prints: console.log(buf1); - const buf2 = Buffer.from([0x1, 0x2, 0x3]); // Throws an exception: RangeError: Buffer size must be a multiple of 64-bits @@ -2132,7 +2125,6 @@ console.log(buf1.toString('ascii')); // Prints: abcde console.log(buf1.toString('ascii', 0, 5)); - const buf2 = Buffer.from('tést'); // Prints: 74c3a97374 diff --git a/doc/api/cli.md b/doc/api/cli.md index 63af8ba5ac85f1..6b98eef3e79ea1 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -494,6 +494,8 @@ Node options that are allowed are: V8 options that are allowed are: - `--abort-on-uncaught-exception` - `--max-old-space-size` +- `--perf-basic-prof` +- `--perf-prof` - `--stack-trace-limit` ### `NODE_PENDING_DEPRECATION=1` diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 379141990089bc..a0df0fe3a0de08 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -42,7 +42,10 @@ added: v0.11.8 --> SPKAC is a Certificate Signing Request mechanism originally implemented by -Netscape and now specified formally as part of [HTML5's `keygen` element][]. +Netscape and was specified formally as part of [HTML5's `keygen` element][]. + +Note that `` is deprecated since [HTML 5.2][] and new projects +should not use this element anymore. The `crypto` module provides the `Certificate` class for working with SPKAC data. The most common usage is handling output generated by the HTML5 @@ -1216,6 +1219,11 @@ Adversaries][] for details. ### crypto.createCipheriv(algorithm, key, iv[, options]) - `algorithm` {string} - `key` {string | Buffer | TypedArray | DataView} @@ -1231,7 +1239,8 @@ available cipher algorithms. The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector][]. Both arguments must be `'utf8'` encoded strings, -[Buffers][`Buffer`], `TypedArray`, or `DataView`s. +[Buffers][`Buffer`], `TypedArray`, or `DataView`s. If the cipher does not need +an initialization vector, `iv` may be `null`. ### crypto.createCredentials(details) - `algorithm` {string} - `key` {string | Buffer | TypedArray | DataView} @@ -1293,7 +1307,8 @@ available cipher algorithms. The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector][]. Both arguments must be `'utf8'` encoded strings, -[Buffers][`Buffer`], `TypedArray`, or `DataView`s. +[Buffers][`Buffer`], `TypedArray`, or `DataView`s. If the cipher does not need +an initialization vector, `iv` may be `null`. ### crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding]) + +* Returns: {Buffer|undefined} The latest `Finished` message that has been +sent to the socket as part of a SSL/TLS handshake, or `undefined` if +no `Finished` message has been sent yet. + +As the `Finished` messages are message digests of the complete handshake +(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can +be used for external authentication procedures when the authentication +provided by SSL/TLS is not desired or is not enough. + +Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used +to implement the `tls-unique` channel binding from [RFC 5929][]. + ### tlsSocket.getPeerCertificate([detailed]) + +* Returns: {Buffer|undefined} The latest `Finished` message that is expected +or has actually been received from the socket as part of a SSL/TLS handshake, +or `undefined` if there is no `Finished` message so far. + +As the `Finished` messages are message digests of the complete handshake +(with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can +be used for external authentication procedures when the authentication +provided by SSL/TLS is not desired or is not enough. + +Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used +to implement the `tls-unique` channel binding from [RFC 5929][]. + ### tlsSocket.getProtocol() ```js diff --git a/test/common/countdown.js b/test/common/countdown.js index 93bdbbfb16da5d..5fcb77c4ed66a0 100644 --- a/test/common/countdown.js +++ b/test/common/countdown.js @@ -4,13 +4,14 @@ const assert = require('assert'); const kLimit = Symbol('limit'); const kCallback = Symbol('callback'); +const common = require('./'); class Countdown { constructor(limit, cb) { assert.strictEqual(typeof limit, 'number'); assert.strictEqual(typeof cb, 'function'); this[kLimit] = limit; - this[kCallback] = cb; + this[kCallback] = common.mustCall(cb); } dec() { diff --git a/test/common/index.js b/test/common/index.js index 5433c6472c9ea5..8efd72fc7d162a 100644 --- a/test/common/index.js +++ b/test/common/index.js @@ -512,7 +512,7 @@ exports.canCreateSymLink = function() { // whoami.exe needs to be the one from System32 // If unix tools are in the path, they can shadow the one we want, // so use the full path while executing whoami - const whoamiPath = path.join(process.env['SystemRoot'], + const whoamiPath = path.join(process.env.SystemRoot, 'System32', 'whoami.exe'); let err = false; diff --git a/test/common/inspector-helper.js b/test/common/inspector-helper.js index 8fc778555d0454..2a05f58625031f 100644 --- a/test/common/inspector-helper.js +++ b/test/common/inspector-helper.js @@ -167,9 +167,7 @@ class InspectorSession { reject(message.error); } else { if (message.method === 'Debugger.scriptParsed') { - const script = message['params']; - const scriptId = script['scriptId']; - const url = script['url']; + const { scriptId, url } = message.params; this._scriptsIdsByUrl.set(scriptId, url); if (url === _MAINSCRIPT) this.mainScriptId = scriptId; @@ -188,12 +186,12 @@ class InspectorSession { _sendMessage(message) { const msg = JSON.parse(JSON.stringify(message)); // Clone! - msg['id'] = this._nextId++; + msg.id = this._nextId++; if (DEBUG) console.log('[sent]', JSON.stringify(msg)); const responsePromise = new Promise((resolve, reject) => { - this._commandResponsePromises.set(msg['id'], { resolve, reject }); + this._commandResponsePromises.set(msg.id, { resolve, reject }); }); return new Promise( @@ -238,12 +236,15 @@ class InspectorSession { return notification; } - _isBreakOnLineNotification(message, line, url) { - if ('Debugger.paused' === message['method']) { - const callFrame = message['params']['callFrames'][0]; - const location = callFrame['location']; - assert.strictEqual(url, this._scriptsIdsByUrl.get(location['scriptId'])); - assert.strictEqual(line, location['lineNumber']); + _isBreakOnLineNotification(message, line, expectedScriptPath) { + if ('Debugger.paused' === message.method) { + const callFrame = message.params.callFrames[0]; + const location = callFrame.location; + const scriptPath = this._scriptsIdsByUrl.get(location.scriptId); + assert.strictEqual(scriptPath.toString(), + expectedScriptPath.toString(), + `${scriptPath} !== ${expectedScriptPath}`); + assert.strictEqual(line, location.lineNumber); return true; } } @@ -259,12 +260,12 @@ class InspectorSession { _matchesConsoleOutputNotification(notification, type, values) { if (!Array.isArray(values)) values = [ values ]; - if ('Runtime.consoleAPICalled' === notification['method']) { - const params = notification['params']; - if (params['type'] === type) { + if ('Runtime.consoleAPICalled' === notification.method) { + const params = notification.params; + if (params.type === type) { let i = 0; - for (const value of params['args']) { - if (value['value'] !== values[i++]) + for (const value of params.args) { + if (value.value !== values[i++]) return false; } return i === values.length; @@ -389,7 +390,7 @@ class NodeInstance { async connectInspectorSession() { console.log('[test]', 'Connecting to a child Node process'); const response = await this.httpGet(null, '/json/list'); - const url = response[0]['webSocketDebuggerUrl']; + const url = response[0].webSocketDebuggerUrl; return this.wsHandshake(url); } diff --git a/test/common/shared-lib-util.js b/test/common/shared-lib-util.js new file mode 100644 index 00000000000000..7ff7518ac31e6d --- /dev/null +++ b/test/common/shared-lib-util.js @@ -0,0 +1,29 @@ +/* eslint-disable required-modules */ +'use strict'; +const path = require('path'); + +// If node executable is linked to shared lib, need to take care about the +// shared lib path. +exports.addLibraryPath = function(env) { + if (!process.config.variables.node_shared) { + return; + } + + env = env || process.env; + + env.LD_LIBRARY_PATH = + (env.LD_LIBRARY_PATH ? env.LD_LIBRARY_PATH + path.delimiter : '') + + path.join(path.dirname(process.execPath), 'lib.target'); + // For AIX. + env.LIBPATH = + (env.LIBPATH ? env.LIBPATH + path.delimiter : '') + + path.join(path.dirname(process.execPath), 'lib.target'); + // For Mac OSX. + env.DYLD_LIBRARY_PATH = + (env.DYLD_LIBRARY_PATH ? env.DYLD_LIBRARY_PATH + path.delimiter : '') + + path.dirname(process.execPath); + // For Windows. + env.PATH = + (env.PATH ? env.PATH + path.delimiter : '') + + path.dirname(process.execPath); +}; diff --git a/test/fixtures/failcounter.js b/test/fixtures/failcounter.js new file mode 100644 index 00000000000000..f3bc34a7308334 --- /dev/null +++ b/test/fixtures/failcounter.js @@ -0,0 +1,2 @@ +const Countdown = require('../common/countdown'); +new Countdown(2, () => {}); diff --git a/test/parallel/test-async-hooks-promise.js b/test/parallel/test-async-hooks-promise.js index d712fd616c647b..4b36f6026b36c6 100644 --- a/test/parallel/test-async-hooks-promise.js +++ b/test/parallel/test-async-hooks-promise.js @@ -21,8 +21,8 @@ const a = Promise.resolve(42); const b = a.then(common.mustCall()); assert.strictEqual(initCalls[0].triggerId, 1); -assert.strictEqual(initCalls[0].resource.parentId, undefined); +assert.strictEqual(initCalls[0].resource.isChainedPromise, false); assert.strictEqual(initCalls[0].resource.promise, a); assert.strictEqual(initCalls[1].triggerId, initCalls[0].id); -assert.strictEqual(initCalls[1].resource.parentId, initCalls[0].id); +assert.strictEqual(initCalls[1].resource.isChainedPromise, true); assert.strictEqual(initCalls[1].resource.promise, b); diff --git a/test/parallel/test-child-process-fork-exec-path.js b/test/parallel/test-child-process-fork-exec-path.js index 42855cd663e826..8b94ef62a93bc8 100644 --- a/test/parallel/test-child-process-fork-exec-path.js +++ b/test/parallel/test-child-process-fork-exec-path.js @@ -28,6 +28,9 @@ const tmpdir = require('../common/tmpdir'); const msg = { test: 'this' }; const nodePath = process.execPath; const copyPath = path.join(tmpdir.path, 'node-copy.exe'); +const { addLibraryPath } = require('../common/shared-lib-util'); + +addLibraryPath(process.env); if (process.env.FORK) { assert(process.send); diff --git a/test/parallel/test-cli-node-options.js b/test/parallel/test-cli-node-options.js index 3118c6bc1bc27d..8eae27b1a2a3a2 100644 --- a/test/parallel/test-cli-node-options.js +++ b/test/parallel/test-cli-node-options.js @@ -28,6 +28,15 @@ expect('--trace-event-categories node', 'B\n'); // eslint-disable-next-line no-template-curly-in-string expect('--trace-event-file-pattern {pid}-${rotation}.trace_events', 'B\n'); +if (!common.isWindows) { + expect('--perf-basic-prof', 'B\n'); +} + +if (common.isLinux && ['arm', 'x64', 'mips'].includes(process.arch)) { + // PerfJitLogger is only implemented in Linux. + expect('--perf-prof', 'B\n'); +} + if (common.hasCrypto) { expect('--use-openssl-ca', 'B\n'); expect('--use-bundled-ca', 'B\n'); diff --git a/test/parallel/test-cluster-fork-env.js b/test/parallel/test-cluster-fork-env.js index 5dd28163084a21..57e7881013d0fd 100644 --- a/test/parallel/test-cluster-fork-env.js +++ b/test/parallel/test-cluster-fork-env.js @@ -31,8 +31,8 @@ const cluster = require('cluster'); if (cluster.isWorker) { const result = cluster.worker.send({ - prop: process.env['cluster_test_prop'], - overwrite: process.env['cluster_test_overwrite'] + prop: process.env.cluster_test_prop, + overwrite: process.env.cluster_test_overwrite }); assert.strictEqual(result, true); @@ -45,7 +45,7 @@ if (cluster.isWorker) { // To check that the cluster extend on the process.env we will overwrite a // property - process.env['cluster_test_overwrite'] = 'old'; + process.env.cluster_test_overwrite = 'old'; // Fork worker const worker = cluster.fork({ diff --git a/test/parallel/test-common-countdown.js b/test/parallel/test-common-countdown.js index ec0543f36fec74..6a1a2f1bbce98a 100644 --- a/test/parallel/test-common-countdown.js +++ b/test/parallel/test-common-countdown.js @@ -3,13 +3,31 @@ const common = require('../common'); const assert = require('assert'); const Countdown = require('../common/countdown'); +const fixtures = require('../common/fixtures'); +const { execFile } = require('child_process'); let done = ''; - -const countdown = new Countdown(2, common.mustCall(() => done = true)); +const countdown = new Countdown(2, () => done = true); assert.strictEqual(countdown.remaining, 2); countdown.dec(); assert.strictEqual(countdown.remaining, 1); countdown.dec(); assert.strictEqual(countdown.remaining, 0); assert.strictEqual(done, true); + +const failFixtures = [ + [ + fixtures.path('failcounter.js'), + 'Mismatched function calls. Expected exactly 1, actual 0.', + ] +]; + +for (const p of failFixtures) { + const [file, expected] = p; + execFile(process.argv[0], [file], common.mustCall((ex, stdout, stderr) => { + assert.ok(ex); + assert.strictEqual(stderr, ''); + const firstLine = stdout.split('\n').shift(); + assert.strictEqual(firstLine, expected); + })); +} diff --git a/test/parallel/test-crypto-cipheriv-decipheriv.js b/test/parallel/test-crypto-cipheriv-decipheriv.js index 01f6717e67a181..8f880cbfb2417a 100644 --- a/test/parallel/test-crypto-cipheriv-decipheriv.js +++ b/test/parallel/test-crypto-cipheriv-decipheriv.js @@ -89,8 +89,9 @@ if (!common.hasFipsCrypto) { Buffer.from('A6A6A6A6A6A6A6A6', 'hex')); } -// Zero-sized IV should be accepted in ECB mode. +// Zero-sized IV or null should be accepted in ECB mode. crypto.createCipheriv('aes-128-ecb', Buffer.alloc(16), Buffer.alloc(0)); +crypto.createCipheriv('aes-128-ecb', Buffer.alloc(16), null); const errMessage = /Invalid IV length/; @@ -114,6 +115,11 @@ for (let n = 0; n < 256; n += 1) { errMessage); } +// And so should null be. +assert.throws(() => { + crypto.createCipheriv('aes-128-cbc', Buffer.alloc(16), null); +}, /Missing IV for cipher aes-128-cbc/); + // Zero-sized IV should be rejected in GCM mode. assert.throws( () => crypto.createCipheriv('aes-128-gcm', Buffer.alloc(16), diff --git a/test/parallel/test-crypto-hmac.js b/test/parallel/test-crypto-hmac.js index 72cba6ed5f190c..9f04b19cf3eddc 100644 --- a/test/parallel/test-crypto-hmac.js +++ b/test/parallel/test-crypto-hmac.js @@ -71,13 +71,13 @@ const wikipedia = [ ]; for (let i = 0, l = wikipedia.length; i < l; i++) { - for (const hash in wikipedia[i]['hmac']) { + for (const hash in wikipedia[i].hmac) { // FIPS does not support MD5. if (common.hasFipsCrypto && hash === 'md5') continue; - const expected = wikipedia[i]['hmac'][hash]; - const actual = crypto.createHmac(hash, wikipedia[i]['key']) - .update(wikipedia[i]['data']) + const expected = wikipedia[i].hmac[hash]; + const actual = crypto.createHmac(hash, wikipedia[i].key) + .update(wikipedia[i].data) .digest('hex'); assert.strictEqual( actual, @@ -236,18 +236,18 @@ const rfc4231 = [ ]; for (let i = 0, l = rfc4231.length; i < l; i++) { - for (const hash in rfc4231[i]['hmac']) { + for (const hash in rfc4231[i].hmac) { const str = crypto.createHmac(hash, rfc4231[i].key); str.end(rfc4231[i].data); let strRes = str.read().toString('hex'); - let actual = crypto.createHmac(hash, rfc4231[i]['key']) - .update(rfc4231[i]['data']) + let actual = crypto.createHmac(hash, rfc4231[i].key) + .update(rfc4231[i].data) .digest('hex'); - if (rfc4231[i]['truncate']) { + if (rfc4231[i].truncate) { actual = actual.substr(0, 32); // first 128 bits == 32 hex chars strRes = strRes.substr(0, 32); } - const expected = rfc4231[i]['hmac'][hash]; + const expected = rfc4231[i].hmac[hash]; assert.strictEqual( actual, expected, @@ -368,10 +368,10 @@ const rfc2202_sha1 = [ if (!common.hasFipsCrypto) { for (let i = 0, l = rfc2202_md5.length; i < l; i++) { - const actual = crypto.createHmac('md5', rfc2202_md5[i]['key']) - .update(rfc2202_md5[i]['data']) + const actual = crypto.createHmac('md5', rfc2202_md5[i].key) + .update(rfc2202_md5[i].data) .digest('hex'); - const expected = rfc2202_md5[i]['hmac']; + const expected = rfc2202_md5[i].hmac; assert.strictEqual( actual, expected, @@ -380,10 +380,10 @@ if (!common.hasFipsCrypto) { } } for (let i = 0, l = rfc2202_sha1.length; i < l; i++) { - const actual = crypto.createHmac('sha1', rfc2202_sha1[i]['key']) - .update(rfc2202_sha1[i]['data']) + const actual = crypto.createHmac('sha1', rfc2202_sha1[i].key) + .update(rfc2202_sha1[i].data) .digest('hex'); - const expected = rfc2202_sha1[i]['hmac']; + const expected = rfc2202_sha1[i].hmac; assert.strictEqual( actual, expected, diff --git a/test/parallel/test-domain-stack-empty-in-process-uncaughtexception.js b/test/parallel/test-domain-stack-empty-in-process-uncaughtexception.js index 79ded2dd9d1424..e9e8ab12d59d2c 100644 --- a/test/parallel/test-domain-stack-empty-in-process-uncaughtexception.js +++ b/test/parallel/test-domain-stack-empty-in-process-uncaughtexception.js @@ -6,15 +6,18 @@ const assert = require('assert'); const d = domain.create(); -process.on('uncaughtException', common.mustCall(function onUncaught() { +process.once('uncaughtException', common.mustCall(function onUncaught() { assert.strictEqual( process.domain, null, - 'domains stack should be empty in uncaughtException handler'); + 'Domains stack should be empty in uncaughtException handler ' + + `but the value of process.domain is ${JSON.stringify(process.domain)}`); })); process.on('beforeExit', common.mustCall(function onBeforeExit() { - assert.strictEqual(process.domain, null, - 'domains stack should be empty in beforeExit handler'); + assert.strictEqual( + process.domain, null, + 'Domains stack should be empty in beforeExit handler ' + + `but the value of process.domain is ${JSON.stringify(process.domain)}`); })); d.run(function() { diff --git a/test/parallel/test-event-emitter-check-listener-leaks.js b/test/parallel/test-event-emitter-check-listener-leaks.js index e24c07506c372e..7688c61a435cfb 100644 --- a/test/parallel/test-event-emitter-check-listener-leaks.js +++ b/test/parallel/test-event-emitter-check-listener-leaks.js @@ -32,9 +32,9 @@ const events = require('events'); for (let i = 0; i < 10; i++) { e.on('default', common.mustNotCall()); } - assert.ok(!e._events['default'].hasOwnProperty('warned')); + assert.ok(!e._events.default.hasOwnProperty('warned')); e.on('default', common.mustNotCall()); - assert.ok(e._events['default'].warned); + assert.ok(e._events.default.warned); // symbol const symbol = Symbol('symbol'); @@ -49,9 +49,9 @@ const events = require('events'); for (let i = 0; i < 5; i++) { e.on('specific', common.mustNotCall()); } - assert.ok(!e._events['specific'].hasOwnProperty('warned')); + assert.ok(!e._events.specific.hasOwnProperty('warned')); e.on('specific', common.mustNotCall()); - assert.ok(e._events['specific'].warned); + assert.ok(e._events.specific.warned); // only one e.setMaxListeners(1); @@ -65,7 +65,7 @@ const events = require('events'); for (let i = 0; i < 1000; i++) { e.on('unlimited', common.mustNotCall()); } - assert.ok(!e._events['unlimited'].hasOwnProperty('warned')); + assert.ok(!e._events.unlimited.hasOwnProperty('warned')); } // process-wide @@ -76,16 +76,16 @@ const events = require('events'); for (let i = 0; i < 42; ++i) { e.on('fortytwo', common.mustNotCall()); } - assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); + assert.ok(!e._events.fortytwo.hasOwnProperty('warned')); e.on('fortytwo', common.mustNotCall()); - assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); - delete e._events['fortytwo'].warned; + assert.ok(e._events.fortytwo.hasOwnProperty('warned')); + delete e._events.fortytwo.warned; events.EventEmitter.defaultMaxListeners = 44; e.on('fortytwo', common.mustNotCall()); - assert.ok(!e._events['fortytwo'].hasOwnProperty('warned')); + assert.ok(!e._events.fortytwo.hasOwnProperty('warned')); e.on('fortytwo', common.mustNotCall()); - assert.ok(e._events['fortytwo'].hasOwnProperty('warned')); + assert.ok(e._events.fortytwo.hasOwnProperty('warned')); } // but _maxListeners still has precedence over defaultMaxListeners @@ -94,9 +94,9 @@ const events = require('events'); const e = new events.EventEmitter(); e.setMaxListeners(1); e.on('uno', common.mustNotCall()); - assert.ok(!e._events['uno'].hasOwnProperty('warned')); + assert.ok(!e._events.uno.hasOwnProperty('warned')); e.on('uno', common.mustNotCall()); - assert.ok(e._events['uno'].hasOwnProperty('warned')); + assert.ok(e._events.uno.hasOwnProperty('warned')); // chainable assert.strictEqual(e, e.setMaxListeners(1)); diff --git a/test/parallel/test-fs-open-flags.js b/test/parallel/test-fs-open-flags.js index adc1f899bfb223..edb4d158b13b58 100644 --- a/test/parallel/test-fs-open-flags.js +++ b/test/parallel/test-fs-open-flags.js @@ -56,8 +56,12 @@ assert.strictEqual(stringToFlags('wx+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); assert.strictEqual(stringToFlags('xw+'), O_TRUNC | O_CREAT | O_RDWR | O_EXCL); assert.strictEqual(stringToFlags('ax'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); assert.strictEqual(stringToFlags('xa'), O_APPEND | O_CREAT | O_WRONLY | O_EXCL); +assert.strictEqual(stringToFlags('as'), O_APPEND | O_CREAT | O_WRONLY | O_SYNC); +assert.strictEqual(stringToFlags('sa'), O_APPEND | O_CREAT | O_WRONLY | O_SYNC); assert.strictEqual(stringToFlags('ax+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); assert.strictEqual(stringToFlags('xa+'), O_APPEND | O_CREAT | O_RDWR | O_EXCL); +assert.strictEqual(stringToFlags('as+'), O_APPEND | O_CREAT | O_RDWR | O_SYNC); +assert.strictEqual(stringToFlags('sa+'), O_APPEND | O_CREAT | O_RDWR | O_SYNC); ('+ +a +r +w rw wa war raw r++ a++ w++ x +x x+ rx rx+ wxx wax xwx xxx') .split(' ') diff --git a/test/parallel/test-fs-ready-event-stream.js b/test/parallel/test-fs-ready-event-stream.js new file mode 100644 index 00000000000000..71f7aa76e36c76 --- /dev/null +++ b/test/parallel/test-fs-ready-event-stream.js @@ -0,0 +1,13 @@ +'use strict'; +const common = require('../common'); +const fs = require('fs'); +const path = require('path'); +const tmpdir = require('../common/tmpdir'); + +const readStream = fs.createReadStream(__filename); +readStream.on('ready', common.mustCall(() => {}, 1)); + +const writeFile = path.join(tmpdir.path, 'write-fsreadyevent.txt'); +tmpdir.refresh(); +const writeStream = fs.createWriteStream(writeFile, { autoClose: true }); +writeStream.on('ready', common.mustCall(() => {}, 1)); diff --git a/test/parallel/test-http-after-connect.js b/test/parallel/test-http-after-connect.js index 324186bab72324..d209c82083e639 100644 --- a/test/parallel/test-http-after-connect.js +++ b/test/parallel/test-http-after-connect.js @@ -32,7 +32,7 @@ const server = http.createServer(common.mustCall((req, res) => { setTimeout(() => res.end(req.url), 50); }, 2)); -const countdown = new Countdown(2, common.mustCall(() => server.close())); +const countdown = new Countdown(2, () => server.close()); server.on('connect', common.mustCall((req, socket) => { socket.write('HTTP/1.1 200 Connection established\r\n\r\n'); diff --git a/test/parallel/test-http-agent-destroyed-socket.js b/test/parallel/test-http-agent-destroyed-socket.js index 7970ce8bae0fcb..39f4ebef5374c1 100644 --- a/test/parallel/test-http-agent-destroyed-socket.js +++ b/test/parallel/test-http-agent-destroyed-socket.js @@ -80,7 +80,7 @@ const server = http.createServer(common.mustCall((req, res) => { assert(request1.socket.destroyed); // assert not reusing the same socket, since it was destroyed. assert.notStrictEqual(request1.socket, request2.socket); - const countdown = new Countdown(2, common.mustCall(() => server.close())); + const countdown = new Countdown(2, () => server.close()); request2.socket.on('close', common.mustCall(() => countdown.dec())); response.on('end', common.mustCall(() => countdown.dec())); response.resume(); diff --git a/test/parallel/test-http-agent-maxsockets-regress-4050.js b/test/parallel/test-http-agent-maxsockets-regress-4050.js index 57a90e4b05c79f..eb1c95d5200694 100644 --- a/test/parallel/test-http-agent-maxsockets-regress-4050.js +++ b/test/parallel/test-http-agent-maxsockets-regress-4050.js @@ -17,7 +17,7 @@ const server = http.createServer(common.mustCall((req, res) => { res.end('hello world'); }, 6)); -const countdown = new Countdown(6, common.mustCall(() => server.close())); +const countdown = new Countdown(6, () => server.close()); function get(path, callback) { return http.get({ diff --git a/test/parallel/test-http-agent-maxsockets.js b/test/parallel/test-http-agent-maxsockets.js index 4d422f4a90b4f9..267f820e0435eb 100644 --- a/test/parallel/test-http-agent-maxsockets.js +++ b/test/parallel/test-http-agent-maxsockets.js @@ -26,13 +26,13 @@ function get(path, callback) { }, callback); } -const countdown = new Countdown(2, common.mustCall(() => { +const countdown = new Countdown(2, () => { const freepool = agent.freeSockets[Object.keys(agent.freeSockets)[0]]; assert.strictEqual(freepool.length, 2, `expect keep 2 free sockets, but got ${freepool.length}`); agent.destroy(); server.close(); -})); +}); function dec() { process.nextTick(() => countdown.dec()); diff --git a/test/parallel/test-http-automatic-headers.js b/test/parallel/test-http-automatic-headers.js index 5a6a8e524c76ee..5e99f1ee39dd6b 100644 --- a/test/parallel/test-http-automatic-headers.js +++ b/test/parallel/test-http-automatic-headers.js @@ -22,8 +22,8 @@ server.on('listening', common.mustCall(() => { assert.strictEqual(res.headers['x-date'], 'foo'); assert.strictEqual(res.headers['x-connection'], 'bar'); assert.strictEqual(res.headers['x-content-length'], 'baz'); - assert(res.headers['date']); - assert.strictEqual(res.headers['connection'], 'keep-alive'); + assert(res.headers.date); + assert.strictEqual(res.headers.connection, 'keep-alive'); assert.strictEqual(res.headers['content-length'], '0'); server.close(); agent.destroy(); diff --git a/test/parallel/test-http-client-abort.js b/test/parallel/test-http-client-abort.js index 71fd2ad64cabdd..f767189ea9d593 100644 --- a/test/parallel/test-http-client-abort.js +++ b/test/parallel/test-http-client-abort.js @@ -26,7 +26,7 @@ const Countdown = require('../common/countdown'); const N = 8; -const countdown = new Countdown(N, common.mustCall(() => server.close())); +const countdown = new Countdown(N, () => server.close()); const server = http.Server(common.mustCall((req, res) => { res.writeHead(200); @@ -37,9 +37,9 @@ const server = http.Server(common.mustCall((req, res) => { server.listen(0, common.mustCall(() => { const requests = []; - const reqCountdown = new Countdown(N, common.mustCall(() => { + const reqCountdown = new Countdown(N, () => { requests.forEach((req) => req.abort()); - })); + }); const options = { port: server.address().port }; diff --git a/test/parallel/test-http-client-parse-error.js b/test/parallel/test-http-client-parse-error.js index 60f1ee45c8efc1..cb4e3ff08434dd 100644 --- a/test/parallel/test-http-client-parse-error.js +++ b/test/parallel/test-http-client-parse-error.js @@ -25,7 +25,7 @@ const http = require('http'); const net = require('net'); const Countdown = require('../common/countdown'); -const countdown = new Countdown(2, common.mustCall(() => server.close())); +const countdown = new Countdown(2, () => server.close()); const payloads = [ 'HTTP/1.1 302 Object Moved\r\nContent-Length: 0\r\n\r\nhi world', diff --git a/test/parallel/test-http-exceptions.js b/test/parallel/test-http-exceptions.js index 0b6ac5bdc1f7d0..03e30b67e18b57 100644 --- a/test/parallel/test-http-exceptions.js +++ b/test/parallel/test-http-exceptions.js @@ -21,7 +21,12 @@ 'use strict'; require('../common'); +const Countdown = require('../common/countdown'); const http = require('http'); +const NUMBER_OF_EXCEPTIONS = 4; +const countdown = new Countdown(NUMBER_OF_EXCEPTIONS, () => { + process.exit(0); +}); const server = http.createServer(function(req, res) { intentionally_not_defined(); // eslint-disable-line no-undef @@ -30,16 +35,16 @@ const server = http.createServer(function(req, res) { res.end(); }); +function onUncaughtException(err) { + console.log(`Caught an exception: ${err}`); + if (err.name === 'AssertionError') throw err; + countdown.dec(); +} + +process.on('uncaughtException', onUncaughtException); + server.listen(0, function() { - for (let i = 0; i < 4; i += 1) { + for (let i = 0; i < NUMBER_OF_EXCEPTIONS; i += 1) { http.get({ port: this.address().port, path: `/busy/${i}` }); } }); - -let exception_count = 0; - -process.on('uncaughtException', function(err) { - console.log(`Caught an exception: ${err}`); - if (err.name === 'AssertionError') throw err; - if (++exception_count === 4) process.exit(0); -}); diff --git a/test/parallel/test-http-flush-headers.js b/test/parallel/test-http-flush-headers.js index 8ca5e92e5e02bc..88e8bddaed9e54 100644 --- a/test/parallel/test-http-flush-headers.js +++ b/test/parallel/test-http-flush-headers.js @@ -5,7 +5,7 @@ const http = require('http'); const server = http.createServer(); server.on('request', function(req, res) { - assert.strictEqual(req.headers['foo'], 'bar'); + assert.strictEqual(req.headers.foo, 'bar'); res.end('ok'); server.close(); }); diff --git a/test/parallel/test-http-flush-response-headers.js b/test/parallel/test-http-flush-response-headers.js index b8045568d49ac7..0f0a1387b56733 100644 --- a/test/parallel/test-http-flush-response-headers.js +++ b/test/parallel/test-http-flush-response-headers.js @@ -20,7 +20,7 @@ server.listen(0, common.localhostIPv4, function() { req.end(); function onResponse(res) { - assert.strictEqual(res.headers['foo'], 'bar'); + assert.strictEqual(res.headers.foo, 'bar'); res.destroy(); server.close(); } diff --git a/test/parallel/test-http-proxy.js b/test/parallel/test-http-proxy.js index a6267faaa6715c..8781679c0a45b8 100644 --- a/test/parallel/test-http-proxy.js +++ b/test/parallel/test-http-proxy.js @@ -50,7 +50,7 @@ const proxy = http.createServer(function(req, res) { console.error(`proxy res headers: ${JSON.stringify(proxy_res.headers)}`); - assert.strictEqual('world', proxy_res.headers['hello']); + assert.strictEqual('world', proxy_res.headers.hello); assert.strictEqual('text/plain', proxy_res.headers['content-type']); assert.deepStrictEqual(cookies, proxy_res.headers['set-cookie']); @@ -81,7 +81,7 @@ function startReq() { console.error('got res'); assert.strictEqual(200, res.statusCode); - assert.strictEqual('world', res.headers['hello']); + assert.strictEqual('world', res.headers.hello); assert.strictEqual('text/plain', res.headers['content-type']); assert.deepStrictEqual(cookies, res.headers['set-cookie']); diff --git a/test/parallel/test-http-server-multiheaders.js b/test/parallel/test-http-server-multiheaders.js index 201a95c346ae65..bf918ad24cc168 100644 --- a/test/parallel/test-http-server-multiheaders.js +++ b/test/parallel/test-http-server-multiheaders.js @@ -38,7 +38,7 @@ const srv = http.createServer(function(req, res) { assert.strictEqual(req.headers['sec-websocket-protocol'], 'chat, share'); assert.strictEqual(req.headers['sec-websocket-extensions'], 'foo; 1, bar; 2, baz'); - assert.strictEqual(req.headers['constructor'], 'foo, bar, baz'); + assert.strictEqual(req.headers.constructor, 'foo, bar, baz'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('EOF'); diff --git a/test/parallel/test-http-write-head.js b/test/parallel/test-http-write-head.js index 143643c4be4eaf..ae776753f2049f 100644 --- a/test/parallel/test-http-write-head.js +++ b/test/parallel/test-http-write-head.js @@ -66,7 +66,7 @@ s.listen(0, common.mustCall(runTest)); function runTest() { http.get({ port: this.address().port }, common.mustCall((response) => { response.on('end', common.mustCall(() => { - assert.strictEqual(response.headers['test'], '2'); + assert.strictEqual(response.headers.test, '2'); assert(response.rawHeaders.includes('Test')); s.close(); })); diff --git a/test/parallel/test-http.js b/test/parallel/test-http.js index 52bebc476e1510..e9a48c0fba3826 100644 --- a/test/parallel/test-http.js +++ b/test/parallel/test-http.js @@ -33,8 +33,8 @@ const server = http.Server(common.mustCall(function(req, res) { switch (req.url) { case '/hello': assert.strictEqual(req.method, 'GET'); - assert.strictEqual(req.headers['accept'], '*/*'); - assert.strictEqual(req.headers['foo'], 'bar'); + assert.strictEqual(req.headers.accept, '*/*'); + assert.strictEqual(req.headers.foo, 'bar'); assert.strictEqual(req.headers.cookie, 'foo=bar; bar=baz; baz=quux'); break; case '/there': diff --git a/test/parallel/test-http2-compat-expect-handling.js b/test/parallel/test-http2-compat-expect-handling.js index f36032c972fc45..e987118476337d 100644 --- a/test/parallel/test-http2-compat-expect-handling.js +++ b/test/parallel/test-http2-compat-expect-handling.js @@ -11,7 +11,7 @@ const expectValue = 'meoww'; const server = http2.createServer(common.mustNotCall()); server.once('checkExpectation', common.mustCall((req, res) => { - assert.strictEqual(req.headers['expect'], expectValue); + assert.strictEqual(req.headers.expect, expectValue); res.statusCode = 417; res.end(); })); diff --git a/test/parallel/test-http2-compat-serverresponse-createpushresponse.js b/test/parallel/test-http2-compat-serverresponse-createpushresponse.js index 18b3ba15be841c..1b9aa66808eeff 100755 --- a/test/parallel/test-http2-compat-serverresponse-createpushresponse.js +++ b/test/parallel/test-http2-compat-serverresponse-createpushresponse.js @@ -77,7 +77,7 @@ server.listen(0, common.mustCall(() => { let actual = ''; pushStream.on('push', common.mustCall((headers) => { assert.strictEqual(headers[':status'], 200); - assert(headers['date']); + assert(headers.date); })); pushStream.setEncoding('utf8'); pushStream.on('data', (chunk) => actual += chunk); @@ -89,7 +89,7 @@ server.listen(0, common.mustCall(() => { req.on('response', common.mustCall((headers) => { assert.strictEqual(headers[':status'], 200); - assert(headers['date']); + assert(headers.date); })); let actual = ''; diff --git a/test/parallel/test-http2-create-client-secure-session.js b/test/parallel/test-http2-create-client-secure-session.js index b0111e15b69c15..1f20ec8e42a871 100644 --- a/test/parallel/test-http2-create-client-secure-session.js +++ b/test/parallel/test-http2-create-client-secure-session.js @@ -62,7 +62,7 @@ function verifySecureSession(key, cert, ca, opts) { req.on('response', common.mustCall((headers) => { assert.strictEqual(headers[':status'], 200); assert.strictEqual(headers['content-type'], 'application/json'); - assert(headers['date']); + assert(headers.date); })); let data = ''; diff --git a/test/parallel/test-http2-create-client-session.js b/test/parallel/test-http2-create-client-session.js index 963db2faa173b7..34e4e975d92d81 100644 --- a/test/parallel/test-http2-create-client-session.js +++ b/test/parallel/test-http2-create-client-session.js @@ -58,7 +58,7 @@ server.on('listening', common.mustCall(() => { assert.strictEqual(headers[':status'], 200, 'status code is set'); assert.strictEqual(headers['content-type'], 'text/html', 'content type is set'); - assert(headers['date'], 'there is a date'); + assert(headers.date); })); let data = ''; diff --git a/test/parallel/test-http2-multiheaders-raw.js b/test/parallel/test-http2-multiheaders-raw.js index 50486450d5aeb7..da9aa3a68eaa51 100644 --- a/test/parallel/test-http2-multiheaders-raw.js +++ b/test/parallel/test-http2-multiheaders-raw.js @@ -12,7 +12,7 @@ const src = Object.create(null); src['www-authenticate'] = 'foo'; src['WWW-Authenticate'] = 'bar'; src['WWW-AUTHENTICATE'] = 'baz'; -src['test'] = 'foo, bar, baz'; +src.test = 'foo, bar, baz'; server.on('stream', common.mustCall((stream, headers, flags, rawHeaders) => { const expected = [ diff --git a/test/parallel/test-http2-multiheaders.js b/test/parallel/test-http2-multiheaders.js index 9bf8f76d22e60e..6611dcf054d42a 100644 --- a/test/parallel/test-http2-multiheaders.js +++ b/test/parallel/test-http2-multiheaders.js @@ -24,21 +24,21 @@ src.constructor = 'foo'; src.Constructor = 'bar'; src.CONSTRUCTOR = 'baz'; // eslint-disable-next-line no-proto -src['__proto__'] = 'foo'; -src['__PROTO__'] = 'bar'; -src['__Proto__'] = 'baz'; +src.__proto__ = 'foo'; +src.__PROTO__ = 'bar'; +src.__Proto__ = 'baz'; function checkHeaders(headers) { - assert.deepStrictEqual(headers['accept'], + assert.deepStrictEqual(headers.accept, 'abc, def, ghijklmnop'); assert.deepStrictEqual(headers['www-authenticate'], 'foo, bar, baz'); assert.deepStrictEqual(headers['proxy-authenticate'], 'foo, bar, baz'); assert.deepStrictEqual(headers['x-foo'], 'foo, bar, baz'); - assert.deepStrictEqual(headers['constructor'], 'foo, bar, baz'); + assert.deepStrictEqual(headers.constructor, 'foo, bar, baz'); // eslint-disable-next-line no-proto - assert.deepStrictEqual(headers['__proto__'], 'foo, bar, baz'); + assert.deepStrictEqual(headers.__proto__, 'foo, bar, baz'); } server.on('stream', common.mustCall((stream, headers) => { diff --git a/test/parallel/test-http2-no-more-streams.js b/test/parallel/test-http2-no-more-streams.js index dd06a709f23023..ff0c8baa14ccdb 100644 --- a/test/parallel/test-http2-no-more-streams.js +++ b/test/parallel/test-http2-no-more-streams.js @@ -23,10 +23,10 @@ server.listen(0, common.mustCall(() => { assert.strictEqual(client.state.nextStreamID, nextID); - const countdown = new Countdown(2, common.mustCall(() => { + const countdown = new Countdown(2, () => { server.close(); client.close(); - })); + }); { // This one will be ok diff --git a/test/parallel/test-http2-server-rst-stream.js b/test/parallel/test-http2-server-rst-stream.js index c2d938c22f4483..4a58091aa61d7f 100644 --- a/test/parallel/test-http2-server-rst-stream.js +++ b/test/parallel/test-http2-server-rst-stream.js @@ -26,16 +26,16 @@ const tests = [ const server = http2.createServer(); server.on('stream', (stream, headers) => { - stream.close(headers['rstcode'] | 0); + stream.close(headers.rstcode | 0); }); server.listen(0, common.mustCall(() => { const client = http2.connect(`http://localhost:${server.address().port}`); - const countdown = new Countdown(tests.length, common.mustCall(() => { + const countdown = new Countdown(tests.length, () => { client.close(); server.close(); - })); + }); tests.forEach((test) => { const req = client.request({ diff --git a/test/parallel/test-http2-server-set-header.js b/test/parallel/test-http2-server-set-header.js index 4b6228053f8ece..83f373ec21b314 100644 --- a/test/parallel/test-http2-server-set-header.js +++ b/test/parallel/test-http2-server-set-header.js @@ -20,7 +20,7 @@ server.listen(0, common.mustCall(() => { const req = client.request(headers); req.setEncoding('utf8'); req.on('response', common.mustCall(function(headers) { - assert.strictEqual(headers['foobar'], 'baz'); + assert.strictEqual(headers.foobar, 'baz'); assert.strictEqual(headers['x-powered-by'], 'node-test'); })); diff --git a/test/parallel/test-https-agent-session-reuse.js b/test/parallel/test-https-agent-session-reuse.js index 0330e111e9bd47..0717a3f8165d67 100644 --- a/test/parallel/test-https-agent-session-reuse.js +++ b/test/parallel/test-https-agent-session-reuse.js @@ -112,11 +112,11 @@ const server = https.createServer(options, function(req, res) { process.on('exit', function() { assert.strictEqual(serverRequests, 6); - assert.strictEqual(clientSessions['first'].toString('hex'), + assert.strictEqual(clientSessions.first.toString('hex'), clientSessions['first-reuse'].toString('hex')); - assert.notStrictEqual(clientSessions['first'].toString('hex'), + assert.notStrictEqual(clientSessions.first.toString('hex'), clientSessions['cipher-change'].toString('hex')); - assert.notStrictEqual(clientSessions['first'].toString('hex'), + assert.notStrictEqual(clientSessions.first.toString('hex'), clientSessions['before-drop'].toString('hex')); assert.notStrictEqual(clientSessions['cipher-change'].toString('hex'), clientSessions['before-drop'].toString('hex')); diff --git a/test/parallel/test-internal-util-decorate-error-stack.js b/test/parallel/test-internal-util-decorate-error-stack.js index d428e3c7ee2a7b..95f96ea5805d76 100644 --- a/test/parallel/test-internal-util-decorate-error-stack.js +++ b/test/parallel/test-internal-util-decorate-error-stack.js @@ -7,8 +7,8 @@ const internalUtil = require('internal/util'); const binding = process.binding('util'); const spawnSync = require('child_process').spawnSync; -const kArrowMessagePrivateSymbolIndex = binding['arrow_message_private_symbol']; -const kDecoratedPrivateSymbolIndex = binding['decorated_private_symbol']; +const kArrowMessagePrivateSymbolIndex = binding.arrow_message_private_symbol; +const kDecoratedPrivateSymbolIndex = binding.decorated_private_symbol; const decorateErrorStack = internalUtil.decorateErrorStack; diff --git a/test/parallel/test-memory-usage-emfile.js b/test/parallel/test-memory-usage-emfile.js index c5345079a7f47b..f8d1fc90da7aec 100644 --- a/test/parallel/test-memory-usage-emfile.js +++ b/test/parallel/test-memory-usage-emfile.js @@ -10,4 +10,4 @@ while (files.length < 256) files.push(fs.openSync(__filename, 'r')); const r = process.memoryUsage(); -assert.strictEqual(true, r['rss'] > 0); +assert.strictEqual(true, r.rss > 0); diff --git a/test/parallel/test-module-globalpaths-nodepath.js b/test/parallel/test-module-globalpaths-nodepath.js index dce5bf12c1604e..c4492169ad7e81 100644 --- a/test/parallel/test-module-globalpaths-nodepath.js +++ b/test/parallel/test-module-globalpaths-nodepath.js @@ -30,11 +30,11 @@ const partC = ''; if (common.isWindows) { partA = 'C:\\Users\\Rocko Artischocko\\AppData\\Roaming\\npm'; partB = 'C:\\Program Files (x86)\\nodejs\\'; - process.env['NODE_PATH'] = `${partA};${partB};${partC}`; + process.env.NODE_PATH = `${partA};${partB};${partC}`; } else { partA = '/usr/test/lib/node_modules'; partB = '/usr/test/lib/node'; - process.env['NODE_PATH'] = `${partA}:${partB}:${partC}`; + process.env.NODE_PATH = `${partA}:${partB}:${partC}`; } mod._initPaths(); diff --git a/test/parallel/test-module-loading-globalpaths.js b/test/parallel/test-module-loading-globalpaths.js index e3c36cb21c202e..aff96543735428 100644 --- a/test/parallel/test-module-loading-globalpaths.js +++ b/test/parallel/test-module-loading-globalpaths.js @@ -6,6 +6,9 @@ const path = require('path'); const fs = require('fs'); const child_process = require('child_process'); const pkgName = 'foo'; +const { addLibraryPath } = require('../common/shared-lib-util'); + +addLibraryPath(process.env); if (process.argv[2] === 'child') { console.log(require(pkgName).string); @@ -39,14 +42,14 @@ if (process.argv[2] === 'child') { const env = Object.assign({}, process.env); // Turn on module debug to aid diagnosing failures. - env['NODE_DEBUG'] = 'module'; + env.NODE_DEBUG = 'module'; // Unset NODE_PATH. - delete env['NODE_PATH']; + delete env.NODE_PATH; // Test empty global path. const noPkgHomeDir = path.join(tmpdir.path, 'home-no-pkg'); fs.mkdirSync(noPkgHomeDir); - env['HOME'] = env['USERPROFILE'] = noPkgHomeDir; + env.HOME = env.USERPROFILE = noPkgHomeDir; assert.throws( () => { child_process.execFileSync(testExecPath, [ __filename, 'child' ], @@ -56,17 +59,17 @@ if (process.argv[2] === 'child') { // Test module in $HOME/.node_modules. const modHomeDir = path.join(testFixturesDir, 'home-pkg-in-node_modules'); - env['HOME'] = env['USERPROFILE'] = modHomeDir; + env.HOME = env.USERPROFILE = modHomeDir; runTest('$HOME/.node_modules', env); // Test module in $HOME/.node_libraries. const libHomeDir = path.join(testFixturesDir, 'home-pkg-in-node_libraries'); - env['HOME'] = env['USERPROFILE'] = libHomeDir; + env.HOME = env.USERPROFILE = libHomeDir; runTest('$HOME/.node_libraries', env); // Test module both $HOME/.node_modules and $HOME/.node_libraries. const bothHomeDir = path.join(testFixturesDir, 'home-pkg-in-both'); - env['HOME'] = env['USERPROFILE'] = bothHomeDir; + env.HOME = env.USERPROFILE = bothHomeDir; runTest('$HOME/.node_modules', env); // Test module in $PREFIX/lib/node. @@ -79,22 +82,22 @@ if (process.argv[2] === 'child') { const pkgPath = path.join(prefixLibNodePath, `${pkgName}.js`); fs.writeFileSync(pkgPath, `exports.string = '${expectedString}';`); - env['HOME'] = env['USERPROFILE'] = noPkgHomeDir; + env.HOME = env.USERPROFILE = noPkgHomeDir; runTest(expectedString, env); // Test module in all global folders. - env['HOME'] = env['USERPROFILE'] = bothHomeDir; + env.HOME = env.USERPROFILE = bothHomeDir; runTest('$HOME/.node_modules', env); // Test module in NODE_PATH is loaded ahead of global folders. - env['HOME'] = env['USERPROFILE'] = bothHomeDir; - env['NODE_PATH'] = path.join(testFixturesDir, 'node_path'); + env.HOME = env.USERPROFILE = bothHomeDir; + env.NODE_PATH = path.join(testFixturesDir, 'node_path'); runTest('$NODE_PATH', env); // Test module in local folder is loaded ahead of global folders. const localDir = path.join(testFixturesDir, 'local-pkg'); - env['HOME'] = env['USERPROFILE'] = bothHomeDir; - env['NODE_PATH'] = path.join(testFixturesDir, 'node_path'); + env.HOME = env.USERPROFILE = bothHomeDir; + env.NODE_PATH = path.join(testFixturesDir, 'node_path'); const child = child_process.execFileSync(testExecPath, [ path.join(localDir, 'test.js') ], { encoding: 'utf8', env: env }); diff --git a/test/parallel/test-net-connect-handle-econnrefused.js b/test/parallel/test-net-connect-handle-econnrefused.js index 569aded7bf5def..3c7310b4752d72 100644 --- a/test/parallel/test-net-connect-handle-econnrefused.js +++ b/test/parallel/test-net-connect-handle-econnrefused.js @@ -27,11 +27,10 @@ const assert = require('assert'); const server = net.createServer(); server.listen(0); const port = server.address().port; -const c = net.createConnection(port); - -c.on('connect', common.mustNotCall()); - -c.on('error', common.mustCall((e) => { - assert.strictEqual('ECONNREFUSED', e.code); +server.close(common.mustCall(() => { + const c = net.createConnection(port); + c.on('connect', common.mustNotCall()); + c.on('error', common.mustCall((e) => { + assert.strictEqual('ECONNREFUSED', e.code); + })); })); -server.close(); diff --git a/test/parallel/test-net-socket-ready-without-cb.js b/test/parallel/test-net-socket-ready-without-cb.js new file mode 100644 index 00000000000000..1ad5db4760dc1e --- /dev/null +++ b/test/parallel/test-net-socket-ready-without-cb.js @@ -0,0 +1,20 @@ +'use strict'; +const common = require('../common'); + +// This test ensures that socket.connect can be called without callback +// which is optional. + +const net = require('net'); + +const server = net.createServer(common.mustCall(function(conn) { + conn.end(); + server.close(); +})).listen(0, common.mustCall(function() { + const client = new net.Socket(); + + client.on('ready', common.mustCall(function() { + client.end(); + })); + + client.connect(server.address()); +})); diff --git a/test/parallel/test-performanceobserver.js b/test/parallel/test-performanceobserver.js index 081362939ce2b5..96bdbdebc9ac77 100644 --- a/test/parallel/test-performanceobserver.js +++ b/test/parallel/test-performanceobserver.js @@ -64,10 +64,10 @@ assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_FUNCTION], 0); new PerformanceObserver(common.mustCall(callback, 3)); const countdown = - new Countdown(3, common.mustCall(() => { + new Countdown(3, () => { observer.disconnect(); assert.strictEqual(counts[NODE_PERFORMANCE_ENTRY_TYPE_MARK], 1); - })); + }); function callback(list, obs) { assert.strictEqual(obs, observer); diff --git a/test/parallel/test-repl-multiline.js b/test/parallel/test-repl-multiline.js new file mode 100644 index 00000000000000..54048bf31f2f6f --- /dev/null +++ b/test/parallel/test-repl-multiline.js @@ -0,0 +1,35 @@ +'use strict'; +const common = require('../common'); +const assert = require('assert'); +const repl = require('repl'); +const inputStream = new common.ArrayStream(); +const outputStream = new common.ArrayStream(); +const input = ['var foo = {', '};', 'foo;']; +let output = ''; + +outputStream.write = (data) => { output += data.replace('\r', ''); }; + +const r = repl.start({ + prompt: '', + input: inputStream, + output: outputStream, + terminal: true, + useColors: false +}); + +r.on('exit', common.mustCall(() => { + const actual = output.split('\n'); + + // Validate the output, which contains terminal escape codes. + assert.strictEqual(actual.length, 6); + assert.ok(actual[0].endsWith(input[0])); + assert.ok(actual[1].includes('... ')); + assert.ok(actual[1].endsWith(input[1])); + assert.strictEqual(actual[2], 'undefined'); + assert.ok(actual[3].endsWith(input[2])); + assert.strictEqual(actual[4], '{}'); + // Ignore the last line, which is nothing but escape codes. +})); + +inputStream.run(input); +r.close(); diff --git a/test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js b/test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js index 842c8180701aa1..5dceb386fdbdf4 100644 --- a/test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js +++ b/test/parallel/test-timers-socket-timeout-removes-other-socket-unref-timer.js @@ -33,7 +33,7 @@ const server = net.createServer(function onClient(client) { }); server.listen(0, common.localhostIPv4, common.mustCall(() => { - const countdown = new Countdown(2, common.mustCall(() => server.close())); + const countdown = new Countdown(2, () => server.close()); { const client = net.connect({ port: server.address().port }); diff --git a/test/parallel/test-tls-addca.js b/test/parallel/test-tls-addca.js index 034334a7e41bf3..8eb88db6291457 100644 --- a/test/parallel/test-tls-addca.js +++ b/test/parallel/test-tls-addca.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const fixtures = require('../common/fixtures'); // Adding a CA certificate to contextWithCert should not also add it to @@ -32,7 +32,7 @@ clientOptions.secureContext = contextWithoutCert; connect({ client: clientOptions, server: serverOptions, -}, function(err, pair, cleanup) { +}, common.mustCall((err, pair, cleanup) => { assert(err); assert.strictEqual(err.message, 'unable to verify the first certificate'); cleanup(); @@ -43,8 +43,8 @@ connect({ connect({ client: clientOptions, server: serverOptions, - }, function(err, pair, cleanup) { + }, common.mustCall((err, pair, cleanup) => { assert.ifError(err); cleanup(); - }); -}); + })); +})); diff --git a/test/parallel/test-tls-client-getephemeralkeyinfo.js b/test/parallel/test-tls-client-getephemeralkeyinfo.js index ed628204025b16..a50a0354c74014 100644 --- a/test/parallel/test-tls-client-getephemeralkeyinfo.js +++ b/test/parallel/test-tls-client-getephemeralkeyinfo.js @@ -24,7 +24,7 @@ const cipherlist = { }; function test(size, type, name, next) { - const cipher = type ? cipherlist[type] : cipherlist['NOT_PFS']; + const cipher = type ? cipherlist[type] : cipherlist.NOT_PFS; if (name) tls.DEFAULT_ECDH_CURVE = name; diff --git a/test/parallel/test-tls-connect-no-host.js b/test/parallel/test-tls-connect-no-host.js index d685ba90ccdd84..f6384743ac7081 100644 --- a/test/parallel/test-tls-connect-no-host.js +++ b/test/parallel/test-tls-connect-no-host.js @@ -6,7 +6,6 @@ if (!common.hasCrypto) common.skip('missing crypto'); const tls = require('tls'); - const assert = require('assert'); const cert = fixtures.readSync('test_cert.pem'); @@ -15,10 +14,10 @@ const key = fixtures.readSync('test_key.pem'); // https://github.com/nodejs/node/issues/1489 // tls.connect(options) with no options.host should accept a cert with // CN:'localhost' -tls.createServer({ +const server = tls.createServer({ key, cert -}).listen(0, function() { +}).listen(0, common.mustCall(function() { const socket = tls.connect({ port: this.address().port, ca: cert, @@ -26,8 +25,9 @@ tls.createServer({ // but tls.checkServerIdentity() breaks before the fix with: // Error: Hostname/IP doesn't match certificate's altnames: // "Host: undefined. is not cert's CN: localhost" - }, function() { + }, common.mustCall(function() { assert(socket.authorized); - process.exit(); - }); -}); + socket.destroy(); + server.close(); + })); +})); diff --git a/test/parallel/test-tls-finished.js b/test/parallel/test-tls-finished.js new file mode 100644 index 00000000000000..8b52934b049d95 --- /dev/null +++ b/test/parallel/test-tls-finished.js @@ -0,0 +1,66 @@ +'use strict'; + +const common = require('../common'); +const fixtures = require('../common/fixtures'); + +if (!common.hasCrypto) + common.skip('missing crypto'); + +// This test ensures that tlsSocket.getFinished() and +// tlsSocket.getPeerFinished() return undefined before +// secure connection is established, and return non-empty +// Buffer objects with Finished messages afterwards, also +// verifying alice.getFinished() == bob.getPeerFinished() +// and alice.getPeerFinished() == bob.getFinished(). + +const assert = require('assert'); +const tls = require('tls'); + +const msg = {}; +const pem = (n) => fixtures.readKey(`${n}.pem`); +const server = tls.createServer({ + key: pem('agent1-key'), + cert: pem('agent1-cert') +}, common.mustCall((alice) => { + msg.server = { + alice: alice.getFinished(), + bob: alice.getPeerFinished() + }; + server.close(); +})); + +server.listen(0, common.mustCall(() => { + const bob = tls.connect({ + port: server.address().port, + rejectUnauthorized: false + }, common.mustCall(() => { + msg.client = { + alice: bob.getPeerFinished(), + bob: bob.getFinished() + }; + bob.end(); + })); + + msg.before = { + alice: bob.getPeerFinished(), + bob: bob.getFinished() + }; +})); + +process.on('exit', () => { + assert.strictEqual(undefined, msg.before.alice); + assert.strictEqual(undefined, msg.before.bob); + + assert(Buffer.isBuffer(msg.server.alice)); + assert(Buffer.isBuffer(msg.server.bob)); + assert(Buffer.isBuffer(msg.client.alice)); + assert(Buffer.isBuffer(msg.client.bob)); + + assert(msg.server.alice.length > 0); + assert(msg.server.bob.length > 0); + assert(msg.client.alice.length > 0); + assert(msg.client.bob.length > 0); + + assert(msg.server.alice.equals(msg.client.alice)); + assert(msg.server.bob.equals(msg.client.bob)); +}); diff --git a/test/parallel/test-tls-over-http-tunnel.js b/test/parallel/test-tls-over-http-tunnel.js index 8e9bafda5394d6..f3f2bb3f2726ed 100644 --- a/test/parallel/test-tls-over-http-tunnel.js +++ b/test/parallel/test-tls-over-http-tunnel.js @@ -24,6 +24,9 @@ const common = require('../common'); if (!common.hasCrypto) common.skip('missing crypto'); +// This test ensures that the data received through tls over http tunnel +// is same as what is sent. + const assert = require('assert'); const https = require('https'); const net = require('net'); @@ -37,21 +40,21 @@ const cert = fixtures.readKey('agent1-cert.pem'); const options = { key, cert }; -const server = https.createServer(options, function(req, res) { +const server = https.createServer(options, common.mustCall((req, res) => { console.log('SERVER: got request'); res.writeHead(200, { 'content-type': 'text/plain' }); console.log('SERVER: sending response'); res.end('hello world\n'); -}); +})); -const proxy = net.createServer(function(clientSocket) { +const proxy = net.createServer((clientSocket) => { console.log('PROXY: got a client connection'); let serverSocket = null; - clientSocket.on('data', function(chunk) { + clientSocket.on('data', (chunk) => { if (!serverSocket) { // Verify the CONNECT request assert.strictEqual(`CONNECT localhost:${server.address().port} ` + @@ -65,39 +68,39 @@ const proxy = net.createServer(function(clientSocket) { console.log('PROXY: creating a tunnel'); // create the tunnel - serverSocket = net.connect(server.address().port, function() { + serverSocket = net.connect(server.address().port, common.mustCall(() => { console.log('PROXY: replying to client CONNECT request'); // Send the response clientSocket.write('HTTP/1.1 200 OK\r\nProxy-Connections: keep' + - '-alive\r\nConnections: keep-alive\r\nVia: ' + - `localhost:${proxy.address().port}\r\n\r\n`); - }); + '-alive\r\nConnections: keep-alive\r\nVia: ' + + `localhost:${proxy.address().port}\r\n\r\n`); + })); - serverSocket.on('data', function(chunk) { + serverSocket.on('data', (chunk) => { clientSocket.write(chunk); }); - serverSocket.on('end', function() { + serverSocket.on('end', common.mustCall(() => { clientSocket.destroy(); - }); + })); } else { serverSocket.write(chunk); } }); - clientSocket.on('end', function() { + clientSocket.on('end', () => { serverSocket.destroy(); }); }); server.listen(0); -proxy.listen(0, function() { +proxy.listen(0, common.mustCall(() => { console.log('CLIENT: Making CONNECT request'); const req = http.request({ - port: this.address().port, + port: proxy.address().port, method: 'CONNECT', path: `localhost:${server.address().port}`, headers: { @@ -117,7 +120,7 @@ proxy.listen(0, function() { function onUpgrade(res, socket, head) { // Hacky. - process.nextTick(function() { + process.nextTick(() => { onConnect(res, socket, head); }); } @@ -145,20 +148,20 @@ proxy.listen(0, function() { socket: socket, // reuse the socket agent: false, rejectUnauthorized: false - }, function(res) { + }, (res) => { assert.strictEqual(200, res.statusCode); - res.on('data', function(chunk) { + res.on('data', common.mustCall((chunk) => { assert.strictEqual('hello world\n', chunk.toString()); console.log('CLIENT: got HTTPS response'); gotRequest = true; - }); + })); - res.on('end', function() { + res.on('end', common.mustCall(() => { proxy.close(); server.close(); - }); - }).on('error', function(er) { + })); + }).on('error', (er) => { // We're ok with getting ECONNRESET in this test, but it's // timing-dependent, and thus unreliable. Any other errors // are just failures, though. @@ -166,8 +169,8 @@ proxy.listen(0, function() { throw er; }).end(); } -}); +})); -process.on('exit', function() { +process.on('exit', () => { assert.ok(gotRequest); }); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index d9f8e30616657d..00ee7c0f80141e 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -273,7 +273,7 @@ assert.strictEqual( '{ writeonly: [Setter] }'); const value = {}; - value['a'] = value; + value.a = value; assert.strictEqual(util.inspect(value), '{ a: [Circular] }'); } diff --git a/test/parallel/test-util-internal.js b/test/parallel/test-util-internal.js index 63e782f15de1e8..cb3d3122f9be4e 100644 --- a/test/parallel/test-util-internal.js +++ b/test/parallel/test-util-internal.js @@ -6,7 +6,7 @@ const assert = require('assert'); const fixtures = require('../common/fixtures'); const binding = process.binding('util'); -const kArrowMessagePrivateSymbolIndex = binding['arrow_message_private_symbol']; +const kArrowMessagePrivateSymbolIndex = binding.arrow_message_private_symbol; function getHiddenValue(obj, index) { return function() { diff --git a/test/sequential/test-benchmark-buffer.js b/test/sequential/test-benchmark-buffer.js index 26600cf4f26a87..47e4df63e67aff 100644 --- a/test/sequential/test-benchmark-buffer.js +++ b/test/sequential/test-benchmark-buffer.js @@ -11,6 +11,7 @@ runBenchmark('buffers', 'buffer=fast', 'encoding=utf8', 'len=2', + 'millions=0.000001', 'method=', 'n=1', 'noAssert=true', diff --git a/test/sequential/test-benchmark-tls.js b/test/sequential/test-benchmark-tls.js index 7c87aa3cbcd89e..3545955e3ab5b0 100644 --- a/test/sequential/test-benchmark-tls.js +++ b/test/sequential/test-benchmark-tls.js @@ -2,6 +2,9 @@ const common = require('../common'); +if (!common.hasCrypto) + common.skip('missing crypto'); + if (!common.enoughTestMem) common.skip('Insufficient memory for TLS benchmark test'); diff --git a/test/sequential/test-init.js b/test/sequential/test-init.js index 1f1679b5e149f8..5dd8d9ab14ea4f 100644 --- a/test/sequential/test-init.js +++ b/test/sequential/test-init.js @@ -25,7 +25,7 @@ const assert = require('assert'); const child = require('child_process'); const fixtures = require('../common/fixtures'); -if (process.env['TEST_INIT']) { +if (process.env.TEST_INIT) { return process.stdout.write('Loaded successfully!'); } diff --git a/test/sequential/test-inspector-bindings.js b/test/sequential/test-inspector-bindings.js index b2140c11a3329a..bf97d8b5124e86 100644 --- a/test/sequential/test-inspector-bindings.js +++ b/test/sequential/test-inspector-bindings.js @@ -27,9 +27,9 @@ function checkScope(session, scopeId) { } function debuggerPausedCallback(session, notification) { - const params = notification['params']; - const callFrame = params['callFrames'][0]; - const scopeId = callFrame['scopeChain'][0]['object']['objectId']; + const params = notification.params; + const callFrame = params.callFrames[0]; + const scopeId = callFrame.scopeChain[0].object.objectId; checkScope(session, scopeId); } @@ -65,11 +65,11 @@ function testSampleDebugSession() { scopeCallback = function(error, result) { const i = cur++; let v, actual, expected; - for (v of result['result']) { - actual = v['value']['value']; - expected = expects[v['name']][i]; + for (v of result.result) { + actual = v.value.value; + expected = expects[v.name][i]; if (actual !== expected) { - failures.push(`Iteration ${i} variable: ${v['name']} ` + + failures.push(`Iteration ${i} variable: ${v.name} ` + `expected: ${expected} actual: ${actual}`); } } diff --git a/test/sequential/test-inspector-ip-detection.js b/test/sequential/test-inspector-ip-detection.js index f7dee4494d3c03..fb86b3ea4a574e 100644 --- a/test/sequential/test-inspector-ip-detection.js +++ b/test/sequential/test-inspector-ip-detection.js @@ -14,12 +14,12 @@ if (!ip) function checkIpAddress(ip, response) { const res = response[0]; - const wsUrl = res['webSocketDebuggerUrl']; + const wsUrl = res.webSocketDebuggerUrl; assert.ok(wsUrl); const match = wsUrl.match(/^ws:\/\/(.*):\d+\/(.*)/); assert.strictEqual(ip, match[1]); - assert.strictEqual(res['id'], match[2]); - assert.strictEqual(ip, res['devtoolsFrontendUrl'].match(/.*ws=(.*):\d+/)[1]); + assert.strictEqual(res.id, match[2]); + assert.strictEqual(ip, res.devtoolsFrontendUrl.match(/.*ws=(.*):\d+/)[1]); } function pickIPv4Address() { diff --git a/test/sequential/test-inspector.js b/test/sequential/test-inspector.js index 992a12e90229ed..50fcff2d425655 100644 --- a/test/sequential/test-inspector.js +++ b/test/sequential/test-inspector.js @@ -10,10 +10,10 @@ const { mainScriptPath, function checkListResponse(response) { assert.strictEqual(1, response.length); - assert.ok(response[0]['devtoolsFrontendUrl']); + assert.ok(response[0].devtoolsFrontendUrl); assert.ok( /ws:\/\/127\.0\.0\.1:\d+\/[0-9A-Fa-f]{8}-/ - .test(response[0]['webSocketDebuggerUrl'])); + .test(response[0].webSocketDebuggerUrl)); } function checkVersion(response) { @@ -33,7 +33,7 @@ function checkBadPath(err) { } function checkException(message) { - assert.strictEqual(message['exceptionDetails'], undefined, + assert.strictEqual(message.exceptionDetails, undefined, 'An exception occurred during execution'); } @@ -46,10 +46,10 @@ function assertNoUrlsWhileConnected(response) { function assertScopeValues({ result }, expected) { const unmatched = new Set(Object.keys(expected)); for (const actual of result) { - const value = expected[actual['name']]; + const value = expected[actual.name]; if (value) { - assert.strictEqual(value, actual['value']['value']); - unmatched.delete(actual['name']); + assert.strictEqual(value, actual.value.value); + unmatched.delete(actual.name); } } if (unmatched.size) @@ -125,14 +125,14 @@ async function testBreakpoint(session) { } }); - assert.strictEqual(1002, result['value']); + assert.strictEqual(1002, result.value); result = (await session.send({ 'method': 'Runtime.evaluate', 'params': { 'expression': '5 * 5' } })).result; - assert.strictEqual(25, result['value']); + assert.strictEqual(25, result.value); } async function testI18NCharacters(session) { @@ -169,7 +169,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.strictEqual(result['result']['value'], true); + assert.strictEqual(result.result.value, true); // the global require has the same properties as a normal `require` result = await session.send( @@ -184,7 +184,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.strictEqual(result['result']['value'], true); + assert.strictEqual(result.result.value, true); // `require` twice returns the same value result = await session.send( { @@ -200,7 +200,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.strictEqual(result['result']['value'], true); + assert.strictEqual(result.result.value, true); // after require the module appears in require.cache result = await session.send( { @@ -212,7 +212,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.deepStrictEqual(JSON.parse(result['result']['value']), + assert.deepStrictEqual(JSON.parse(result.result.value), { old: 'yes' }); // remove module from require.cache result = await session.send( @@ -223,7 +223,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.strictEqual(result['result']['value'], true); + assert.strictEqual(result.result.value, true); // require again, should get fresh (empty) exports result = await session.send( { @@ -233,7 +233,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.deepStrictEqual(JSON.parse(result['result']['value']), {}); + assert.deepStrictEqual(JSON.parse(result.result.value), {}); // require 2nd module, exports an empty object result = await session.send( { @@ -243,7 +243,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.deepStrictEqual(JSON.parse(result['result']['value']), {}); + assert.deepStrictEqual(JSON.parse(result.result.value), {}); // both modules end up with the same module.parent result = await session.send( { @@ -258,7 +258,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.deepStrictEqual(JSON.parse(result['result']['value']), { + assert.deepStrictEqual(JSON.parse(result.result.value), { parentsEqual: true, parentId: '' }); @@ -275,7 +275,7 @@ async function testCommandLineAPI(session) { } }); checkException(result); - assert.notStrictEqual(result['result']['value'], + assert.notStrictEqual(result.result.value, ''); }