From f25c7ceb731e350591b2e8d406bb8f65d1897ea9 Mon Sep 17 00:00:00 2001 From: Matteo Collina Date: Tue, 12 Jan 2016 12:21:09 +0000 Subject: [PATCH 01/34] win,msi: Added Italian translation As titled. Tested by @piccoloaiutante. PR-URL: https://github.com/nodejs/node/pull/4647 Refs: https://github.com/wixtoolset/wix3/pull/366 Reviewed-By: Rod Vagg Reviewed-By: Frederic Hemberger --- tools/msvs/msi/i18n/it-it.wxl | 38 ++++++++++++++++++++++++++++++++++ tools/msvs/msi/nodemsi.wixproj | 3 +++ 2 files changed, 41 insertions(+) create mode 100644 tools/msvs/msi/i18n/it-it.wxl diff --git a/tools/msvs/msi/i18n/it-it.wxl b/tools/msvs/msi/i18n/it-it.wxl new file mode 100644 index 00000000000000..54a251ea2530b4 --- /dev/null +++ b/tools/msvs/msi/i18n/it-it.wxl @@ -0,0 +1,38 @@ + + + + 1040 + + Installazione di [ProductName] sul tuo computer. + Scegliere una cartella di destinazione o premere Avanti per installare nella cartella predefinita. + + Una versione successiva di [ProductName] è già installata. Il setup terminerà ora. + + + Node.js runtime + Installa [ProductName] runtime (node.exe). + + Performance counters + Installa il supporto per i performance counters specifici di [ProductName]. + + Event tracing (ETW) + Installa il supporto per gli eventi "event tracing" (ETW) generati da [ProductName]. + + npm package manager + Installa npm, il package manager raccomandato per [ProductName]. + + Collegamenti alla documentazione online + Aggiunge i collegamenti al menu start alla documentazione online per [ProductName] [FullVersion] e per il sito web di [ProductName]. + + Aggiunta al PATH + Aggiunge [ProductName], npm, e i moduli installati globalmente da npm alla variable di ambiente PATH. + + Node.js e npm + Aggiunge [ProductName] e npm (se installato) alla variabile di ambiente PATH. + + Moduli npm + Aggiunge i moduli installati globalmente da npm alla variabile di ambiente PATH. Questa opzione avrà effetto solo per l'utente corrente, gli altri utenti dovranno aggiornare la loro variabile PATH manualmente. + + + Node.js è stato installato correttamente. + diff --git a/tools/msvs/msi/nodemsi.wixproj b/tools/msvs/msi/nodemsi.wixproj index 70ffec50bcc8e4..d21a3cf2327432 100644 --- a/tools/msvs/msi/nodemsi.wixproj +++ b/tools/msvs/msi/nodemsi.wixproj @@ -56,6 +56,7 @@ + @@ -78,7 +79,9 @@ From 9db861b650ef7e83172b55f4df45b366e1e466b7 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Sun, 10 Jul 2016 14:01:00 -0700 Subject: [PATCH 02/34] tools: increase lint coverage MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Extend linting to tools/license2rtf.js and any other JS that gets added to the `tools` directory by default. This incidentally simplifies lint invocation. PR-URL: https://github.com/nodejs/node/pull/7647 Reviewed-By: Michaël Zasso Reviewed-By: Ben Noordhuis Reviewed-By: Roman Reiss Reviewed-By: Сковорода Никита Андреевич --- .eslintignore | 4 +- Makefile | 6 +-- tools/license2rtf.js | 100 +++++++++++++++++++++---------------------- vcbuild.bat | 4 +- 4 files changed, 55 insertions(+), 59 deletions(-) diff --git a/.eslintignore b/.eslintignore index 9b5c5fccb643e4..6791fbf312a08b 100644 --- a/.eslintignore +++ b/.eslintignore @@ -2,7 +2,7 @@ lib/internal/v8_prof_polyfill.js lib/punycode.js test/addons/??_*/ test/fixtures -test/**/node_modules test/disabled test/tmp*/ -tools/doc/node_modules +tools/eslint +node_modules diff --git a/Makefile b/Makefile index ebea5354f0c6fb..fe058a5b7ec890 100644 --- a/Makefile +++ b/Makefile @@ -678,13 +678,11 @@ bench-idle: $(NODE) benchmark/idle_clients.js & jslint: - $(NODE) tools/jslint.js -J benchmark lib src test tools/doc \ - tools/eslint-rules tools/jslint.js + $(NODE) tools/jslint.js -J benchmark lib src test tools jslint-ci: $(NODE) tools/jslint.js $(PARALLEL_ARGS) -f tap -o test-eslint.tap \ - benchmark lib src test tools/doc \ - tools/eslint-rules tools/jslint.js + benchmark lib src test tools CPPLINT_EXCLUDE ?= CPPLINT_EXCLUDE += src/node_root_certs.h diff --git a/tools/license2rtf.js b/tools/license2rtf.js index f5a75a176dd6bb..0b66cc10f322f9 100644 --- a/tools/license2rtf.js +++ b/tools/license2rtf.js @@ -1,15 +1,16 @@ +'use strict'; -var assert = require('assert'), - Stream = require('stream'), - inherits = require('util').inherits; +const assert = require('assert'); +const Stream = require('stream'); +const inherits = require('util').inherits; /* * This filter consumes a stream of characters and emits one string per line. */ function LineSplitter() { - var self = this, - buffer = ""; + const self = this; + var buffer = ''; Stream.call(this); this.writable = true; @@ -38,33 +39,31 @@ inherits(LineSplitter, Stream); * This filter consumes lines and emits paragraph objects. */ function ParagraphParser() { - var self = this, - block_is_license_block = false, - block_has_c_style_comment, - is_first_line_in_paragraph, - paragraph_line_indent, - paragraph; - - Stream.call(this); - this.writable = true; - - resetBlock(false); - - this.write = function(data) { - parseLine(data + ''); - return true; - }; - - this.end = function(data) { - if (data) { - parseLine(data + ''); - } - flushParagraph(); - self.emit('end'); - }; + const self = this; + var block_is_license_block = false; + var block_has_c_style_comment; + var paragraph_line_indent; + var paragraph; + + Stream.call(this); + this.writable = true; + + resetBlock(false); + + this.write = function(data) { + parseLine(data + ''); + return true; + }; + + this.end = function(data) { + if (data) { + parseLine(data + ''); + } + flushParagraph(); + self.emit('end'); + }; function resetParagraph() { - is_first_line_in_paragraph = true; paragraph_line_indent = -1; paragraph = { @@ -165,8 +164,6 @@ function ParagraphParser() { if (line) paragraph.lines.push(line); - - is_first_line_in_paragraph = false; } } inherits(ParagraphParser, Stream); @@ -184,16 +181,16 @@ function Unwrapper() { this.writable = true; this.write = function(paragraph) { - var lines = paragraph.lines, - break_after = [], - i; + var lines = paragraph.lines; + var break_after = []; + var i; for (i = 0; i < lines.length - 1; i++) { var line = lines[i]; // When a line is really short, the line was probably kept separate for a // reason. - if (line.length < 50) { + if (line.length < 50) { // If the first word on the next line really didn't fit after the line, // it probably was just ordinary wrapping after all. var next_first_word_length = lines[i + 1].replace(/\s.*$/, '').length; @@ -203,7 +200,7 @@ function Unwrapper() { } } - for (i = 0; i < lines.length - 1; ) { + for (i = 0; i < lines.length - 1;) { if (!break_after[i]) { lines[i] += ' ' + lines.splice(i + 1, 1)[0]; } else { @@ -233,8 +230,8 @@ inherits(Unwrapper, Stream); * This filter generates an rtf document from a stream of paragraph objects. */ function RtfGenerator() { - var self = this, - did_write_anything = false; + const self = this; + var did_write_anything = false; Stream.call(this); this.writable = true; @@ -245,11 +242,11 @@ function RtfGenerator() { did_write_anything = true; } - var li = paragraph.li, - level = paragraph.level + (li ? 1 : 0), - lic = paragraph.in_license_block; + var li = paragraph.li; + var level = paragraph.level + (li ? 1 : 0); + var lic = paragraph.in_license_block; - var rtf = "\\pard"; + var rtf = '\\pard'; rtf += '\\sa150\\sl300\\slmult1'; if (level > 0) rtf += '\\li' + (level * 240); @@ -290,18 +287,19 @@ function RtfGenerator() { function rtfEscape(string) { return string .replace(/[\\\{\}]/g, function(m) { - return '\\' + m; + return '\\' + m; }) .replace(/\t/g, function() { return '\\tab '; }) + // eslint-disable-next-line no-control-regex .replace(/[\x00-\x1f\x7f-\xff]/g, function(m) { return '\\\'' + toHex(m.charCodeAt(0), 2); }) .replace(/\ufeff/g, '') .replace(/[\u0100-\uffff]/g, function(m) { return '\\u' + toHex(m.charCodeAt(0), 4) + '?'; - }); + }); } function emitHeader() { @@ -317,12 +315,12 @@ function RtfGenerator() { inherits(RtfGenerator, Stream); -var stdin = process.stdin, - stdout = process.stdout, - line_splitter = new LineSplitter(), - paragraph_parser = new ParagraphParser(), - unwrapper = new Unwrapper(), - rtf_generator = new RtfGenerator(); +const stdin = process.stdin; +const stdout = process.stdout; +const line_splitter = new LineSplitter(); +const paragraph_parser = new ParagraphParser(); +const unwrapper = new Unwrapper(); +const rtf_generator = new RtfGenerator(); stdin.setEncoding('utf-8'); stdin.resume(); diff --git a/vcbuild.bat b/vcbuild.bat index ee5b4c8a17df08..f95cfca8b390a9 100644 --- a/vcbuild.bat +++ b/vcbuild.bat @@ -348,12 +348,12 @@ if defined jslint_ci goto jslint-ci if not defined jslint goto exit if not exist tools\eslint\bin\eslint.js goto no-lint echo running jslint -%config%\node tools\jslint.js -J benchmark lib src test tools\doc tools\eslint-rules tools\jslint.js +%config%\node tools\jslint.js -J benchmark lib src test tools goto exit :jslint-ci echo running jslint-ci -%config%\node tools\jslint.js -J -f tap -o test-eslint.tap benchmark lib src test tools\doc tools\eslint-rules tools\jslint.js +%config%\node tools\jslint.js -J -f tap -o test-eslint.tap benchmark lib src test tools goto exit :no-lint From 25b3ff402d50fe12d9088973d3f6fd0fa56ce6f6 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Fri, 8 Jul 2016 12:59:26 +0200 Subject: [PATCH 03/34] test,doc: clarify `buf.indexOf(num)` input range Hopefully clarify the behaviour of `buffer.indexOf()` and `buffer.includes()` for numbers in that they will be truncated to uint8s. Add tests for that behaviour. Fixes: https://github.com/nodejs/node/issues/7591 PR-URL: https://github.com/nodejs/node/pull/7611 Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott --- doc/api/buffer.md | 6 ++++-- test/parallel/test-buffer-includes.js | 16 ++++++++++++++++ test/parallel/test-buffer-indexof.js | 16 ++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index fd527a02d170ff..fb8065a645fdab 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -973,7 +973,8 @@ Operates similar to [`Array#indexOf()`][] in that it returns either the starting index position of `value` in Buffer or `-1` if the Buffer does not contain `value`. The `value` can be a String, Buffer or Number. Strings are by default interpreted as UTF8. Buffers will use the entire Buffer (to compare a -partial Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255. +partial Buffer use [`buf.slice()`][]). Numbers will be interpreted as unsigned 8-bit +integer values between `0` and `255`. ```js const buf = Buffer.from('this is a buffer'); @@ -1012,7 +1013,8 @@ added: v5.3.0 Operates similar to [`Array#includes()`][]. The `value` can be a String, Buffer or Number. Strings are interpreted as UTF8 unless overridden with the `encoding` argument. Buffers will use the entire Buffer (to compare a partial -Buffer use [`buf.slice()`][]). Numbers can range from 0 to 255. +Buffer use [`buf.slice()`][]). Numbers will be interpreted as unsigned 8-bit +integer values between `0` and `255`. The `byteOffset` indicates the index in `buf` where searching begins. diff --git a/test/parallel/test-buffer-includes.js b/test/parallel/test-buffer-includes.js index 7962d1cef850f4..5859399b507f86 100644 --- a/test/parallel/test-buffer-includes.js +++ b/test/parallel/test-buffer-includes.js @@ -256,3 +256,19 @@ assert.throws(function() { assert.throws(function() { b.includes([]); }); + +// test truncation of Number arguments to uint8 +{ + const buf = Buffer.from('this is a test'); + assert.ok(buf.includes(0x6973)); + assert.ok(buf.includes(0x697320)); + assert.ok(buf.includes(0x69732069)); + assert.ok(buf.includes(0x697374657374)); + assert.ok(buf.includes(0x69737374)); + assert.ok(buf.includes(0x69737465)); + assert.ok(buf.includes(0x69737465)); + assert.ok(buf.includes(-140)); + assert.ok(buf.includes(-152)); + assert.ok(!buf.includes(0xff)); + assert.ok(!buf.includes(0xffff)); +} diff --git a/test/parallel/test-buffer-indexof.js b/test/parallel/test-buffer-indexof.js index 647f1e9a623248..d699e1cd5909ea 100644 --- a/test/parallel/test-buffer-indexof.js +++ b/test/parallel/test-buffer-indexof.js @@ -448,3 +448,19 @@ pattern = reallyLong.slice(0, 1000000); // First 1/5th. assert.equal(3932160, reallyLong.lastIndexOf(pattern)); pattern = reallyLong.slice(0, 2000000); // first 2/5ths. assert.equal(0, reallyLong.lastIndexOf(pattern)); + +// test truncation of Number arguments to uint8 +{ + const buf = Buffer.from('this is a test'); + assert.strictEqual(buf.indexOf(0x6973), 3); + assert.strictEqual(buf.indexOf(0x697320), 4); + assert.strictEqual(buf.indexOf(0x69732069), 2); + assert.strictEqual(buf.indexOf(0x697374657374), 0); + assert.strictEqual(buf.indexOf(0x69737374), 0); + assert.strictEqual(buf.indexOf(0x69737465), 11); + assert.strictEqual(buf.indexOf(0x69737465), 11); + assert.strictEqual(buf.indexOf(-140), 0); + assert.strictEqual(buf.indexOf(-152), 1); + assert.strictEqual(buf.indexOf(0xff), -1); + assert.strictEqual(buf.indexOf(0xffff), -1); +} From 45a8fce5a465f78163fd8961c11345716b638f46 Mon Sep 17 00:00:00 2001 From: vsemozhetbyt Date: Wed, 6 Jul 2016 21:50:58 +0300 Subject: [PATCH 04/34] doc: fix typo in the CHANGELOG_V6 compliment -> complement PR-URL: https://github.com/nodejs/node/pull/7568 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell --- doc/changelogs/CHANGELOG_V6.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/changelogs/CHANGELOG_V6.md b/doc/changelogs/CHANGELOG_V6.md index 06462967547187..0a6f372a5acaa2 100644 --- a/doc/changelogs/CHANGELOG_V6.md +++ b/doc/changelogs/CHANGELOG_V6.md @@ -33,7 +33,7 @@ October 2016. ### Notable changes -* **buffer**: Added `buffer.swap64()` to compliment `swap16()` & `swap32()`. (Zach Bjornson) [#7157](https://github.com/nodejs/node/pull/7157) +* **buffer**: Added `buffer.swap64()` to complement `swap16()` & `swap32()`. (Zach Bjornson) [#7157](https://github.com/nodejs/node/pull/7157) * **build**: New `configure` options have been added for building Node.js as a shared library. (Stefan Budeanu) [#6994](https://github.com/nodejs/node/pull/6994) - The options are: `--shared`, `--without-v8-platform` & `--without-bundled-v8`. * **crypto**: Root certificates have been updated. (Ben Noordhuis) [#7363](https://github.com/nodejs/node/pull/7363) From 8bbb3eb32c4403949faff3cc0a77ae076fc27830 Mon Sep 17 00:00:00 2001 From: silverwind Date: Wed, 13 Jul 2016 00:09:41 +0200 Subject: [PATCH 05/34] tools: consistent .eslintrc formatting MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All quotes in .eslintrc were unnecessary and inconsistently placed across the file. Additionally, format the globals to be consistent with the style of whitespace and sorted them alphabetically. PR-URL: https://github.com/nodejs/node/pull/7691 Reviewed-By: Colin Ihrig Reviewed-By: Rich Trott Reviewed-By: Michaël Zasso --- .eslintrc | 66 +++++++++++++++++++++++++------------------------- test/.eslintrc | 2 +- 2 files changed, 34 insertions(+), 34 deletions(-) diff --git a/.eslintrc b/.eslintrc index dbc12427ca7ed7..120bca8d2f3b4b 100644 --- a/.eslintrc +++ b/.eslintrc @@ -5,7 +5,7 @@ env: rules: # Possible Errors # http://eslint.org/docs/rules/#possible-errors - comma-dangle: [2, "only-multiline"] + comma-dangle: [2, only-multiline] no-control-regex: 2 no-debugger: 2 no-dupe-args: 2 @@ -14,7 +14,7 @@ rules: no-empty-character-class: 2 no-ex-assign: 2 no-extra-boolean-cast: 2 - no-extra-parens: [2, "functions"] + no-extra-parens: [2, functions] no-extra-semi: 2 no-func-assign: 2 no-invalid-regexp: 2 @@ -38,47 +38,47 @@ rules: # Strict Mode # http://eslint.org/docs/rules/#strict-mode - strict: [2, "global"] + strict: [2, global] # Variables # http://eslint.org/docs/rules/#variables no-delete-var: 2 no-undef: 2 - no-unused-vars: [2, {"args": "none"}] + no-unused-vars: [2, {args: none}] # Node.js and CommonJS # http://eslint.org/docs/rules/#nodejs-and-commonjs no-mixed-requires: 2 no-new-require: 2 no-path-concat: 2 - no-restricted-modules: [2, "sys", "_linklist"] + no-restricted-modules: [2, sys, _linklist] # Stylistic Issues # http://eslint.org/docs/rules/#stylistic-issues - brace-style: [2, "1tbs", {allowSingleLine: true}] + brace-style: [2, 1tbs, {allowSingleLine: true}] comma-spacing: 2 eol-last: 2 indent: [2, 2, {SwitchCase: 1}] - key-spacing: [2, {mode: "minimum"}] + key-spacing: [2, {mode: minimum}] keyword-spacing: 2 - linebreak-style: [2, "unix"] + linebreak-style: [2, unix] max-len: [2, 80, 2] new-parens: 2 no-mixed-spaces-and-tabs: 2 no-multiple-empty-lines: [2, {max: 2}] no-trailing-spaces: 2 - quotes: [2, "single", "avoid-escape"] + quotes: [2, single, avoid-escape] semi: 2 - space-before-blocks: [2, "always"] - space-before-function-paren: [2, "never"] - space-in-parens: [2, "never"] + space-before-blocks: [2, always] + space-before-function-paren: [2, never] + space-in-parens: [2, never] space-infix-ops: 2 space-unary-ops: 2 # ECMAScript 6 # http://eslint.org/docs/rules/#ecmascript-6 - arrow-parens: [2, "always"] - arrow-spacing: [2, {"before": true, "after": true}] + arrow-parens: [2, always] + arrow-spacing: [2, {before: true, after: true}] constructor-super: 2 no-class-assign: 2 no-confusing-arrow: 2 @@ -93,27 +93,27 @@ rules: align-function-arguments: 2 align-multiline-assignment: 2 assert-fail-single-argument: 2 - new-with-error: [2, "Error", "RangeError", "TypeError", "SyntaxError", "ReferenceError"] + new-with-error: [2, Error, RangeError, TypeError, SyntaxError, ReferenceError] no-deepEqual: 2 no-definegetter-definesetter: 2 # Global scoped method and vars globals: - DTRACE_HTTP_CLIENT_REQUEST : false - LTTNG_HTTP_CLIENT_REQUEST : false - COUNTER_HTTP_CLIENT_REQUEST : false - DTRACE_HTTP_CLIENT_RESPONSE : false - LTTNG_HTTP_CLIENT_RESPONSE : false - COUNTER_HTTP_CLIENT_RESPONSE : false - DTRACE_HTTP_SERVER_REQUEST : false - LTTNG_HTTP_SERVER_REQUEST : false - COUNTER_HTTP_SERVER_REQUEST : false - DTRACE_HTTP_SERVER_RESPONSE : false - LTTNG_HTTP_SERVER_RESPONSE : false - COUNTER_HTTP_SERVER_RESPONSE : false - DTRACE_NET_STREAM_END : false - LTTNG_NET_STREAM_END : false - COUNTER_NET_SERVER_CONNECTION_CLOSE : false - DTRACE_NET_SERVER_CONNECTION : false - LTTNG_NET_SERVER_CONNECTION : false - COUNTER_NET_SERVER_CONNECTION : false + COUNTER_HTTP_CLIENT_REQUEST: false + COUNTER_HTTP_CLIENT_RESPONSE: false + COUNTER_HTTP_SERVER_REQUEST: false + COUNTER_HTTP_SERVER_RESPONSE: false + COUNTER_NET_SERVER_CONNECTION: false + COUNTER_NET_SERVER_CONNECTION_CLOSE: false + DTRACE_HTTP_CLIENT_REQUEST: false + DTRACE_HTTP_CLIENT_RESPONSE: false + DTRACE_HTTP_SERVER_REQUEST: false + DTRACE_HTTP_SERVER_RESPONSE: false + DTRACE_NET_SERVER_CONNECTION: false + DTRACE_NET_STREAM_END: false + LTTNG_HTTP_CLIENT_REQUEST: false + LTTNG_HTTP_CLIENT_RESPONSE: false + LTTNG_HTTP_SERVER_REQUEST: false + LTTNG_HTTP_SERVER_RESPONSE: false + LTTNG_NET_SERVER_CONNECTION: false + LTTNG_NET_STREAM_END: false diff --git a/test/.eslintrc b/test/.eslintrc index b498b08f4d7d0c..d20e21aa27f2a3 100644 --- a/test/.eslintrc +++ b/test/.eslintrc @@ -2,4 +2,4 @@ rules: ## common module is mandatory in tests - required-modules: [2, "common"] + required-modules: [2, common] From e1e477e2a0b00581a2fb013e3c71232ed7f75922 Mon Sep 17 00:00:00 2001 From: Minqi Pan Date: Thu, 14 Jul 2016 10:59:44 +0800 Subject: [PATCH 06/34] win,msi: add zh-CN translations for the installer PR-URL: https://github.com/nodejs/node/pull/2569 Reviewed-By: Jackson Tian Reviewed-By: Wexpo Lyu Reviewed-By: Yiyu He Reviewed-By: Yorkie Liu --- tools/msvs/msi/i18n/zh-cn.wxl | 38 +++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 tools/msvs/msi/i18n/zh-cn.wxl diff --git a/tools/msvs/msi/i18n/zh-cn.wxl b/tools/msvs/msi/i18n/zh-cn.wxl new file mode 100644 index 00000000000000..605eea70927c14 --- /dev/null +++ b/tools/msvs/msi/i18n/zh-cn.wxl @@ -0,0 +1,38 @@ + + + + 2052 + + 本安装向导将在您的计算机上安装 [ProductName]。 + 请选择一个自定义的安装位置,或单击下一步开始安装。 + + 已安装 [ProductName] 的一个更高版本。安装程序将立即退出。 + + + Node.js 运行时 + 安装核心 [ProductName] 运行时(node.exe)。 + + 性能计数器 + 为 [ProductName] 安装特定的性能计数器支持。 + + 事件追踪(ETW) + 为 [ProductName] 生成的事件安装事件追踪(ETW)的支持。 + + npm 包管理器 + 安装 npm, [ProductName] 的推荐包管理器。 + + 在线文档的快捷方式 + 在开始菜单内添加 [ProductName] [FullVersion] 的在线文档链接和 [ProductName] 的网站链接。 + + 添加到 PATH 环境变量中 + 把 [ProductName], npm 和以全局方式安装的 npm 模块添加到 PATH 环境变量中。 + + Node.js 和 npm + 把 [ProductName] 和 npm(如果安装了)添加到 PATH 环境变量中。 + + npm 模块 + 把以全局方式安装的 npm 模块添加到 PATH 环境变量中。此选项仅适用于当前用户;其他用户需要手动更新他们的 PATH 环境变量。 + + + Node.js 已成功安装。 + From 43b5bf4616dcb4ab0ae356295a7c8dbb4312c5fd Mon Sep 17 00:00:00 2001 From: Eugene Ostroukhov Date: Wed, 1 Jun 2016 16:07:23 -0700 Subject: [PATCH 07/34] inspector: Unify event queues Current implementation tracks connected/disconnected status separately which potentially introduces race condition. This change introduces notion of session IDs and also posts connect/disconnect events into the same queue as the messages. This way Node knows what session given response belongs to and can discard messages if the frontend for that session had disconnected. This also fixes an issue when frontend was unable to attach to V8 instance that was running infinite loop. PR-URL: https://github.com/nodejs/node/pull/7271 Reviewed-By: bnoordhuis - Ben Noordhuis --- src/inspector_agent.cc | 213 +++++++++++++++++++++-------------------- 1 file changed, 110 insertions(+), 103 deletions(-) diff --git a/src/inspector_agent.cc b/src/inspector_agent.cc index 8ef95305a6f3c0..d8233f41dc2de9 100644 --- a/src/inspector_agent.cc +++ b/src/inspector_agent.cc @@ -17,6 +17,7 @@ #include "libplatform/libplatform.h" #include +#include #include // We need pid to use as ID with Chrome @@ -31,6 +32,9 @@ namespace node { namespace { +const char TAG_CONNECT[] = "#connect"; +const char TAG_DISCONNECT[] = "#disconnect"; + const char DEVTOOLS_PATH[] = "/node"; const char DEVTOOLS_HASH[] = "521e5b7e2b7cc66b4006a8a54cb9c4e57494a5ef"; @@ -154,7 +158,6 @@ bool RespondToGet(inspector_socket_t* socket, const char* path, int port) { namespace inspector { using blink::protocol::DictionaryValue; -using blink::protocol::String16; class AgentImpl { public: @@ -171,24 +174,27 @@ class AgentImpl { void WaitForDisconnect(); private: + using MessageQueue = std::vector>; + static void ThreadCbIO(void* agent); static void OnSocketConnectionIO(uv_stream_t* server, int status); static bool OnInspectorHandshakeIO(inspector_socket_t* socket, enum inspector_handshake_event state, const char* path); - static void OnRemoteDataIO(uv_stream_t* stream, ssize_t read, - const uv_buf_t* b); static void WriteCbIO(uv_async_t* async); void WorkerRunIO(); void OnInspectorConnectionIO(inspector_socket_t* socket); - void PushPendingMessage(std::vector* queue, - const std::string& message); - void SwapBehindLock(std::vector AgentImpl::*queue, - std::vector* output); + void OnRemoteDataIO(inspector_socket_t* stream, ssize_t read, + const uv_buf_t* b); void PostMessages(); void SetConnected(bool connected); - void Write(const std::string& message); + void DispatchMessages(); + void Write(int session_id, const String16& message); + void AppendMessage(MessageQueue* vector, int session_id, + const String16& message); + void SwapBehindLock(MessageQueue* vector1, MessageQueue* vector2); + void PostIncomingMessage(const String16& message); uv_sem_t start_sem_; ConditionVariable pause_cond_; @@ -208,19 +214,28 @@ class AgentImpl { inspector_socket_t* client_socket_; blink::V8Inspector* inspector_; v8::Platform* platform_; - std::vector message_queue_; - std::vector outgoing_message_queue_; + MessageQueue incoming_message_queue_; + MessageQueue outgoing_message_queue_; bool dispatching_messages_; + int frontend_session_id_; + int backend_session_id_; friend class ChannelImpl; friend class DispatchOnInspectorBackendTask; friend class SetConnectedTask; friend class V8NodeInspector; friend void InterruptCallback(v8::Isolate*, void* agent); + friend void DataCallback(uv_stream_t* stream, ssize_t read, + const uv_buf_t* buf); }; void InterruptCallback(v8::Isolate*, void* agent) { - static_cast(agent)->PostMessages(); + static_cast(agent)->DispatchMessages(); +} + +void DataCallback(uv_stream_t* stream, ssize_t read, const uv_buf_t* buf) { + inspector_socket_t* socket = static_cast(stream->data); + static_cast(socket->data)->OnRemoteDataIO(socket, read, buf); } class DispatchOnInspectorBackendTask : public v8::Task { @@ -228,7 +243,7 @@ class DispatchOnInspectorBackendTask : public v8::Task { explicit DispatchOnInspectorBackendTask(AgentImpl* agent) : agent_(agent) {} void Run() override { - agent_->PostMessages(); + agent_->DispatchMessages(); } private: @@ -251,27 +266,12 @@ class ChannelImpl final : public blink::protocol::FrontendChannel { void flushProtocolNotifications() override { } void sendMessageToFrontend(const String16& message) { - agent_->Write(message.utf8()); + agent_->Write(agent_->frontend_session_id_, message); } AgentImpl* const agent_; }; -class SetConnectedTask : public v8::Task { - public: - SetConnectedTask(AgentImpl* agent, bool connected) - : agent_(agent), - connected_(connected) {} - - void Run() override { - agent_->SetConnected(connected_); - } - - private: - AgentImpl* agent_; - bool connected_; -}; - class V8NodeInspector : public blink::V8Inspector { public: V8NodeInspector(AgentImpl* agent, node::Environment* env, @@ -320,7 +320,9 @@ AgentImpl::AgentImpl(Environment* env) : port_(0), client_socket_(nullptr), inspector_(nullptr), platform_(nullptr), - dispatching_messages_(false) { + dispatching_messages_(false), + frontend_session_id_(0), + backend_session_id_(0) { CHECK_EQ(0, uv_sem_init(&start_sem_, 0)); memset(&data_written_, 0, sizeof(data_written_)); memset(&io_thread_req_, 0, sizeof(io_thread_req_)); @@ -355,10 +357,7 @@ void AgentImpl::Start(v8::Platform* platform, int port, bool wait) { uv_sem_wait(&start_sem_); if (wait) { - // Flush messages in case of wait to connect, see OnRemoteDataIO on how it - // should be fixed. - SetConnected(true); - PostMessages(); + DispatchMessages(); } } @@ -424,55 +423,39 @@ bool AgentImpl::OnInspectorHandshakeIO(inspector_socket_t* socket, } } -// static -void AgentImpl::OnRemoteDataIO(uv_stream_t* stream, - ssize_t read, - const uv_buf_t* b) { - inspector_socket_t* socket = static_cast(stream->data); - AgentImpl* agent = static_cast(socket->data); - Mutex::ScopedLock scoped_lock(agent->pause_lock_); +void AgentImpl::OnRemoteDataIO(inspector_socket_t* socket, + ssize_t read, + const uv_buf_t* buf) { + Mutex::ScopedLock scoped_lock(pause_lock_); if (read > 0) { - std::string str(b->base, read); - agent->PushPendingMessage(&agent->message_queue_, str); - free(b->base); - + String16 str = String16::fromUTF8(buf->base, read); + PostIncomingMessage(str); // TODO(pfeldman): Instead of blocking execution while debugger // engages, node should wait for the run callback from the remote client // and initiate its startup. This is a change to node.cc that should be // upstreamed separately. - if (agent->wait_ && str.find("\"Runtime.run\"") != std::string::npos) { - agent->wait_ = false; - uv_sem_post(&agent->start_sem_); + if (wait_ && str.find("\"Runtime.run\"") != std::string::npos) { + wait_ = false; + uv_sem_post(&start_sem_); } - agent->platform_->CallOnForegroundThread(agent->parent_env_->isolate(), - new DispatchOnInspectorBackendTask(agent)); - agent->parent_env_->isolate() - ->RequestInterrupt(InterruptCallback, agent); - uv_async_send(&agent->data_written_); + platform_->CallOnForegroundThread(parent_env_->isolate(), + new DispatchOnInspectorBackendTask(this)); + parent_env_->isolate()->RequestInterrupt(InterruptCallback, this); + uv_async_send(&data_written_); } else if (read <= 0) { // EOF - if (agent->client_socket_ == socket) { - agent->client_socket_ = nullptr; - agent->platform_->CallOnForegroundThread(agent->parent_env_->isolate(), - new SetConnectedTask(agent, false)); - uv_async_send(&agent->data_written_); + if (client_socket_ == socket) { + String16 message(TAG_DISCONNECT, sizeof(TAG_DISCONNECT) - 1); + client_socket_ = nullptr; + PostIncomingMessage(message); } DisconnectAndDisposeIO(socket); } - agent->pause_cond_.Broadcast(scoped_lock); -} - -void AgentImpl::PushPendingMessage(std::vector* queue, - const std::string& message) { - Mutex::ScopedLock scoped_lock(queue_lock_); - queue->push_back(message); -} - -void AgentImpl::SwapBehindLock(std::vector AgentImpl::*queue, - std::vector* output) { - Mutex::ScopedLock scoped_lock(queue_lock_); - (this->*queue).swap(*output); + if (buf) { + free(buf->base); + } + pause_cond_.Broadcast(scoped_lock); } // static @@ -480,11 +463,14 @@ void AgentImpl::WriteCbIO(uv_async_t* async) { AgentImpl* agent = static_cast(async->data); inspector_socket_t* socket = agent->client_socket_; if (socket) { - std::vector outgoing_messages; - agent->SwapBehindLock(&AgentImpl::outgoing_message_queue_, - &outgoing_messages); - for (auto const& message : outgoing_messages) - inspector_write(socket, message.c_str(), message.length()); + MessageQueue outgoing_messages; + agent->SwapBehindLock(&agent->outgoing_message_queue_, &outgoing_messages); + for (const MessageQueue::value_type& outgoing : outgoing_messages) { + if (outgoing.first == agent->frontend_session_id_) { + std::string message = outgoing.second.utf8(); + inspector_write(socket, message.c_str(), message.length()); + } + } } } @@ -518,49 +504,70 @@ void AgentImpl::WorkerRunIO() { uv_run(&child_loop_, UV_RUN_DEFAULT); } +void AgentImpl::AppendMessage(MessageQueue* queue, int session_id, + const String16& message) { + Mutex::ScopedLock scoped_lock(queue_lock_); + queue->push_back(std::make_pair(session_id, message)); +} + +void AgentImpl::SwapBehindLock(MessageQueue* vector1, MessageQueue* vector2) { + Mutex::ScopedLock scoped_lock(queue_lock_); + vector1->swap(*vector2); +} + +void AgentImpl::PostIncomingMessage(const String16& message) { + AppendMessage(&incoming_message_queue_, frontend_session_id_, message); + v8::Isolate* isolate = parent_env_->isolate(); + platform_->CallOnForegroundThread(isolate, + new DispatchOnInspectorBackendTask(this)); + isolate->RequestInterrupt(InterruptCallback, this); + uv_async_send(&data_written_); +} + void AgentImpl::OnInspectorConnectionIO(inspector_socket_t* socket) { if (client_socket_) { DisconnectAndDisposeIO(socket); return; } client_socket_ = socket; - inspector_read_start(socket, OnBufferAlloc, AgentImpl::OnRemoteDataIO); - platform_->CallOnForegroundThread(parent_env_->isolate(), - new SetConnectedTask(this, true)); + inspector_read_start(socket, OnBufferAlloc, DataCallback); + frontend_session_id_++; + PostIncomingMessage(String16(TAG_CONNECT, sizeof(TAG_CONNECT) - 1)); } -void AgentImpl::PostMessages() { +void AgentImpl::DispatchMessages() { if (dispatching_messages_) return; dispatching_messages_ = true; - std::vector messages; - SwapBehindLock(&AgentImpl::message_queue_, &messages); - for (auto const& message : messages) - inspector_->dispatchMessageFromFrontend( - String16::fromUTF8(message.c_str(), message.length())); + MessageQueue tasks; + SwapBehindLock(&incoming_message_queue_, &tasks); + for (const MessageQueue::value_type& pair : tasks) { + const String16& message = pair.second; + if (message == TAG_CONNECT) { + CHECK_EQ(false, connected_); + backend_session_id_++; + connected_ = true; + fprintf(stderr, "Debugger attached.\n"); + inspector_->connectFrontend(new ChannelImpl(this)); + } else if (message == TAG_DISCONNECT) { + CHECK(connected_); + connected_ = false; + if (!shutting_down_) + PrintDebuggerReadyMessage(port_); + inspector_->quitMessageLoopOnPause(); + inspector_->disconnectFrontend(); + } else { + inspector_->dispatchMessageFromFrontend(message); + } + } uv_async_send(&data_written_); dispatching_messages_ = false; } -void AgentImpl::SetConnected(bool connected) { - if (connected_ == connected) - return; - - connected_ = connected; - if (connected) { - fprintf(stderr, "Debugger attached.\n"); - inspector_->connectFrontend(new ChannelImpl(this)); - } else { - if (!shutting_down_) - PrintDebuggerReadyMessage(port_); - inspector_->quitMessageLoopOnPause(); - inspector_->disconnectFrontend(); - } -} - -void AgentImpl::Write(const std::string& message) { - PushPendingMessage(&outgoing_message_queue_, message); - ASSERT_EQ(0, uv_async_send(&io_thread_req_)); +void AgentImpl::Write(int session_id, const String16& message) { + AppendMessage(&outgoing_message_queue_, session_id, message); + int err = uv_async_send(&io_thread_req_); + CHECK_EQ(0, err); } // Exported class Agent From ccd498359b608a9c3b86da099e983fd6d3f84588 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 12 Jul 2016 12:17:28 -0400 Subject: [PATCH 08/34] test: add common.rootDir A few of the child process tests can be simplified by computing the OS specific root directory in common and then accessing that value. PR-URL: https://github.com/nodejs/node/pull/7685 Reviewed-By: Roman Reiss --- test/common.js | 1 + test/parallel/test-child-process-cwd.js | 3 +-- test/parallel/test-child-process-spawnsync.js | 2 +- test/sequential/test-child-process-execsync.js | 17 +++++------------ 4 files changed, 8 insertions(+), 15 deletions(-) diff --git a/test/common.js b/test/common.js index 5aefdc3bcee5f1..f9d80ff1490e42 100644 --- a/test/common.js +++ b/test/common.js @@ -27,6 +27,7 @@ exports.isSunOS = process.platform === 'sunos'; exports.isFreeBSD = process.platform === 'freebsd'; exports.enoughTestMem = os.totalmem() > 0x20000000; /* 512MB */ +exports.rootDir = exports.isWindows ? 'c:\\' : '/'; function rimrafSync(p) { try { diff --git a/test/parallel/test-child-process-cwd.js b/test/parallel/test-child-process-cwd.js index f13da684fbdfe4..108538629e7060 100644 --- a/test/parallel/test-child-process-cwd.js +++ b/test/parallel/test-child-process-cwd.js @@ -36,12 +36,11 @@ function testCwd(options, forCode, forData) { } // Assume these exist, and 'pwd' gives us the right directory back +testCwd({cwd: common.rootDir}, 0, common.rootDir); if (common.isWindows) { testCwd({cwd: process.env.windir}, 0, process.env.windir); - testCwd({cwd: 'c:\\'}, 0, 'c:\\'); } else { testCwd({cwd: '/dev'}, 0, '/dev'); - testCwd({cwd: '/'}, 0, '/'); } // Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT diff --git a/test/parallel/test-child-process-spawnsync.js b/test/parallel/test-child-process-spawnsync.js index d45cc1e0dcea7a..77d205f79a414e 100644 --- a/test/parallel/test-child-process-spawnsync.js +++ b/test/parallel/test-child-process-spawnsync.js @@ -20,7 +20,7 @@ assert.deepStrictEqual(ret_err.spawnargs, ['bar']); { // Test the cwd option - const cwd = common.isWindows ? 'c:\\' : '/'; + const cwd = common.rootDir; const response = common.spawnSyncPwd({cwd}); assert.strictEqual(response.stdout.toString().trim(), cwd); diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index fcb923a38fcfd0..2fad4ba8c205b7 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -61,20 +61,13 @@ assert.strictEqual(ret, msg + '\n', 'execFileSync encoding result should match'); // Verify that the cwd option works - GH #7824 -(function() { - var response; - var cwd; - - if (common.isWindows) { - cwd = 'c:\\'; - response = execSync('echo %cd%', {cwd: cwd}); - } else { - cwd = '/'; - response = execSync('pwd', {cwd: cwd}); - } +{ + const cwd = common.rootDir; + const cmd = common.isWindows ? 'echo %cd%' : 'pwd'; + const response = execSync(cmd, {cwd}); assert.strictEqual(response.toString().trim(), cwd); -})(); +} // Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 (function() { From f00346500a82244dc02ec51a145bd93893f52900 Mon Sep 17 00:00:00 2001 From: Claudio Rodriguez Date: Fri, 1 Jul 2016 09:33:20 +0100 Subject: [PATCH 09/34] fs: rename event to eventType in fs.watch listener The name 'event' for the argument of the listener in fs.watch was confusing considering FSWatcher also had events. This changes the name of the argument to eventType. Fixes: https://github.com/nodejs/node/issues/7504 PR-URL: https://github.com/nodejs/node/pull/7506 Reviewed-By: Rich Trott Reviewed-By: Sakthipriyan Vairamani --- doc/api/fs.md | 21 +++++++++++++++------ lib/fs.js | 4 ++-- 2 files changed, 17 insertions(+), 8 deletions(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index bd975732c67987..74da659dbf6625 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -109,14 +109,19 @@ non-UTF-8 encoded Buffers to `fs` functions will not work as expected. added: v0.5.8 --> -Objects returned from `fs.watch()` are of this type. +Objects returned from [`fs.watch()`][] are of this type. + +The `listener` callback provided to `fs.watch()` receives the returned FSWatcher's +`change` events. + +The object itself emits these events: ### Event: 'change' -* `event` {String} The type of fs change +* `eventType` {String} The type of fs change * `filename` {String | Buffer} The filename that changed (if relevant/available) Emitted when something changes in a watched directory or file. @@ -128,7 +133,8 @@ support. If `filename` is provided, it will be provided as a `Buffer` if `filename` will be a string. ```js -fs.watch('./tmp', {encoding: 'buffer'}, (event, filename) => { +// Example when handled through fs.watch listener +fs.watch('./tmp', {encoding: 'buffer'}, (eventType, filename) => { if (filename) console.log(filename); // Prints: @@ -1443,10 +1449,13 @@ directory. The returned object is a [`fs.FSWatcher`][]. The second argument is optional. If `options` is provided as a string, it specifies the `encoding`. Otherwise `options` should be passed as an object. -The listener callback gets two arguments `(event, filename)`. `event` is either +The listener callback gets two arguments `(eventType, filename)`. `eventType` is either `'rename'` or `'change'`, and `filename` is the name of the file which triggered the event. +Please note the listener callback is attached to the `'change'` event +fired by [`fs.FSWatcher`][], but they are not the same thing. + ### Caveats @@ -1499,8 +1508,8 @@ be provided. Therefore, don't assume that `filename` argument is always provided in the callback, and have some fallback logic if it is null. ```js -fs.watch('somedir', (event, filename) => { - console.log(`event is: ${event}`); +fs.watch('somedir', (eventType, filename) => { + console.log(`event type is: ${eventType}`); if (filename) { console.log(`filename provided: ${filename}`); } else { diff --git a/lib/fs.js b/lib/fs.js index 39bb3777bf9035..e3bfdabe885734 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -1399,7 +1399,7 @@ function FSWatcher() { this._handle = new FSEvent(); this._handle.owner = this; - this._handle.onchange = function(status, event, filename) { + this._handle.onchange = function(status, eventType, filename) { if (status < 0) { self._handle.close(); const error = !filename ? @@ -1409,7 +1409,7 @@ function FSWatcher() { error.filename = filename; self.emit('error', error); } else { - self.emit('change', event, filename); + self.emit('change', eventType, filename); } }; } From 1af8c03c99de9e441d6289bee20e6acc918d6988 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Tue, 12 Jul 2016 19:47:32 -0400 Subject: [PATCH 10/34] test: cleanup IIFE tests A number of test files use IIFEs to separate distinct tests from each other in the same file. The project has been moving toward using block scopes and let/const in favor of IIFEs. This commit moves IIFE tests to block scopes. Some additional cleanup such as use of strictEqual() and common.mustCall() is also included. PR-URL: https://github.com/nodejs/node/pull/7694 Reviewed-By: Santiago Gimeno --- test/gc/test-net-timeout.js | 22 +- test/parallel/test-buffer-alloc.js | 84 ++--- test/parallel/test-buffer.js | 88 ++--- test/parallel/test-child-process-cwd.js | 15 +- test/parallel/test-crypto-authenticated.js | 78 ++-- test/parallel/test-crypto-binary-default.js | 36 +- test/parallel/test-crypto-cipher-decipher.js | 30 +- test/parallel/test-crypto-dh.js | 12 +- test/parallel/test-crypto-from-binary.js | 20 +- test/parallel/test-crypto-rsa-dsa.js | 60 ++-- test/parallel/test-fs-mkdir.js | 40 +-- test/parallel/test-fs-truncate-GH-6233.js | 18 +- test/parallel/test-fs-write-stream-end.js | 20 +- test/parallel/test-fs-write-stream.js | 13 +- test/parallel/test-http-1.0.js | 90 ++--- test/parallel/test-http-parser.js | 340 +++++++++--------- test/parallel/test-querystring.js | 8 +- test/parallel/test-require-cache.js | 18 +- .../test-stream-pipe-error-handling.js | 88 ++--- test/parallel/test-stream-readable-event.js | 78 +--- .../test-stream-writable-decoded-encoding.js | 22 +- .../test-stream2-pipe-error-handling.js | 36 +- test/parallel/test-stringbytes-external.js | 70 ++-- test/parallel/test-timers-unref.js | 6 +- test/parallel/test-timers-zero-timeout.js | 39 +- test/parallel/test-tls-connect.js | 25 +- test/parallel/test-util-format.js | 6 +- test/parallel/test-vm-debug-context.js | 12 +- test/parallel/test-zlib-dictionary-fail.js | 12 +- test/pummel/test-https-ci-reneg-attack.js | 6 +- test/pummel/test-net-connect-memleak.js | 7 +- test/pummel/test-tls-ci-reneg-attack.js | 6 +- test/pummel/test-tls-connect-memleak.js | 10 +- .../sequential/test-child-process-execsync.js | 4 +- 34 files changed, 667 insertions(+), 752 deletions(-) diff --git a/test/gc/test-net-timeout.js b/test/gc/test-net-timeout.js index ff1d5656ce9bcf..2645ccc5038d91 100644 --- a/test/gc/test-net-timeout.js +++ b/test/gc/test-net-timeout.js @@ -35,19 +35,16 @@ function getall() { if (count >= todo) return; - (function() { - var req = net.connect(server.address().port, server.address().address); - req.resume(); - req.setTimeout(10, function() { - //console.log('timeout (expected)') - req.destroy(); - done++; - global.gc(); - }); + const req = net.connect(server.address().port, server.address().address); + req.resume(); + req.setTimeout(10, function() { + req.destroy(); + done++; + global.gc(); + }); - count++; - weak(req, afterGC); - })(); + count++; + weak(req, afterGC); setImmediate(getall); } @@ -76,4 +73,3 @@ function status() { }, 200); } } - diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index 0f06393d6a5aaa..c06c1107039cb2 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -1029,28 +1029,28 @@ Buffer.from(Buffer.allocUnsafe(0), 0, 0); // GH-5110 -(function() { +{ const buffer = Buffer.from('test'); const string = JSON.stringify(buffer); - assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); + assert.strictEqual(string, '{"type":"Buffer","data":[116,101,115,116]}'); assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) { return value && value.type === 'Buffer' ? Buffer.from(value.data) : value; })); -})(); +} // issue GH-7849 -(function() { - var buf = Buffer.from('test'); - var json = JSON.stringify(buf); - var obj = JSON.parse(json); - var copy = Buffer.from(obj); +{ + const buf = Buffer.from('test'); + const json = JSON.stringify(buf); + const obj = JSON.parse(json); + const copy = Buffer.from(obj); assert(buf.equals(copy)); -})(); +} // issue GH-4331 assert.throws(function() { @@ -1156,30 +1156,30 @@ assert.throws(function() { }); // test for common read(U)IntLE/BE -(function() { +{ var buf = Buffer.from([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); - assert.equal(buf.readUIntLE(0, 1), 0x01); - assert.equal(buf.readUIntBE(0, 1), 0x01); - assert.equal(buf.readUIntLE(0, 3), 0x030201); - assert.equal(buf.readUIntBE(0, 3), 0x010203); - assert.equal(buf.readUIntLE(0, 5), 0x0504030201); - assert.equal(buf.readUIntBE(0, 5), 0x0102030405); - assert.equal(buf.readUIntLE(0, 6), 0x060504030201); - assert.equal(buf.readUIntBE(0, 6), 0x010203040506); - assert.equal(buf.readIntLE(0, 1), 0x01); - assert.equal(buf.readIntBE(0, 1), 0x01); - assert.equal(buf.readIntLE(0, 3), 0x030201); - assert.equal(buf.readIntBE(0, 3), 0x010203); - assert.equal(buf.readIntLE(0, 5), 0x0504030201); - assert.equal(buf.readIntBE(0, 5), 0x0102030405); - assert.equal(buf.readIntLE(0, 6), 0x060504030201); - assert.equal(buf.readIntBE(0, 6), 0x010203040506); -})(); + assert.strictEqual(buf.readUIntLE(0, 1), 0x01); + assert.strictEqual(buf.readUIntBE(0, 1), 0x01); + assert.strictEqual(buf.readUIntLE(0, 3), 0x030201); + assert.strictEqual(buf.readUIntBE(0, 3), 0x010203); + assert.strictEqual(buf.readUIntLE(0, 5), 0x0504030201); + assert.strictEqual(buf.readUIntBE(0, 5), 0x0102030405); + assert.strictEqual(buf.readUIntLE(0, 6), 0x060504030201); + assert.strictEqual(buf.readUIntBE(0, 6), 0x010203040506); + assert.strictEqual(buf.readIntLE(0, 1), 0x01); + assert.strictEqual(buf.readIntBE(0, 1), 0x01); + assert.strictEqual(buf.readIntLE(0, 3), 0x030201); + assert.strictEqual(buf.readIntBE(0, 3), 0x010203); + assert.strictEqual(buf.readIntLE(0, 5), 0x0504030201); + assert.strictEqual(buf.readIntBE(0, 5), 0x0102030405); + assert.strictEqual(buf.readIntLE(0, 6), 0x060504030201); + assert.strictEqual(buf.readIntBE(0, 6), 0x010203040506); +} // test for common write(U)IntLE/BE -(function() { - var buf = Buffer.allocUnsafe(3); +{ + let buf = Buffer.allocUnsafe(3); buf.writeUIntLE(0x123456, 0, 3); assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.equal(buf.readUIntLE(0, 3), 0x123456); @@ -1268,11 +1268,11 @@ assert.throws(function() { buf.writeIntBE(-0x0012000000, 0, 5); assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); assert.equal(buf.readIntBE(0, 5), -0x0012000000); -})(); +} // test Buffer slice -(function() { - var buf = Buffer.from('0123456789'); +{ + const buf = Buffer.from('0123456789'); assert.equal(buf.slice(-10, 10), '0123456789'); assert.equal(buf.slice(-20, 10), '0123456789'); assert.equal(buf.slice(-20, -10), ''); @@ -1305,7 +1305,7 @@ assert.throws(function() { assert.equal(buf.slice(0, -i), s.slice(0, -i)); } - var utf16Buf = Buffer.from('0123456789', 'utf16le'); + const utf16Buf = Buffer.from('0123456789', 'utf16le'); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer.from('012', 'utf16le')); assert.equal(buf.slice('0', '1'), '0'); @@ -1319,7 +1319,7 @@ assert.throws(function() { // try to slice a zero length Buffer // see https://github.com/joyent/node/issues/5881 Buffer.alloc(0).slice(0, 1); -})(); +} // Regression test for #5482: should throw but not assert in C++ land. assert.throws(function() { @@ -1328,20 +1328,20 @@ assert.throws(function() { // Regression test for #6111. Constructing a buffer from another buffer // should a) work, and b) not corrupt the source buffer. -(function() { - var a = [0]; +{ + let a = [0]; for (let i = 0; i < 7; ++i) a = a.concat(a); a = a.map(function(_, i) { return i; }); const b = Buffer.from(a); const c = Buffer.from(b); - assert.equal(b.length, a.length); - assert.equal(c.length, a.length); + assert.strictEqual(b.length, a.length); + assert.strictEqual(c.length, a.length); for (let i = 0, k = a.length; i < k; ++i) { - assert.equal(a[i], i); - assert.equal(b[i], i); - assert.equal(c[i], i); + assert.strictEqual(a[i], i); + assert.strictEqual(b[i], i); + assert.strictEqual(c[i], i); } -})(); +} assert.throws(function() { diff --git a/test/parallel/test-buffer.js b/test/parallel/test-buffer.js index 02f94436968c30..a007a1088b3e70 100644 --- a/test/parallel/test-buffer.js +++ b/test/parallel/test-buffer.js @@ -1031,28 +1031,28 @@ Buffer(Buffer(0), 0, 0); // GH-5110 -(function() { +{ const buffer = new Buffer('test'); const string = JSON.stringify(buffer); - assert.equal(string, '{"type":"Buffer","data":[116,101,115,116]}'); + assert.strictEqual(string, '{"type":"Buffer","data":[116,101,115,116]}'); assert.deepStrictEqual(buffer, JSON.parse(string, function(key, value) { return value && value.type === 'Buffer' ? new Buffer(value.data) : value; })); -})(); +} // issue GH-7849 -(function() { - var buf = new Buffer('test'); - var json = JSON.stringify(buf); - var obj = JSON.parse(json); - var copy = new Buffer(obj); +{ + const buf = new Buffer('test'); + const json = JSON.stringify(buf); + const obj = JSON.parse(json); + const copy = new Buffer(obj); assert(buf.equals(copy)); -})(); +} // issue GH-4331 assert.throws(function() { @@ -1168,30 +1168,30 @@ assert.throws(function() { }); // test for common read(U)IntLE/BE -(function() { - var buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); - - assert.equal(buf.readUIntLE(0, 1), 0x01); - assert.equal(buf.readUIntBE(0, 1), 0x01); - assert.equal(buf.readUIntLE(0, 3), 0x030201); - assert.equal(buf.readUIntBE(0, 3), 0x010203); - assert.equal(buf.readUIntLE(0, 5), 0x0504030201); - assert.equal(buf.readUIntBE(0, 5), 0x0102030405); - assert.equal(buf.readUIntLE(0, 6), 0x060504030201); - assert.equal(buf.readUIntBE(0, 6), 0x010203040506); - assert.equal(buf.readIntLE(0, 1), 0x01); - assert.equal(buf.readIntBE(0, 1), 0x01); - assert.equal(buf.readIntLE(0, 3), 0x030201); - assert.equal(buf.readIntBE(0, 3), 0x010203); - assert.equal(buf.readIntLE(0, 5), 0x0504030201); - assert.equal(buf.readIntBE(0, 5), 0x0102030405); - assert.equal(buf.readIntLE(0, 6), 0x060504030201); - assert.equal(buf.readIntBE(0, 6), 0x010203040506); -})(); +{ + const buf = new Buffer([0x01, 0x02, 0x03, 0x04, 0x05, 0x06]); + + assert.strictEqual(buf.readUIntLE(0, 1), 0x01); + assert.strictEqual(buf.readUIntBE(0, 1), 0x01); + assert.strictEqual(buf.readUIntLE(0, 3), 0x030201); + assert.strictEqual(buf.readUIntBE(0, 3), 0x010203); + assert.strictEqual(buf.readUIntLE(0, 5), 0x0504030201); + assert.strictEqual(buf.readUIntBE(0, 5), 0x0102030405); + assert.strictEqual(buf.readUIntLE(0, 6), 0x060504030201); + assert.strictEqual(buf.readUIntBE(0, 6), 0x010203040506); + assert.strictEqual(buf.readIntLE(0, 1), 0x01); + assert.strictEqual(buf.readIntBE(0, 1), 0x01); + assert.strictEqual(buf.readIntLE(0, 3), 0x030201); + assert.strictEqual(buf.readIntBE(0, 3), 0x010203); + assert.strictEqual(buf.readIntLE(0, 5), 0x0504030201); + assert.strictEqual(buf.readIntBE(0, 5), 0x0102030405); + assert.strictEqual(buf.readIntLE(0, 6), 0x060504030201); + assert.strictEqual(buf.readIntBE(0, 6), 0x010203040506); +} // test for common write(U)IntLE/BE -(function() { - var buf = Buffer(3); +{ + let buf = Buffer(3); buf.writeUIntLE(0x123456, 0, 3); assert.deepStrictEqual(buf.toJSON().data, [0x56, 0x34, 0x12]); assert.equal(buf.readUIntLE(0, 3), 0x123456); @@ -1280,11 +1280,11 @@ assert.throws(function() { buf.writeIntBE(-0x0012000000, 0, 5); assert.deepStrictEqual(buf.toJSON().data, [0xff, 0xee, 0x00, 0x00, 0x00]); assert.equal(buf.readIntBE(0, 5), -0x0012000000); -})(); +} // test Buffer slice -(function() { - var buf = new Buffer('0123456789'); +{ + const buf = new Buffer('0123456789'); assert.equal(buf.slice(-10, 10), '0123456789'); assert.equal(buf.slice(-20, 10), '0123456789'); assert.equal(buf.slice(-20, -10), ''); @@ -1317,7 +1317,7 @@ assert.throws(function() { assert.equal(buf.slice(0, -i), s.slice(0, -i)); } - var utf16Buf = new Buffer('0123456789', 'utf16le'); + const utf16Buf = new Buffer('0123456789', 'utf16le'); assert.deepStrictEqual(utf16Buf.slice(0, 6), Buffer('012', 'utf16le')); assert.equal(buf.slice('0', '1'), '0'); @@ -1331,7 +1331,7 @@ assert.throws(function() { // try to slice a zero length Buffer // see https://github.com/joyent/node/issues/5881 SlowBuffer(0).slice(0, 1); -})(); +} // Regression test for #5482: should throw but not assert in C++ land. assert.throws(function() { @@ -1340,20 +1340,20 @@ assert.throws(function() { // Regression test for #6111. Constructing a buffer from another buffer // should a) work, and b) not corrupt the source buffer. -(function() { - var a = [0]; +{ + let a = [0]; for (let i = 0; i < 7; ++i) a = a.concat(a); a = a.map(function(_, i) { return i; }); const b = Buffer(a); const c = Buffer(b); - assert.equal(b.length, a.length); - assert.equal(c.length, a.length); + assert.strictEqual(b.length, a.length); + assert.strictEqual(c.length, a.length); for (let i = 0, k = a.length; i < k; ++i) { - assert.equal(a[i], i); - assert.equal(b[i], i); - assert.equal(c[i], i); + assert.strictEqual(a[i], i); + assert.strictEqual(b[i], i); + assert.strictEqual(c[i], i); } -})(); +} assert.throws(function() { diff --git a/test/parallel/test-child-process-cwd.js b/test/parallel/test-child-process-cwd.js index 108538629e7060..acba57939f0afe 100644 --- a/test/parallel/test-child-process-cwd.js +++ b/test/parallel/test-child-process-cwd.js @@ -44,18 +44,11 @@ if (common.isWindows) { } // Assume does-not-exist doesn't exist, expect exitCode=-1 and errno=ENOENT -(function() { - var errors = 0; - - testCwd({cwd: 'does-not-exist'}, -1).on('error', function(e) { +{ + testCwd({cwd: 'does-not-exist'}, -1).on('error', common.mustCall(function(e) { assert.equal(e.code, 'ENOENT'); - errors++; - }); - - process.on('exit', function() { - assert.equal(errors, 1); - }); -})(); + })); +} // Spawn() shouldn't try to chdir() so this should just work testCwd(undefined, 0); diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index f1b92f8a19dafc..331c2d20e0a441 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -322,34 +322,34 @@ for (var i in TEST_CASES) { continue; } - (function() { - var encrypt = crypto.createCipheriv(test.algo, + { + const encrypt = crypto.createCipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); if (test.aad) encrypt.setAAD(Buffer.from(test.aad, 'hex')); - var inputEncoding = test.plainIsHex ? 'hex' : 'ascii'; - var hex = encrypt.update(test.plain, inputEncoding, 'hex'); + const inputEncoding = test.plainIsHex ? 'hex' : 'ascii'; + let hex = encrypt.update(test.plain, inputEncoding, 'hex'); hex += encrypt.final('hex'); - var auth_tag = encrypt.getAuthTag(); + const auth_tag = encrypt.getAuthTag(); // only test basic encryption run if output is marked as tampered. if (!test.tampered) { - assert.equal(hex, test.ct); - assert.equal(auth_tag.toString('hex'), test.tag); + assert.strictEqual(hex, test.ct); + assert.strictEqual(auth_tag.toString('hex'), test.tag); } - })(); + } - (function() { - var decrypt = crypto.createDecipheriv(test.algo, + { + const decrypt = crypto.createDecipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); if (test.aad) decrypt.setAAD(Buffer.from(test.aad, 'hex')); - var outputEncoding = test.plainIsHex ? 'hex' : 'ascii'; + const outputEncoding = test.plainIsHex ? 'hex' : 'ascii'; - var msg = decrypt.update(test.ct, 'hex', outputEncoding); + let msg = decrypt.update(test.ct, 'hex', outputEncoding); if (!test.tampered) { msg += decrypt.final(outputEncoding); assert.equal(msg, test.plain); @@ -357,48 +357,48 @@ for (var i in TEST_CASES) { // assert that final throws if input data could not be verified! assert.throws(function() { decrypt.final('ascii'); }, / auth/); } - })(); + } - (function() { + { if (!test.password) return; if (common.hasFipsCrypto) { assert.throws(() => { crypto.createCipher(test.algo, test.password); }, /not supported in FIPS mode/); } else { - var encrypt = crypto.createCipher(test.algo, test.password); + const encrypt = crypto.createCipher(test.algo, test.password); if (test.aad) encrypt.setAAD(Buffer.from(test.aad, 'hex')); - var hex = encrypt.update(test.plain, 'ascii', 'hex'); + let hex = encrypt.update(test.plain, 'ascii', 'hex'); hex += encrypt.final('hex'); - var auth_tag = encrypt.getAuthTag(); + const auth_tag = encrypt.getAuthTag(); // only test basic encryption run if output is marked as tampered. if (!test.tampered) { - assert.equal(hex, test.ct); - assert.equal(auth_tag.toString('hex'), test.tag); + assert.strictEqual(hex, test.ct); + assert.strictEqual(auth_tag.toString('hex'), test.tag); } } - })(); + } - (function() { + { if (!test.password) return; if (common.hasFipsCrypto) { assert.throws(() => { crypto.createDecipher(test.algo, test.password); }, /not supported in FIPS mode/); } else { - var decrypt = crypto.createDecipher(test.algo, test.password); + const decrypt = crypto.createDecipher(test.algo, test.password); decrypt.setAuthTag(Buffer.from(test.tag, 'hex')); if (test.aad) decrypt.setAAD(Buffer.from(test.aad, 'hex')); - var msg = decrypt.update(test.ct, 'hex', 'ascii'); + let msg = decrypt.update(test.ct, 'hex', 'ascii'); if (!test.tampered) { msg += decrypt.final('ascii'); - assert.equal(msg, test.plain); + assert.strictEqual(msg, test.plain); } else { // assert that final throws if input data could not be verified! assert.throws(function() { decrypt.final('ascii'); }, / auth/); } } - })(); + } // after normal operation, test some incorrect ways of calling the API: // it's most certainly enough to run these tests with one algorithm only. @@ -407,41 +407,41 @@ for (var i in TEST_CASES) { continue; } - (function() { + { // non-authenticating mode: - var encrypt = crypto.createCipheriv('aes-128-cbc', + const encrypt = crypto.createCipheriv('aes-128-cbc', 'ipxp9a6i1Mb4USb4', '6fKjEjR3Vl30EUYC'); encrypt.update('blah', 'ascii'); encrypt.final(); assert.throws(() => { encrypt.getAuthTag(); }, / state/); assert.throws(() => { encrypt.setAAD(Buffer.from('123', 'ascii')); }, / state/); - })(); + } - (function() { + { // trying to get tag before inputting all data: - var encrypt = crypto.createCipheriv(test.algo, + const encrypt = crypto.createCipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); encrypt.update('blah', 'ascii'); assert.throws(function() { encrypt.getAuthTag(); }, / state/); - })(); + } - (function() { + { // trying to set tag on encryption object: - var encrypt = crypto.createCipheriv(test.algo, + const encrypt = crypto.createCipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); assert.throws(() => { encrypt.setAuthTag(Buffer.from(test.tag, 'hex')); }, / state/); - })(); + } - (function() { + { // trying to read tag from decryption object: - var decrypt = crypto.createDecipheriv(test.algo, + const decrypt = crypto.createDecipheriv(test.algo, Buffer.from(test.key, 'hex'), Buffer.from(test.iv, 'hex')); assert.throws(function() { decrypt.getAuthTag(); }, / state/); - })(); + } - (function() { + { // trying to create cipher with incorrect IV length assert.throws(function() { crypto.createCipheriv( @@ -450,5 +450,5 @@ for (var i in TEST_CASES) { Buffer.alloc(0) ); }, /Invalid IV length/); - })(); + } } diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index 74447ce69d2ee9..2386ff1c24b5b4 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -580,58 +580,58 @@ assert.strictEqual(rsaVerify.verify(rsaPubPem, rsaSignature, 'hex'), true); // // Test RSA signing and verification // -(function() { - var privateKey = fs.readFileSync( +{ + const privateKey = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_2.pem'); - var publicKey = fs.readFileSync( + const publicKey = fs.readFileSync( common.fixturesDir + '/test_rsa_pubkey_2.pem'); - var input = 'I AM THE WALRUS'; + const input = 'I AM THE WALRUS'; - var signature = + const signature = '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '0ddfb299bedeb1ad'; - var sign = crypto.createSign('RSA-SHA256'); + const sign = crypto.createSign('RSA-SHA256'); sign.update(input); - var output = sign.sign(privateKey, 'hex'); - assert.equal(output, signature); + const output = sign.sign(privateKey, 'hex'); + assert.strictEqual(output, signature); - var verify = crypto.createVerify('RSA-SHA256'); + const verify = crypto.createVerify('RSA-SHA256'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); +} // // Test DSA signing and verification // -(function() { - var privateKey = fs.readFileSync( +{ + const privateKey = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey.pem'); - var publicKey = fs.readFileSync( + const publicKey = fs.readFileSync( common.fixturesDir + '/test_dsa_pubkey.pem'); - var input = 'I AM THE WALRUS'; + const input = 'I AM THE WALRUS'; // DSA signatures vary across runs so there is no static string to verify // against - var sign = crypto.createSign('DSS1'); + const sign = crypto.createSign('DSS1'); sign.update(input); - var signature = sign.sign(privateKey, 'hex'); + const signature = sign.sign(privateKey, 'hex'); - var verify = crypto.createVerify('DSS1'); + const verify = crypto.createVerify('DSS1'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); +} // diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index eef329b5f35384..8c9daa16e875f3 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -73,35 +73,35 @@ testCipher2('0123456789abcdef'); testCipher2(Buffer.from('0123456789abcdef')); // Base64 padding regression test, see #4837. -(function() { - var c = crypto.createCipher('aes-256-cbc', 'secret'); - var s = c.update('test', 'utf8', 'base64') + c.final('base64'); - assert.equal(s, '375oxUQCIocvxmC5At+rvA=='); -})(); +{ + const c = crypto.createCipher('aes-256-cbc', 'secret'); + const s = c.update('test', 'utf8', 'base64') + c.final('base64'); + assert.strictEqual(s, '375oxUQCIocvxmC5At+rvA=='); +} // Calling Cipher.final() or Decipher.final() twice should error but // not assert. See #4886. -(function() { - var c = crypto.createCipher('aes-256-cbc', 'secret'); +{ + const c = crypto.createCipher('aes-256-cbc', 'secret'); try { c.final('xxx'); } catch (e) { /* Ignore. */ } try { c.final('xxx'); } catch (e) { /* Ignore. */ } try { c.final('xxx'); } catch (e) { /* Ignore. */ } - var d = crypto.createDecipher('aes-256-cbc', 'secret'); + const d = crypto.createDecipher('aes-256-cbc', 'secret'); try { d.final('xxx'); } catch (e) { /* Ignore. */ } try { d.final('xxx'); } catch (e) { /* Ignore. */ } try { d.final('xxx'); } catch (e) { /* Ignore. */ } -})(); +} // Regression test for #5482: string to Cipher#update() should not assert. -(function() { - var c = crypto.createCipher('aes192', '0123456789abcdef'); +{ + const c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update'); c.final(); -})(); +} // #5655 regression tests, 'utf-8' and 'utf8' are identical. -(function() { - var c = crypto.createCipher('aes192', '0123456789abcdef'); +{ + let c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update', ''); // Defaults to "utf8". c.final('utf-8'); // Should not throw. @@ -112,4 +112,4 @@ testCipher2(Buffer.from('0123456789abcdef')); c = crypto.createCipher('aes192', '0123456789abcdef'); c.update('update', 'utf-8'); c.final('utf8'); // Should not throw. -})(); +} diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index e9fbd30a2effc8..17ee6134c6124b 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -57,19 +57,19 @@ var secret3 = dh3.computeSecret(key2, 'hex', 'base64'); assert.equal(secret1, secret3); // Run this one twice to make sure that the dh3 clears its error properly -(function() { - var c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); +{ + const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); assert.throws(function() { c.final('utf8'); }, /wrong final block length/); -})(); +} assert.throws(function() { dh3.computeSecret(''); }, /key is too small/i); -(function() { - var c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); +{ + const c = crypto.createDecipheriv('aes-128-ecb', crypto.randomBytes(16), ''); assert.throws(function() { c.final('utf8'); }, /wrong final block length/); -})(); +} // Create a shared using a DH group. var alice = crypto.createDiffieHellmanGroup('modp5'); diff --git a/test/parallel/test-crypto-from-binary.js b/test/parallel/test-crypto-from-binary.js index 5c7e75a72104c5..0889541ef6e144 100644 --- a/test/parallel/test-crypto-from-binary.js +++ b/test/parallel/test-crypto-from-binary.js @@ -29,18 +29,18 @@ var b = Buffer.from(ucs2_control + ucs2_control, 'ucs2'); // // Test updating from birant data // -(function() { - var datum1 = b.slice(700000); - var hash1_converted = crypto.createHash('sha1') +{ + const datum1 = b.slice(700000); + const hash1_converted = crypto.createHash('sha1') .update(datum1.toString('base64'), 'base64') .digest('hex'); - var hash1_direct = crypto.createHash('sha1').update(datum1).digest('hex'); - assert.equal(hash1_direct, hash1_converted, 'should hash the same.'); + const hash1_direct = crypto.createHash('sha1').update(datum1).digest('hex'); + assert.strictEqual(hash1_direct, hash1_converted, 'should hash the same.'); - var datum2 = b; - var hash2_converted = crypto.createHash('sha1') + const datum2 = b; + const hash2_converted = crypto.createHash('sha1') .update(datum2.toString('base64'), 'base64') .digest('hex'); - var hash2_direct = crypto.createHash('sha1').update(datum2).digest('hex'); - assert.equal(hash2_direct, hash2_converted, 'should hash the same.'); -})(); + const hash2_direct = crypto.createHash('sha1').update(datum2).digest('hex'); + assert.strictEqual(hash2_direct, hash2_converted, 'should hash the same.'); +} diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 2e29cd723d2677..a05102320caa7c 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -27,20 +27,20 @@ var dsaKeyPemEncrypted = fs.readFileSync( common.fixturesDir + '/test_dsa_privkey_encrypted.pem', 'ascii'); // Test RSA encryption/decryption -(function() { - var input = 'I AM THE WALRUS'; - var bufferToEncrypt = Buffer.from(input); +{ + const input = 'I AM THE WALRUS'; + const bufferToEncrypt = Buffer.from(input); - var encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); + let encryptedBuffer = crypto.publicEncrypt(rsaPubPem, bufferToEncrypt); - var decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + let decryptedBuffer = crypto.privateDecrypt(rsaKeyPem, encryptedBuffer); + assert.strictEqual(input, decryptedBuffer.toString()); - var decryptedBufferWithPassword = crypto.privateDecrypt({ + let decryptedBufferWithPassword = crypto.privateDecrypt({ key: rsaKeyPemEncrypted, passphrase: 'password' }, encryptedBuffer); - assert.equal(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(input, decryptedBufferWithPassword.toString()); encryptedBuffer = crypto.publicEncrypt({ key: rsaKeyPemEncrypted, @@ -51,7 +51,7 @@ var dsaKeyPemEncrypted = fs.readFileSync( key: rsaKeyPemEncrypted, passphrase: 'password' }, encryptedBuffer); - assert.equal(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(input, decryptedBufferWithPassword.toString()); encryptedBuffer = crypto.privateEncrypt({ key: rsaKeyPemEncrypted, @@ -62,22 +62,22 @@ var dsaKeyPemEncrypted = fs.readFileSync( key: rsaKeyPemEncrypted, passphrase: Buffer.from('password') }, encryptedBuffer); - assert.equal(input, decryptedBufferWithPassword.toString()); + assert.strictEqual(input, decryptedBufferWithPassword.toString()); encryptedBuffer = crypto.publicEncrypt(certPem, bufferToEncrypt); decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + assert.strictEqual(input, decryptedBuffer.toString()); encryptedBuffer = crypto.publicEncrypt(keyPem, bufferToEncrypt); decryptedBuffer = crypto.privateDecrypt(keyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + assert.strictEqual(input, decryptedBuffer.toString()); encryptedBuffer = crypto.privateEncrypt(keyPem, bufferToEncrypt); decryptedBuffer = crypto.publicDecrypt(keyPem, encryptedBuffer); - assert.equal(input, decryptedBuffer.toString()); + assert.strictEqual(input, decryptedBuffer.toString()); assert.throws(function() { crypto.privateDecrypt({ @@ -104,7 +104,7 @@ var dsaKeyPemEncrypted = fs.readFileSync( passphrase: [].concat.apply([], Buffer.from('password')) }, encryptedBuffer); }); -})(); +} function test_rsa(padding) { var input = Buffer.allocUnsafe(padding === 'RSA_NO_PADDING' ? 1024 / 8 : 32); @@ -176,52 +176,52 @@ assert.throws(function() { // // Test RSA signing and verification // -(function() { - var privateKey = fs.readFileSync( +{ + const privateKey = fs.readFileSync( common.fixturesDir + '/test_rsa_privkey_2.pem'); - var publicKey = fs.readFileSync( + const publicKey = fs.readFileSync( common.fixturesDir + '/test_rsa_pubkey_2.pem'); - var input = 'I AM THE WALRUS'; + const input = 'I AM THE WALRUS'; - var signature = + const signature = '79d59d34f56d0e94aa6a3e306882b52ed4191f07521f25f505a078dc2f89' + '396e0c8ac89e996fde5717f4cb89199d8fec249961fcb07b74cd3d2a4ffa' + '235417b69618e4bcd76b97e29975b7ce862299410e1b522a328e44ac9bb2' + '8195e0268da7eda23d9825ac43c724e86ceeee0d0d4465678652ccaf6501' + '0ddfb299bedeb1ad'; - var sign = crypto.createSign('RSA-SHA256'); + const sign = crypto.createSign('RSA-SHA256'); sign.update(input); - var output = sign.sign(privateKey, 'hex'); - assert.equal(output, signature); + const output = sign.sign(privateKey, 'hex'); + assert.strictEqual(output, signature); - var verify = crypto.createVerify('RSA-SHA256'); + const verify = crypto.createVerify('RSA-SHA256'); verify.update(input); assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); -})(); +} // // Test DSA signing and verification // -(function() { - var input = 'I AM THE WALRUS'; +{ + const input = 'I AM THE WALRUS'; // DSA signatures vary across runs so there is no static string to verify // against - var sign = crypto.createSign('DSS1'); + const sign = crypto.createSign('DSS1'); sign.update(input); - var signature = sign.sign(dsaKeyPem, 'hex'); + const signature = sign.sign(dsaKeyPem, 'hex'); - var verify = crypto.createVerify('DSS1'); + const verify = crypto.createVerify('DSS1'); verify.update(input); assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); -})(); +} // diff --git a/test/parallel/test-fs-mkdir.js b/test/parallel/test-fs-mkdir.js index ae13b9bc7a071d..2b8e8b8f026637 100644 --- a/test/parallel/test-fs-mkdir.js +++ b/test/parallel/test-fs-mkdir.js @@ -12,53 +12,47 @@ function unlink(pathname) { common.refreshTmpDir(); -(function() { - var ncalls = 0; - var pathname = common.tmpDir + '/test1'; +{ + const pathname = common.tmpDir + '/test1'; unlink(pathname); - fs.mkdir(pathname, function(err) { - assert.equal(err, null); - assert.equal(common.fileExists(pathname), true); - ncalls++; - }); + fs.mkdir(pathname, common.mustCall(function(err) { + assert.strictEqual(err, null); + assert.strictEqual(common.fileExists(pathname), true); + })); process.on('exit', function() { unlink(pathname); - assert.equal(ncalls, 1); }); -})(); +} -(function() { - var ncalls = 0; - var pathname = common.tmpDir + '/test2'; +{ + const pathname = common.tmpDir + '/test2'; unlink(pathname); - fs.mkdir(pathname, 0o777, function(err) { + fs.mkdir(pathname, 0o777, common.mustCall(function(err) { assert.equal(err, null); assert.equal(common.fileExists(pathname), true); - ncalls++; - }); + })); process.on('exit', function() { unlink(pathname); - assert.equal(ncalls, 1); }); -})(); +} -(function() { - var pathname = common.tmpDir + '/test3'; +{ + const pathname = common.tmpDir + '/test3'; unlink(pathname); fs.mkdirSync(pathname); - var exists = common.fileExists(pathname); + const exists = common.fileExists(pathname); unlink(pathname); - assert.equal(exists, true); -})(); + assert.strictEqual(exists, true); +} // Keep the event loop alive so the async mkdir() requests // have a chance to run (since they don't ref the event loop). diff --git a/test/parallel/test-fs-truncate-GH-6233.js b/test/parallel/test-fs-truncate-GH-6233.js index 023d08b15101d7..acfdd1ccae1259 100644 --- a/test/parallel/test-fs-truncate-GH-6233.js +++ b/test/parallel/test-fs-truncate-GH-6233.js @@ -8,19 +8,19 @@ var filename = common.tmpDir + '/truncate-file.txt'; common.refreshTmpDir(); // Synchronous test. -(function() { +{ fs.writeFileSync(filename, '0123456789'); - assert.equal(fs.readFileSync(filename).toString(), '0123456789'); + assert.strictEqual(fs.readFileSync(filename).toString(), '0123456789'); fs.truncateSync(filename, 5); - assert.equal(fs.readFileSync(filename).toString(), '01234'); -})(); + assert.strictEqual(fs.readFileSync(filename).toString(), '01234'); +} // Asynchronous test. -(function() { +{ fs.writeFileSync(filename, '0123456789'); - assert.equal(fs.readFileSync(filename).toString(), '0123456789'); + assert.strictEqual(fs.readFileSync(filename).toString(), '0123456789'); fs.truncate(filename, 5, common.mustCall(function(err) { - if (err) throw err; - assert.equal(fs.readFileSync(filename).toString(), '01234'); + assert.ifError(err); + assert.strictEqual(fs.readFileSync(filename).toString(), '01234'); })); -})(); +} diff --git a/test/parallel/test-fs-write-stream-end.js b/test/parallel/test-fs-write-stream-end.js index a8af29d1327672..ade6777d5f68ac 100644 --- a/test/parallel/test-fs-write-stream-end.js +++ b/test/parallel/test-fs-write-stream-end.js @@ -6,19 +6,19 @@ var fs = require('fs'); common.refreshTmpDir(); -(function() { - var file = path.join(common.tmpDir, 'write-end-test0.txt'); - var stream = fs.createWriteStream(file); +{ + const file = path.join(common.tmpDir, 'write-end-test0.txt'); + const stream = fs.createWriteStream(file); stream.end(); stream.on('close', common.mustCall(function() { })); -})(); +} -(function() { - var file = path.join(common.tmpDir, 'write-end-test1.txt'); - var stream = fs.createWriteStream(file); +{ + const file = path.join(common.tmpDir, 'write-end-test1.txt'); + const stream = fs.createWriteStream(file); stream.end('a\n', 'utf8'); stream.on('close', common.mustCall(function() { - var content = fs.readFileSync(file, 'utf8'); - assert.equal(content, 'a\n'); + const content = fs.readFileSync(file, 'utf8'); + assert.strictEqual(content, 'a\n'); })); -})(); +} diff --git a/test/parallel/test-fs-write-stream.js b/test/parallel/test-fs-write-stream.js index 5d29e60545f434..71aaaa75dd5845 100644 --- a/test/parallel/test-fs-write-stream.js +++ b/test/parallel/test-fs-write-stream.js @@ -8,7 +8,7 @@ var file = path.join(common.tmpDir, 'write.txt'); common.refreshTmpDir(); -(function() { +{ const stream = fs.WriteStream(file); const _fs_close = fs.close; @@ -17,15 +17,14 @@ common.refreshTmpDir(); fs.close = _fs_close; }; stream.destroy(); -})(); +} -(function() { - var stream = fs.createWriteStream(file); +{ + const stream = fs.createWriteStream(file); stream.on('drain', function() { - assert.fail(null, null, '\'drain\' event must not be emitted before ' + + common.fail('\'drain\' event must not be emitted before ' + 'stream.write() has been called at least once.'); }); stream.destroy(); -})(); - +} diff --git a/test/parallel/test-http-1.0.js b/test/parallel/test-http-1.0.js index 622dd4a16f1516..d01613de45452d 100644 --- a/test/parallel/test-http-1.0.js +++ b/test/parallel/test-http-1.0.js @@ -35,11 +35,11 @@ function test(handler, request_generator, response_validator) { }); } -(function() { +{ function handler(req, res) { - assert.equal('1.0', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(0, req.httpVersionMinor); + assert.strictEqual('1.0', req.httpVersion); + assert.strictEqual(1, req.httpVersionMajor); + assert.strictEqual(0, req.httpVersionMinor); res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(body); } @@ -49,25 +49,25 @@ function test(handler, request_generator, response_validator) { } function response_validator(server_response, client_got_eof, timed_out) { - var m = server_response.split('\r\n\r\n'); - assert.equal(m[1], body); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); + const m = server_response.split('\r\n\r\n'); + assert.strictEqual(m[1], body); + assert.strictEqual(true, client_got_eof); + assert.strictEqual(false, timed_out); } test(handler, request_generator, response_validator); -})(); +} // // Don't send HTTP/1.1 status lines to HTTP/1.0 clients. // // https://github.com/joyent/node/issues/1234 // -(function() { +{ function handler(req, res) { - assert.equal('1.0', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(0, req.httpVersionMinor); + assert.strictEqual('1.0', req.httpVersion); + assert.strictEqual(1, req.httpVersionMajor); + assert.strictEqual(0, req.httpVersionMinor); res.sendDate = false; res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello, '); res._send(''); @@ -85,25 +85,25 @@ function test(handler, request_generator, response_validator) { } function response_validator(server_response, client_got_eof, timed_out) { - var expected_response = 'HTTP/1.1 200 OK\r\n' + - 'Content-Type: text/plain\r\n' + - 'Connection: close\r\n' + - '\r\n' + - 'Hello, world!'; - - assert.equal(expected_response, server_response); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); + const expected_response = 'HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/plain\r\n' + + 'Connection: close\r\n' + + '\r\n' + + 'Hello, world!'; + + assert.strictEqual(expected_response, server_response); + assert.strictEqual(true, client_got_eof); + assert.strictEqual(false, timed_out); } test(handler, request_generator, response_validator); -})(); +} -(function() { +{ function handler(req, res) { - assert.equal('1.1', req.httpVersion); - assert.equal(1, req.httpVersionMajor); - assert.equal(1, req.httpVersionMinor); + assert.strictEqual('1.1', req.httpVersion); + assert.strictEqual(1, req.httpVersionMajor); + assert.strictEqual(1, req.httpVersionMinor); res.sendDate = false; res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('Hello, '); res._send(''); @@ -112,32 +112,32 @@ function test(handler, request_generator, response_validator) { } function request_generator() { - return ('GET / HTTP/1.1\r\n' + + return 'GET / HTTP/1.1\r\n' + 'User-Agent: curl/7.19.7 (x86_64-pc-linux-gnu) libcurl/7.19.7 ' + 'OpenSSL/0.9.8k zlib/1.2.3.3 libidn/1.15\r\n' + 'Connection: close\r\n' + 'Host: 127.0.0.1:1337\r\n' + 'Accept: */*\r\n' + - '\r\n'); + '\r\n'; } function response_validator(server_response, client_got_eof, timed_out) { - var expected_response = 'HTTP/1.1 200 OK\r\n' + - 'Content-Type: text/plain\r\n' + - 'Connection: close\r\n' + - 'Transfer-Encoding: chunked\r\n' + - '\r\n' + - '7\r\n' + - 'Hello, \r\n' + - '6\r\n' + - 'world!\r\n' + - '0\r\n' + - '\r\n'; - - assert.equal(expected_response, server_response); - assert.equal(true, client_got_eof); - assert.equal(false, timed_out); + const expected_response = 'HTTP/1.1 200 OK\r\n' + + 'Content-Type: text/plain\r\n' + + 'Connection: close\r\n' + + 'Transfer-Encoding: chunked\r\n' + + '\r\n' + + '7\r\n' + + 'Hello, \r\n' + + '6\r\n' + + 'world!\r\n' + + '0\r\n' + + '\r\n'; + + assert.strictEqual(expected_response, server_response); + assert.strictEqual(true, client_got_eof); + assert.strictEqual(false, timed_out); } test(handler, request_generator, response_validator); -})(); +} diff --git a/test/parallel/test-http-parser.js b/test/parallel/test-http-parser.js index 360dc6ccc982dd..abc1d096dff0d8 100644 --- a/test/parallel/test-http-parser.js +++ b/test/parallel/test-http-parser.js @@ -72,21 +72,21 @@ function expectBody(expected) { // // Simple request test. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'GET /hello HTTP/1.1' + CRLF + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); - assert.equal(method, methods.indexOf('GET')); - assert.equal(url || parser.url, '/hello'); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); + assert.strictEqual(method, methods.indexOf('GET')); + assert.strictEqual(url || parser.url, '/hello'); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser.execute(request, 0, request.length); @@ -104,72 +104,72 @@ function expectBody(expected) { assert.throws(function() { parser.execute(request, 0, request.length); }, Error, 'hello world'); -})(); +} // // Simple response test. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'HTTP/1.1 200 OK' + CRLF + 'Content-Type: text/plain' + CRLF + 'Content-Length: 4' + CRLF + CRLF + 'pong'); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, undefined); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); - assert.equal(statusCode, 200); - assert.equal(statusMessage, 'OK'); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, undefined); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); + assert.strictEqual(statusCode, 200); + assert.strictEqual(statusMessage, 'OK'); }; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'pong'); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, 'pong'); }; - var parser = newParser(RESPONSE); + const parser = newParser(RESPONSE); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody); parser.execute(request, 0, request.length); -})(); +} // // Response with no headers. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'HTTP/1.0 200 Connection established' + CRLF + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 0); - assert.equal(method, undefined); - assert.equal(statusCode, 200); - assert.equal(statusMessage, 'Connection established'); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 0); + assert.strictEqual(method, undefined); + assert.strictEqual(statusCode, 200); + assert.strictEqual(statusMessage, 'Connection established'); assert.deepStrictEqual(headers || parser.headers, []); }; - var parser = newParser(RESPONSE); + const parser = newParser(RESPONSE); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser.execute(request, 0, request.length); -})(); +} // // Trailing headers. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Transfer-Encoding: chunked' + CRLF + CRLF + @@ -180,139 +180,139 @@ function expectBody(expected) { 'Content-Type: text/plain' + CRLF + CRLF); - var seen_body = false; + let seen_body = false; - var onHeaders = function(headers, url) { + const onHeaders = function(headers, url) { assert.ok(seen_body); // trailers should come after the body assert.deepStrictEqual(headers, ['Vary', '*', 'Content-Type', 'text/plain']); }; - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); // expect to see trailing headers now parser[kOnHeaders] = mustCall(onHeaders); }; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'ping'); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, 'ping'); seen_body = true; }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody); parser.execute(request, 0, request.length); -})(); +} // // Test header ordering. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'GET / HTTP/1.0' + CRLF + 'X-Filler: 1337' + CRLF + 'X-Filler: 42' + CRLF + 'X-Filler2: 42' + CRLF + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('GET')); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 0); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('GET')); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 0); assert.deepStrictEqual( headers || parser.headers, ['X-Filler', '1337', 'X-Filler', '42', 'X-Filler2', '42']); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser.execute(request, 0, request.length); -})(); +} // // Test large number of headers // -(function() { +{ // 256 X-Filler headers - var lots_of_headers = 'X-Filler: 42' + CRLF; + let lots_of_headers = 'X-Filler: 42' + CRLF; lots_of_headers = lots_of_headers.repeat(256); - var request = Buffer.from( + const request = Buffer.from( 'GET /foo/bar/baz?quux=42#1337 HTTP/1.0' + CRLF + lots_of_headers + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('GET')); - assert.equal(url || parser.url, '/foo/bar/baz?quux=42#1337'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 0); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('GET')); + assert.strictEqual(url || parser.url, '/foo/bar/baz?quux=42#1337'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 0); headers = headers || parser.headers; - assert.equal(headers.length, 2 * 256); // 256 key/value pairs - for (var i = 0; i < headers.length; i += 2) { - assert.equal(headers[i], 'X-Filler'); - assert.equal(headers[i + 1], '42'); + assert.strictEqual(headers.length, 2 * 256); // 256 key/value pairs + for (let i = 0; i < headers.length; i += 2) { + assert.strictEqual(headers[i], 'X-Filler'); + assert.strictEqual(headers[i + 1], '42'); } }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser.execute(request, 0, request.length); -})(); +} // // Test request body // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: application/x-www-form-urlencoded' + CRLF + 'Content-Length: 15' + CRLF + CRLF + 'foo=42&bar=1337'); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); }; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, 'foo=42&bar=1337'); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, 'foo=42&bar=1337'); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody); parser.execute(request, 0, request.length); -})(); +} // // Test chunked request body // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -325,35 +325,35 @@ function expectBody(expected) { '1234567890' + CRLF + '0' + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); }; let body_part = 0; const body_parts = ['123', '123456', '1234567890']; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, body_parts[body_part++]); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, body_parts[body_part++]); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody, body_parts.length); parser.execute(request, 0, request.length); -})(); +} // // Test chunked request body spread over multiple buffers (packets) // -(function() { - var request = Buffer.from( +{ + let request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -363,25 +363,25 @@ function expectBody(expected) { '6' + CRLF + '123456' + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); }; let body_part = 0; const body_parts = ['123', '123456', '123456789', '123456789ABC', '123456789ABCDEF']; - var onBody = function(buf, start, len) { - var body = '' + buf.slice(start, start + len); - assert.equal(body, body_parts[body_part++]); + const onBody = function(buf, start, len) { + const body = '' + buf.slice(start, start + len); + assert.strictEqual(body, body_parts[body_part++]); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = mustCall(onBody, body_parts.length); parser.execute(request, 0, request.length); @@ -396,14 +396,14 @@ function expectBody(expected) { '0' + CRLF); parser.execute(request, 0, request.length); -})(); +} // // Stress test. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /helpme HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -421,30 +421,30 @@ function expectBody(expected) { '0' + CRLF); function test(a, b) { - var onHeadersComplete = function(versionMajor, versionMinor, headers, - method, url, statusCode, statusMessage, - upgrade, shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/helpme'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/helpme'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); }; - var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; + let expected_body = '123123456123456789123456789ABC123456789ABCDEF'; - var onBody = function(buf, start, len) { - var chunk = '' + buf.slice(start, start + len); - assert.equal(expected_body.indexOf(chunk), 0); + const onBody = function(buf, start, len) { + const chunk = '' + buf.slice(start, start + len); + assert.strictEqual(expected_body.indexOf(chunk), 0); expected_body = expected_body.slice(chunk.length); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = onBody; parser.execute(a, 0, a.length); parser.execute(b, 0, b.length); - assert.equal(expected_body, ''); + assert.strictEqual(expected_body, ''); } for (var i = 1; i < request.length - 1; ++i) { @@ -456,14 +456,14 @@ function expectBody(expected) { JSON.stringify(b.toString())); test(a, b); } -})(); +} // // Byte by byte test. // -(function() { - var request = Buffer.from( +{ + const request = Buffer.from( 'POST /it HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -480,43 +480,43 @@ function expectBody(expected) { '123456789ABCDEF' + CRLF + '0' + CRLF); - var onHeadersComplete = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url || parser.url, '/it'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 1); + const onHeadersComplete = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url || parser.url, '/it'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 1); assert.deepStrictEqual( headers || parser.headers, ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); }; - var expected_body = '123123456123456789123456789ABC123456789ABCDEF'; + let expected_body = '123123456123456789123456789ABC123456789ABCDEF'; - var onBody = function(buf, start, len) { - var chunk = '' + buf.slice(start, start + len); - assert.equal(expected_body.indexOf(chunk), 0); + const onBody = function(buf, start, len) { + const chunk = '' + buf.slice(start, start + len); + assert.strictEqual(expected_body.indexOf(chunk), 0); expected_body = expected_body.slice(chunk.length); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = mustCall(onHeadersComplete); parser[kOnBody] = onBody; - for (var i = 0; i < request.length; ++i) { + for (let i = 0; i < request.length; ++i) { parser.execute(request, i, 1); } - assert.equal(expected_body, ''); -})(); + assert.strictEqual(expected_body, ''); +} // // Test parser reinit sequence. // -(function() { - var req1 = Buffer.from( +{ + const req1 = Buffer.from( 'PUT /this HTTP/1.1' + CRLF + 'Content-Type: text/plain' + CRLF + 'Transfer-Encoding: chunked' + CRLF + @@ -525,16 +525,16 @@ function expectBody(expected) { 'ping' + CRLF + '0' + CRLF); - var req2 = Buffer.from( + const req2 = Buffer.from( 'POST /that HTTP/1.0' + CRLF + 'Content-Type: text/plain' + CRLF + 'Content-Length: 4' + CRLF + CRLF + 'pong'); - var onHeadersComplete1 = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { + const onHeadersComplete1 = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { assert.equal(method, methods.indexOf('PUT')); assert.equal(url, '/this'); assert.equal(versionMajor, 1); @@ -544,20 +544,20 @@ function expectBody(expected) { ['Content-Type', 'text/plain', 'Transfer-Encoding', 'chunked']); }; - var onHeadersComplete2 = function(versionMajor, versionMinor, headers, method, - url, statusCode, statusMessage, upgrade, - shouldKeepAlive) { - assert.equal(method, methods.indexOf('POST')); - assert.equal(url, '/that'); - assert.equal(versionMajor, 1); - assert.equal(versionMinor, 0); + const onHeadersComplete2 = function(versionMajor, versionMinor, headers, + method, url, statusCode, statusMessage, + upgrade, shouldKeepAlive) { + assert.strictEqual(method, methods.indexOf('POST')); + assert.strictEqual(url, '/that'); + assert.strictEqual(versionMajor, 1); + assert.strictEqual(versionMinor, 0); assert.deepStrictEqual( headers, ['Content-Type', 'text/plain', 'Content-Length', '4'] ); }; - var parser = newParser(REQUEST); + const parser = newParser(REQUEST); parser[kOnHeadersComplete] = onHeadersComplete1; parser[kOnBody] = expectBody('ping'); parser.execute(req1, 0, req1.length); @@ -566,7 +566,7 @@ function expectBody(expected) { parser[kOnBody] = expectBody('pong'); parser[kOnHeadersComplete] = onHeadersComplete2; parser.execute(req2, 0, req2.length); -})(); +} // Test parser 'this' safety // https://github.com/joyent/node/issues/6690 diff --git a/test/parallel/test-querystring.js b/test/parallel/test-querystring.js index 5d52fe6544a1a8..37cf66705d56d7 100644 --- a/test/parallel/test-querystring.js +++ b/test/parallel/test-querystring.js @@ -134,7 +134,7 @@ qsNoMungeTestCases.forEach(function(testCase) { }); // test the nested qs-in-qs case -(function() { +{ const f = qs.parse('a=b&q=x%3Dy%26y%3Dz'); check(f, createWithNoPrototype([ { key: 'a', value: 'b'}, @@ -147,10 +147,10 @@ qsNoMungeTestCases.forEach(function(testCase) { {key: 'y', value: 'z' } ]); check(f.q, expectedInternal); -})(); +} // nested in colon -(function() { +{ const f = qs.parse('a:b;q:x%3Ay%3By%3Az', ';', ':'); check(f, createWithNoPrototype([ {key: 'a', value: 'b'}, @@ -162,7 +162,7 @@ qsNoMungeTestCases.forEach(function(testCase) { {key: 'y', value: 'z' } ]); check(f.q, expectedInternal); -})(); +} // now test stringifying diff --git a/test/parallel/test-require-cache.js b/test/parallel/test-require-cache.js index 7ea68dd0515799..247590197d6126 100644 --- a/test/parallel/test-require-cache.js +++ b/test/parallel/test-require-cache.js @@ -2,22 +2,22 @@ require('../common'); var assert = require('assert'); -(function testInjectFakeModule() { - var relativePath = '../fixtures/semicolon'; - var absolutePath = require.resolve(relativePath); - var fakeModule = {}; +{ + const relativePath = '../fixtures/semicolon'; + const absolutePath = require.resolve(relativePath); + const fakeModule = {}; require.cache[absolutePath] = {exports: fakeModule}; assert.strictEqual(require(relativePath), fakeModule); -})(); +} -(function testInjectFakeNativeModule() { - var relativePath = 'fs'; - var fakeModule = {}; +{ + const relativePath = 'fs'; + const fakeModule = {}; require.cache[relativePath] = {exports: fakeModule}; assert.strictEqual(require(relativePath), fakeModule); -})(); +} diff --git a/test/parallel/test-stream-pipe-error-handling.js b/test/parallel/test-stream-pipe-error-handling.js index 88a70fb58e2cf1..b2c25cfe8c6e22 100644 --- a/test/parallel/test-stream-pipe-error-handling.js +++ b/test/parallel/test-stream-pipe-error-handling.js @@ -1,33 +1,33 @@ 'use strict'; -require('../common'); -var assert = require('assert'); -var Stream = require('stream').Stream; +const common = require('../common'); +const assert = require('assert'); +const Stream = require('stream').Stream; -(function testErrorListenerCatches() { - var source = new Stream(); - var dest = new Stream(); +{ + const source = new Stream(); + const dest = new Stream(); source.pipe(dest); - var gotErr = null; + let gotErr = null; source.on('error', function(err) { gotErr = err; }); - var err = new Error('This stream turned into bacon.'); + const err = new Error('This stream turned into bacon.'); source.emit('error', err); assert.strictEqual(gotErr, err); -})(); +} -(function testErrorWithoutListenerThrows() { - var source = new Stream(); - var dest = new Stream(); +{ + const source = new Stream(); + const dest = new Stream(); source.pipe(dest); - var err = new Error('This stream turned into bacon.'); + const err = new Error('This stream turned into bacon.'); - var gotErr = null; + let gotErr = null; try { source.emit('error', err); } catch (e) { @@ -35,30 +35,23 @@ var Stream = require('stream').Stream; } assert.strictEqual(gotErr, err); -})(); +} -(function testErrorWithRemovedListenerThrows() { - var R = Stream.Readable; - var W = Stream.Writable; +{ + const R = Stream.Readable; + const W = Stream.Writable; - var r = new R(); - var w = new W(); - var removed = false; - var didTest = false; - - process.on('exit', function() { - assert(didTest); - console.log('ok'); - }); + const r = new R(); + const w = new W(); + let removed = false; r._read = function() { - setTimeout(function() { + setTimeout(common.mustCall(function() { assert(removed); assert.throws(function() { w.emit('error', new Error('fail')); }); - didTest = true; - }); + })); }; w.on('error', myOnError); @@ -69,41 +62,28 @@ var Stream = require('stream').Stream; function myOnError(er) { throw new Error('this should not happen'); } -})(); +} -(function testErrorWithRemovedListenerThrows() { - var R = Stream.Readable; - var W = Stream.Writable; +{ + const R = Stream.Readable; + const W = Stream.Writable; - var r = new R(); - var w = new W(); - var removed = false; - var didTest = false; - var caught = false; - - process.on('exit', function() { - assert(didTest); - console.log('ok'); - }); + const r = new R(); + const w = new W(); + let removed = false; r._read = function() { - setTimeout(function() { + setTimeout(common.mustCall(function() { assert(removed); w.emit('error', new Error('fail')); - didTest = true; - }); + })); }; - w.on('error', myOnError); + w.on('error', common.mustCall(function(er) {})); w._write = function() {}; r.pipe(w); // Removing some OTHER random listener should not do anything w.removeListener('error', function() {}); removed = true; - - function myOnError(er) { - assert(!caught); - caught = true; - } -})(); +} diff --git a/test/parallel/test-stream-readable-event.js b/test/parallel/test-stream-readable-event.js index 957f4097818bfc..a20fc2ee732d0f 100644 --- a/test/parallel/test-stream-readable-event.js +++ b/test/parallel/test-stream-readable-event.js @@ -1,106 +1,64 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); -var Readable = require('stream').Readable; +const Readable = require('stream').Readable; -(function first() { +{ // First test, not reading when the readable is added. // make sure that on('readable', ...) triggers a readable event. - var r = new Readable({ + const r = new Readable({ highWaterMark: 3 }); - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; + r._read = common.fail; // This triggers a 'readable' event, which is lost. r.push(Buffer.from('blerg')); - var caughtReadable = false; setTimeout(function() { // we're testing what we think we are assert(!r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); + r.on('readable', common.mustCall(function() {})); }); +} - process.on('exit', function() { - // we're testing what we think we are - assert(!_readCalled); - - assert(caughtReadable); - console.log('ok 1'); - }); -})(); - -(function second() { +{ // second test, make sure that readable is re-emitted if there's // already a length, while it IS reading. - var r = new Readable({ + const r = new Readable({ highWaterMark: 3 }); - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; + r._read = common.mustCall(function(n) {}); // This triggers a 'readable' event, which is lost. r.push(Buffer.from('bl')); - var caughtReadable = false; setTimeout(function() { // assert we're testing what we think we are assert(r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); - }); - - process.on('exit', function() { - // we're testing what we think we are - assert(_readCalled); - - assert(caughtReadable); - console.log('ok 2'); + r.on('readable', common.mustCall(function() {})); }); -})(); +} -(function third() { +{ // Third test, not reading when the stream has not passed // the highWaterMark but *has* reached EOF. - var r = new Readable({ + const r = new Readable({ highWaterMark: 30 }); - var _readCalled = false; - r._read = function(n) { - _readCalled = true; - }; + r._read = common.fail; // This triggers a 'readable' event, which is lost. r.push(Buffer.from('blerg')); r.push(null); - var caughtReadable = false; setTimeout(function() { // assert we're testing what we think we are assert(!r._readableState.reading); - r.on('readable', function() { - caughtReadable = true; - }); - }); - - process.on('exit', function() { - // we're testing what we think we are - assert(!_readCalled); - - assert(caughtReadable); - console.log('ok 3'); + r.on('readable', common.mustCall(function() {})); }); -})(); +} diff --git a/test/parallel/test-stream-writable-decoded-encoding.js b/test/parallel/test-stream-writable-decoded-encoding.js index 75d5d424766323..621e342a3c2d74 100644 --- a/test/parallel/test-stream-writable-decoded-encoding.js +++ b/test/parallel/test-stream-writable-decoded-encoding.js @@ -17,24 +17,22 @@ MyWritable.prototype._write = function(chunk, encoding, callback) { callback(); }; -(function decodeStringsTrue() { - var m = new MyWritable(function(isBuffer, type, enc) { +{ + const m = new MyWritable(function(isBuffer, type, enc) { assert(isBuffer); - assert.equal(type, 'object'); - assert.equal(enc, 'buffer'); - console.log('ok - decoded string is decoded'); + assert.strictEqual(type, 'object'); + assert.strictEqual(enc, 'buffer'); }, { decodeStrings: true }); m.write('some-text', 'utf8'); m.end(); -})(); +} -(function decodeStringsFalse() { - var m = new MyWritable(function(isBuffer, type, enc) { +{ + const m = new MyWritable(function(isBuffer, type, enc) { assert(!isBuffer); - assert.equal(type, 'string'); - assert.equal(enc, 'utf8'); - console.log('ok - un-decoded string is not decoded'); + assert.strictEqual(type, 'string'); + assert.strictEqual(enc, 'utf8'); }, { decodeStrings: false }); m.write('some-text', 'utf8'); m.end(); -})(); +} diff --git a/test/parallel/test-stream2-pipe-error-handling.js b/test/parallel/test-stream2-pipe-error-handling.js index 65397566c23ca2..bdf7a4a9a33a77 100644 --- a/test/parallel/test-stream2-pipe-error-handling.js +++ b/test/parallel/test-stream2-pipe-error-handling.js @@ -3,77 +3,77 @@ require('../common'); var assert = require('assert'); var stream = require('stream'); -(function testErrorListenerCatches() { - var count = 1000; +{ + let count = 1000; - var source = new stream.Readable(); + const source = new stream.Readable(); source._read = function(n) { n = Math.min(count, n); count -= n; source.push(Buffer.allocUnsafe(n)); }; - var unpipedDest; + let unpipedDest; source.unpipe = function(dest) { unpipedDest = dest; stream.Readable.prototype.unpipe.call(this, dest); }; - var dest = new stream.Writable(); + const dest = new stream.Writable(); dest._write = function(chunk, encoding, cb) { cb(); }; source.pipe(dest); - var gotErr = null; + let gotErr = null; dest.on('error', function(err) { gotErr = err; }); - var unpipedSource; + let unpipedSource; dest.on('unpipe', function(src) { unpipedSource = src; }); - var err = new Error('This stream turned into bacon.'); + const err = new Error('This stream turned into bacon.'); dest.emit('error', err); assert.strictEqual(gotErr, err); assert.strictEqual(unpipedSource, source); assert.strictEqual(unpipedDest, dest); -})(); +} -(function testErrorWithoutListenerThrows() { - var count = 1000; +{ + let count = 1000; - var source = new stream.Readable(); + const source = new stream.Readable(); source._read = function(n) { n = Math.min(count, n); count -= n; source.push(Buffer.allocUnsafe(n)); }; - var unpipedDest; + let unpipedDest; source.unpipe = function(dest) { unpipedDest = dest; stream.Readable.prototype.unpipe.call(this, dest); }; - var dest = new stream.Writable(); + const dest = new stream.Writable(); dest._write = function(chunk, encoding, cb) { cb(); }; source.pipe(dest); - var unpipedSource; + let unpipedSource; dest.on('unpipe', function(src) { unpipedSource = src; }); - var err = new Error('This stream turned into bacon.'); + const err = new Error('This stream turned into bacon.'); - var gotErr = null; + let gotErr = null; try { dest.emit('error', err); } catch (e) { @@ -82,4 +82,4 @@ var stream = require('stream'); assert.strictEqual(gotErr, err); assert.strictEqual(unpipedSource, source); assert.strictEqual(unpipedDest, dest); -})(); +} diff --git a/test/parallel/test-stringbytes-external.js b/test/parallel/test-stringbytes-external.js index 68332232171ab4..8372321991dc53 100644 --- a/test/parallel/test-stringbytes-external.js +++ b/test/parallel/test-stringbytes-external.js @@ -53,57 +53,57 @@ var RADIOS = 2; var PRE_HALF_APEX = Math.ceil(EXTERN_APEX / 2) - RADIOS; var PRE_3OF4_APEX = Math.ceil((EXTERN_APEX / 4) * 3) - RADIOS; -(function() { - for (var j = 0; j < RADIOS * 2; j += 1) { - var datum = b; - var slice = datum.slice(0, PRE_HALF_APEX + j); - var slice2 = datum.slice(0, PRE_HALF_APEX + j + 2); - var pumped_string = slice.toString('hex'); - var pumped_string2 = slice2.toString('hex'); - var decoded = Buffer.from(pumped_string, 'hex'); +{ + for (let j = 0; j < RADIOS * 2; j += 1) { + const datum = b; + const slice = datum.slice(0, PRE_HALF_APEX + j); + const slice2 = datum.slice(0, PRE_HALF_APEX + j + 2); + const pumped_string = slice.toString('hex'); + const pumped_string2 = slice2.toString('hex'); + const decoded = Buffer.from(pumped_string, 'hex'); // the string are the same? - for (var k = 0; k < pumped_string.length; ++k) { - assert.equal(pumped_string[k], pumped_string2[k]); + for (let k = 0; k < pumped_string.length; ++k) { + assert.strictEqual(pumped_string[k], pumped_string2[k]); } // the recoded buffer is the same? - for (var i = 0; i < decoded.length; ++i) { - assert.equal(datum[i], decoded[i]); + for (let i = 0; i < decoded.length; ++i) { + assert.strictEqual(datum[i], decoded[i]); } } -})(); +} -(function() { - for (var j = 0; j < RADIOS * 2; j += 1) { - var datum = b; - var slice = datum.slice(0, PRE_3OF4_APEX + j); - var slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2); - var pumped_string = slice.toString('base64'); - var pumped_string2 = slice2.toString('base64'); - var decoded = Buffer.from(pumped_string, 'base64'); +{ + for (let j = 0; j < RADIOS * 2; j += 1) { + const datum = b; + const slice = datum.slice(0, PRE_3OF4_APEX + j); + const slice2 = datum.slice(0, PRE_3OF4_APEX + j + 2); + const pumped_string = slice.toString('base64'); + const pumped_string2 = slice2.toString('base64'); + const decoded = Buffer.from(pumped_string, 'base64'); // the string are the same? - for (var k = 0; k < pumped_string.length - 3; ++k) { - assert.equal(pumped_string[k], pumped_string2[k]); + for (let k = 0; k < pumped_string.length - 3; ++k) { + assert.strictEqual(pumped_string[k], pumped_string2[k]); } // the recoded buffer is the same? - for (var i = 0; i < decoded.length; ++i) { - assert.equal(datum[i], decoded[i]); + for (let i = 0; i < decoded.length; ++i) { + assert.strictEqual(datum[i], decoded[i]); } } -})(); +} // https://github.com/nodejs/node/issues/1024 -(function() { - var a = Array(1 << 20).join('x'); - var b = Buffer.from(a, 'ucs2').toString('ucs2'); - var c = Buffer.from(b, 'utf8').toString('utf8'); +{ + const a = Array(1 << 20).join('x'); + const b = Buffer.from(a, 'ucs2').toString('ucs2'); + const c = Buffer.from(b, 'utf8').toString('utf8'); - assert.equal(a.length, b.length); - assert.equal(b.length, c.length); + assert.strictEqual(a.length, b.length); + assert.strictEqual(b.length, c.length); - assert.equal(a, b); - assert.equal(b, c); -})(); + assert.strictEqual(a, b); + assert.strictEqual(b, c); +} diff --git a/test/parallel/test-timers-unref.js b/test/parallel/test-timers-unref.js index 570c51b9ac7a5f..801b34792a1f73 100644 --- a/test/parallel/test-timers-unref.js +++ b/test/parallel/test-timers-unref.js @@ -55,11 +55,11 @@ setInterval(function() { }, SHORT_TIME); // Should not assert on args.Holder()->InternalFieldCount() > 0. See #4261. -(function() { - var t = setInterval(function() {}, 1); +{ + const t = setInterval(function() {}, 1); process.nextTick(t.unref.bind({})); process.nextTick(t.unref.bind(t)); -})(); +} process.on('exit', function() { assert.strictEqual(interval_fired, false, diff --git a/test/parallel/test-timers-zero-timeout.js b/test/parallel/test-timers-zero-timeout.js index ab0c38f6084277..00e75b7ea8fa24 100644 --- a/test/parallel/test-timers-zero-timeout.js +++ b/test/parallel/test-timers-zero-timeout.js @@ -1,39 +1,32 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); +const assert = require('assert'); // https://github.com/joyent/node/issues/2079 - zero timeout drops extra args -(function() { - var ncalled = 0; - - setTimeout(f, 0, 'foo', 'bar', 'baz'); +{ + setTimeout(common.mustCall(f), 0, 'foo', 'bar', 'baz'); setTimeout(function() {}, 0); function f(a, b, c) { - assert.equal(a, 'foo'); - assert.equal(b, 'bar'); - assert.equal(c, 'baz'); - ncalled++; + assert.strictEqual(a, 'foo'); + assert.strictEqual(b, 'bar'); + assert.strictEqual(c, 'baz'); } +} - process.on('exit', function() { - assert.equal(ncalled, 1); - }); -})(); - -(function() { - var ncalled = 0; +{ + let ncalled = 0; - var iv = setInterval(f, 0, 'foo', 'bar', 'baz'); + const iv = setInterval(f, 0, 'foo', 'bar', 'baz'); function f(a, b, c) { - assert.equal(a, 'foo'); - assert.equal(b, 'bar'); - assert.equal(c, 'baz'); + assert.strictEqual(a, 'foo'); + assert.strictEqual(b, 'bar'); + assert.strictEqual(c, 'baz'); if (++ncalled == 3) clearTimeout(iv); } process.on('exit', function() { - assert.equal(ncalled, 3); + assert.strictEqual(ncalled, 3); }); -})(); +} diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index 3853ea66bc80f4..96de1b0ad6fe42 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -13,37 +13,38 @@ var path = require('path'); // https://github.com/joyent/node/issues/1218 // uncatchable exception on TLS connection error -(function() { - var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); - var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); +{ + const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); + const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - var errorEmitted = false; + let errorEmitted = false; process.on('exit', function() { assert.ok(errorEmitted); }); - var conn = tls.connect({cert: cert, key: key, port: common.PORT}, function() { + const options = {cert: cert, key: key, port: common.PORT}; + const conn = tls.connect(options, function() { assert.ok(false); // callback should never be executed }); conn.on('error', function() { errorEmitted = true; }); -})(); +} // SSL_accept/SSL_connect error handling -(function() { - var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); - var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); +{ + const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); + const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - var errorEmitted = false; + let errorEmitted = false; process.on('exit', function() { assert.ok(errorEmitted); }); - var conn = tls.connect({ + const conn = tls.connect({ cert: cert, key: key, port: common.PORT, @@ -55,4 +56,4 @@ var path = require('path'); conn.on('error', function() { errorEmitted = true; }); -})(); +} diff --git a/test/parallel/test-util-format.js b/test/parallel/test-util-format.js index 92c448578bec1f..f3702ef2f05547 100644 --- a/test/parallel/test-util-format.js +++ b/test/parallel/test-util-format.js @@ -48,11 +48,11 @@ assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz'); assert.equal(util.format('%%%s%%', 'hi'), '%hi%'); assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%'); -(function() { - var o = {}; +{ + const o = {}; o.o = o; assert.equal(util.format('%j', o), '[Circular]'); -})(); +} // Errors const err = new Error('foo'); diff --git a/test/parallel/test-vm-debug-context.js b/test/parallel/test-vm-debug-context.js index 07335fad56a1f7..9b8da58756c8d3 100644 --- a/test/parallel/test-vm-debug-context.js +++ b/test/parallel/test-vm-debug-context.js @@ -31,9 +31,9 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined); // See https://github.com/nodejs/node/issues/1190, accessing named interceptors // and accessors inside a debug event listener should not crash. -(function() { - var Debug = vm.runInDebugContext('Debug'); - var breaks = 0; +{ + const Debug = vm.runInDebugContext('Debug'); + let breaks = 0; function ondebugevent(evt, exc) { if (evt !== Debug.DebugEvent.Break) return; @@ -51,10 +51,10 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined); assert.equal(breaks, 0); breakpoint(); assert.equal(breaks, 1); -})(); +} // Can set listeners and breakpoints on a single line file -(function() { +{ const Debug = vm.runInDebugContext('Debug'); const fn = require(common.fixturesDir + '/exports-function-with-param'); let called = false; @@ -69,7 +69,7 @@ assert.strictEqual(vm.runInDebugContext(undefined), undefined); fn('foo'); assert.strictEqual(Debug.showBreakPoints(fn), '(arg) { [B0]return arg; }'); assert.strictEqual(called, true); -})(); +} // See https://github.com/nodejs/node/issues/1190, fatal errors should not // crash the process. diff --git a/test/parallel/test-zlib-dictionary-fail.js b/test/parallel/test-zlib-dictionary-fail.js index 2c8939c68fac21..21c94b2c41015b 100644 --- a/test/parallel/test-zlib-dictionary-fail.js +++ b/test/parallel/test-zlib-dictionary-fail.js @@ -4,8 +4,8 @@ var assert = require('assert'); var zlib = require('zlib'); // Should raise an error, not trigger an assertion in src/node_zlib.cc -(function() { - var stream = zlib.createInflate(); +{ + const stream = zlib.createInflate(); stream.on('error', common.mustCall(function(err) { assert(/Missing dictionary/.test(err.message)); @@ -13,11 +13,11 @@ var zlib = require('zlib'); // String "test" encoded with dictionary "dict". stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); -})(); +} // Should raise an error, not trigger an assertion in src/node_zlib.cc -(function() { - var stream = zlib.createInflate({ dictionary: Buffer.from('fail') }); +{ + const stream = zlib.createInflate({ dictionary: Buffer.from('fail') }); stream.on('error', common.mustCall(function(err) { assert(/Bad dictionary/.test(err.message)); @@ -25,4 +25,4 @@ var zlib = require('zlib'); // String "test" encoded with dictionary "dict". stream.write(Buffer.from([0x78, 0xBB, 0x04, 0x09, 0x01, 0xA5])); -})(); +} diff --git a/test/pummel/test-https-ci-reneg-attack.js b/test/pummel/test-https-ci-reneg-attack.js index 701963606e6d80..8bda7cc10286e9 100644 --- a/test/pummel/test-https-ci-reneg-attack.js +++ b/test/pummel/test-https-ci-reneg-attack.js @@ -20,15 +20,15 @@ if (!common.opensslCli) { // renegotiation limits to test var LIMITS = [0, 1, 2, 3, 5, 10, 16]; -(function() { - var n = 0; +{ + let n = 0; function next() { if (n >= LIMITS.length) return; tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; test(next); } next(); -})(); +} function test(next) { var options = { diff --git a/test/pummel/test-net-connect-memleak.js b/test/pummel/test-net-connect-memleak.js index e30ca2e6b0b72a..7c74011755403c 100644 --- a/test/pummel/test-net-connect-memleak.js +++ b/test/pummel/test-net-connect-memleak.js @@ -9,10 +9,11 @@ assert(typeof global.gc === 'function', 'Run this test with --expose-gc'); net.createServer(function() {}).listen(common.PORT); var before = 0; -(function() { +{ // 2**26 == 64M entries global.gc(); - for (var i = 0, junk = [0]; i < 26; ++i) junk = junk.concat(junk); + let junk = [0]; + for (let i = 0; i < 26; ++i) junk = junk.concat(junk); before = process.memoryUsage().rss; net.createConnection(common.PORT, '127.0.0.1', function() { @@ -20,7 +21,7 @@ var before = 0; setTimeout(done, 10); global.gc(); }); -})(); +} function done() { global.gc(); diff --git a/test/pummel/test-tls-ci-reneg-attack.js b/test/pummel/test-tls-ci-reneg-attack.js index b62b8944357ee7..5075806c1085b6 100644 --- a/test/pummel/test-tls-ci-reneg-attack.js +++ b/test/pummel/test-tls-ci-reneg-attack.js @@ -19,15 +19,15 @@ if (!common.opensslCli) { // renegotiation limits to test var LIMITS = [0, 1, 2, 3, 5, 10, 16]; -(function() { - var n = 0; +{ + let n = 0; function next() { if (n >= LIMITS.length) return; tls.CLIENT_RENEG_LIMIT = LIMITS[n++]; test(next); } next(); -})(); +} function test(next) { var options = { diff --git a/test/pummel/test-tls-connect-memleak.js b/test/pummel/test-tls-connect-memleak.js index 2ea61ead6fe5c3..227d9c56f4366e 100644 --- a/test/pummel/test-tls-connect-memleak.js +++ b/test/pummel/test-tls-connect-memleak.js @@ -19,17 +19,19 @@ tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/test_key.pem') }).listen(common.PORT); -(function() { +{ // 2**26 == 64M entries - for (var i = 0, junk = [0]; i < 26; ++i) junk = junk.concat(junk); + let junk = [0]; - var options = { rejectUnauthorized: false }; + for (let i = 0; i < 26; ++i) junk = junk.concat(junk); + + const options = { rejectUnauthorized: false }; tls.connect(common.PORT, '127.0.0.1', options, function() { assert(junk.length != 0); // keep reference alive setTimeout(done, 10); global.gc(); }); -})(); +} function done() { var before = process.memoryUsage().rss; diff --git a/test/sequential/test-child-process-execsync.js b/test/sequential/test-child-process-execsync.js index 2fad4ba8c205b7..fc3c0494dcbe18 100644 --- a/test/sequential/test-child-process-execsync.js +++ b/test/sequential/test-child-process-execsync.js @@ -70,8 +70,8 @@ assert.strictEqual(ret, msg + '\n', } // Verify that stderr is not accessed when stdio = 'ignore' - GH #7966 -(function() { +{ assert.throws(function() { execSync('exit -1', {stdio: 'ignore'}); }, /Command failed: exit -1/); -})(); +} From d224b47b3a7c41fda7b037584eaaa685969e534d Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Tue, 12 Jul 2016 16:31:46 -0700 Subject: [PATCH 11/34] test: improve error message in test-tick-processor Provide additional information about values that indicate test failed. PR-URL: https://github.com/nodejs/node/pull/7693 Reviewed-By: Colin Ihrig Reviewed-By: Brian White --- test/parallel/test-tick-processor.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/test/parallel/test-tick-processor.js b/test/parallel/test-tick-processor.js index 3abb97579b74ee..550061499a394b 100644 --- a/test/parallel/test-tick-processor.js +++ b/test/parallel/test-tick-processor.js @@ -1,8 +1,8 @@ 'use strict'; -var fs = require('fs'); -var assert = require('assert'); -var cp = require('child_process'); -var common = require('../common'); +const fs = require('fs'); +const assert = require('assert'); +const cp = require('child_process'); +const common = require('../common'); // TODO(mhdawson) Currently the test-tick-processor functionality in V8 // depends on addresses being smaller than a full 64 bits. Aix supports @@ -49,12 +49,12 @@ function runTest(pattern, code) { return /^isolate-/.test(file); }); if (matches.length != 1) { - assert.fail(null, null, 'There should be a single log file.'); + common.fail('There should be a single log file.'); } var log = matches[0]; var out = cp.execSync(process.execPath + ' --prof-process --call-graph-size=10 ' + log, {encoding: 'utf8'}); - assert(pattern.test(out)); + assert(pattern.test(out), `${pattern} not matching ${out}`); fs.unlinkSync(log); } From f0d96103ff3d4a433c3349efc068fc4aff2145e7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jaime=20Hidalgo=20Garc=C3=ADa?= Date: Thu, 7 Jul 2016 20:39:09 +0200 Subject: [PATCH 12/34] doc: removed old git conflict markers from fs.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "doc/api/fs.md" file had some conflict markers like "<<<<<<< HEAD" that are visible at the bottom of https://nodejs.org/api/fs.html PR-URL: https://github.com/nodejs/node/pull/7590 Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Brian White Reviewed-By: Colin Ihrig Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Myles Borins --- doc/api/fs.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/doc/api/fs.md b/doc/api/fs.md index 74da659dbf6625..268b6db9b49b3d 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1963,12 +1963,9 @@ The following constants are meant for use with the [`fs.Stats`][] object's [Writable Stream]: stream.html#stream_class_stream_writable [inode]: http://www.linux.org/threads/intro-to-inodes.4130 [FS Constants]: #fs_fs_constants -<<<<<<< HEAD [`inotify`]: http://man7.org/linux/man-pages/man7/inotify.7.html [`kqueue`]: https://www.freebsd.org/cgi/man.cgi?kqueue [`FSEvents`]: https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/FSEvents_ProgGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40005289-CH1-SW1 [`event ports`]: http://illumos.org/man/port_create [`ReadDirectoryChangesW`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v=vs.85%29.aspx [`AHAFS`]: https://www.ibm.com/developerworks/aix/library/au-aix_event_infrastructure/ -======= ->>>>>>> dcccbfd... src: refactor require('constants') From 3b767b86bded42d7b85e19f39264d1c21fdd3bfe Mon Sep 17 00:00:00 2001 From: Ingvar Stepanyan Date: Mon, 6 Jun 2016 13:06:56 +0100 Subject: [PATCH 13/34] buffer: fix creating from zero-length ArrayBuffer MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixes regression where creating a new Buffer from an empty ArrayBuffer would fail. Ref: https://github.com/nodejs/node/commit/85ab4a5f1281c4e1dd06450ac7bd3250326267fa PR-URL: https://github.com/nodejs/node/pull/7176 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Ron Korving --- lib/buffer.js | 2 +- test/parallel/test-buffer-alloc.js | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/buffer.js b/lib/buffer.js index 3be54669619567..a5f7ec5ffbb7b1 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -218,7 +218,7 @@ function fromArrayBuffer(obj, byteOffset, length) { const maxLength = obj.byteLength - byteOffset; - if (maxLength <= 0) + if (maxLength < 0) throw new RangeError("'offset' is out of bounds"); if (length === undefined) { diff --git a/test/parallel/test-buffer-alloc.js b/test/parallel/test-buffer-alloc.js index c06c1107039cb2..b771054bdd0656 100644 --- a/test/parallel/test-buffer-alloc.js +++ b/test/parallel/test-buffer-alloc.js @@ -1458,3 +1458,8 @@ const ubuf = Buffer.allocUnsafeSlow(10); assert(ubuf); assert(ubuf.buffer); assert.equal(ubuf.buffer.byteLength, 10); + +// Regression test +assert.doesNotThrow(() => { + Buffer.from(new ArrayBuffer()); +}); From c10ade917a0891eaad206c21c6d31eed322d573e Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Sat, 9 Jul 2016 14:51:21 +0200 Subject: [PATCH 14/34] deps: back-port d721121 from v8 upstream MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Original commit message: Quit creating array literal boilerplates from Crankshaft. It's such a corner case. BUG= Review URL: https://codereview.chromium.org/1865013002 Cr-Commit-Position: refs/heads/master@{#35346} Fixes: https://github.com/nodejs/node/issues/7454 PR-URL: https://github.com/nodejs/node/pull/7633 Reviewed-By: Fedor Indutny Reviewed-By: Michaël Zasso --- deps/v8/include/v8-version.h | 2 +- deps/v8/src/crankshaft/hydrogen.cc | 53 +++++++------------------ deps/v8/src/runtime/runtime-literals.cc | 9 ++--- deps/v8/src/runtime/runtime.h | 5 --- 4 files changed, 19 insertions(+), 50 deletions(-) diff --git a/deps/v8/include/v8-version.h b/deps/v8/include/v8-version.h index 39a537df5720aa..c30ace1e885cf1 100644 --- a/deps/v8/include/v8-version.h +++ b/deps/v8/include/v8-version.h @@ -11,7 +11,7 @@ #define V8_MAJOR_VERSION 5 #define V8_MINOR_VERSION 0 #define V8_BUILD_NUMBER 71 -#define V8_PATCH_LEVEL 54 +#define V8_PATCH_LEVEL 55 // Use 1 for candidates and 0 otherwise. // (Boolean macro values are not supported by all preprocessors.) diff --git a/deps/v8/src/crankshaft/hydrogen.cc b/deps/v8/src/crankshaft/hydrogen.cc index 4e34d177254076..ea20a971de961a 100644 --- a/deps/v8/src/crankshaft/hydrogen.cc +++ b/deps/v8/src/crankshaft/hydrogen.cc @@ -6044,60 +6044,34 @@ void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { Handle site; Handle literals(environment()->closure()->literals(), isolate()); - bool uninitialized = false; Handle literals_cell(literals->literal(expr->literal_index()), isolate()); Handle boilerplate_object; - if (literals_cell->IsUndefined()) { - uninitialized = true; - Handle raw_boilerplate; - ASSIGN_RETURN_ON_EXCEPTION_VALUE( - isolate(), raw_boilerplate, - Runtime::CreateArrayLiteralBoilerplate( - isolate(), literals, expr->constant_elements(), - is_strong(function_language_mode())), - Bailout(kArrayBoilerplateCreationFailed)); - - boilerplate_object = Handle::cast(raw_boilerplate); - AllocationSiteCreationContext creation_context(isolate()); - site = creation_context.EnterNewScope(); - if (JSObject::DeepWalk(boilerplate_object, &creation_context).is_null()) { - return Bailout(kArrayBoilerplateCreationFailed); - } - creation_context.ExitScope(site, boilerplate_object); - literals->set_literal(expr->literal_index(), *site); - - if (boilerplate_object->elements()->map() == - isolate()->heap()->fixed_cow_array_map()) { - isolate()->counters()->cow_arrays_created_runtime()->Increment(); - } - } else { + if (!literals_cell->IsUndefined()) { DCHECK(literals_cell->IsAllocationSite()); site = Handle::cast(literals_cell); boilerplate_object = Handle( JSObject::cast(site->transition_info()), isolate()); } - DCHECK(!boilerplate_object.is_null()); - DCHECK(site->SitePointsToLiteral()); - - ElementsKind boilerplate_elements_kind = - boilerplate_object->GetElementsKind(); + ElementsKind boilerplate_elements_kind = expr->constant_elements_kind(); + if (!boilerplate_object.is_null()) { + boilerplate_elements_kind = boilerplate_object->GetElementsKind(); + } // Check whether to use fast or slow deep-copying for boilerplate. int max_properties = kMaxFastLiteralProperties; - if (IsFastLiteral(boilerplate_object, - kMaxFastLiteralDepth, + if (!boilerplate_object.is_null() && + IsFastLiteral(boilerplate_object, kMaxFastLiteralDepth, &max_properties)) { + DCHECK(site->SitePointsToLiteral()); AllocationSiteUsageContext site_context(isolate(), site, false); site_context.EnterNewScope(); literal = BuildFastLiteral(boilerplate_object, &site_context); site_context.ExitScope(site, boilerplate_object); } else { NoObservableSideEffectsScope no_effects(this); - // Boilerplate already exists and constant elements are never accessed, - // pass an empty fixed array to the runtime function instead. - Handle constants = isolate()->factory()->empty_fixed_array(); + Handle constants = expr->constant_elements(); int literal_index = expr->literal_index(); int flags = expr->ComputeFlags(true); @@ -6108,7 +6082,9 @@ void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { literal = Add(Runtime::FunctionForId(function_id), 4); // Register to deopt if the boilerplate ElementsKind changes. - top_info()->dependencies()->AssumeTransitionStable(site); + if (!site.is_null()) { + top_info()->dependencies()->AssumeTransitionStable(site); + } } // The array is expected in the bailout environment during computation @@ -6140,9 +6116,8 @@ void HOptimizedGraphBuilder::VisitArrayLiteral(ArrayLiteral* expr) { case FAST_HOLEY_ELEMENTS: case FAST_DOUBLE_ELEMENTS: case FAST_HOLEY_DOUBLE_ELEMENTS: { - HStoreKeyed* instr = Add(elements, key, value, nullptr, - boilerplate_elements_kind); - instr->SetUninitialized(uninitialized); + Add(elements, key, value, nullptr, + boilerplate_elements_kind); break; } default: diff --git a/deps/v8/src/runtime/runtime-literals.cc b/deps/v8/src/runtime/runtime-literals.cc index e73095720eb9cd..d1e4e4670ec86e 100644 --- a/deps/v8/src/runtime/runtime-literals.cc +++ b/deps/v8/src/runtime/runtime-literals.cc @@ -138,7 +138,7 @@ MUST_USE_RESULT static MaybeHandle CreateObjectLiteralBoilerplate( } -MaybeHandle Runtime::CreateArrayLiteralBoilerplate( +static MaybeHandle CreateArrayLiteralBoilerplate( Isolate* isolate, Handle literals, Handle elements, bool is_strong) { // Create the JSArray. @@ -225,8 +225,8 @@ MUST_USE_RESULT static MaybeHandle CreateLiteralBoilerplate( return CreateObjectLiteralBoilerplate(isolate, literals, elements, false, kHasNoFunctionLiteral, is_strong); case CompileTimeValue::ARRAY_LITERAL: - return Runtime::CreateArrayLiteralBoilerplate(isolate, literals, - elements, is_strong); + return CreateArrayLiteralBoilerplate(isolate, literals, + elements, is_strong); default: UNREACHABLE(); return MaybeHandle(); @@ -318,8 +318,7 @@ MUST_USE_RESULT static MaybeHandle GetLiteralAllocationSite( Handle boilerplate; ASSIGN_RETURN_ON_EXCEPTION( isolate, boilerplate, - Runtime::CreateArrayLiteralBoilerplate(isolate, literals, elements, - is_strong), + CreateArrayLiteralBoilerplate(isolate, literals, elements, is_strong), AllocationSite); AllocationSiteCreationContext creation_context(isolate); diff --git a/deps/v8/src/runtime/runtime.h b/deps/v8/src/runtime/runtime.h index 7019c3bf041907..36412d2ffc08f1 100644 --- a/deps/v8/src/runtime/runtime.h +++ b/deps/v8/src/runtime/runtime.h @@ -1148,11 +1148,6 @@ class Runtime : public AllStatic { ElementsKind* fixed_elements_kind, size_t* element_size); - // Used in runtime.cc and hydrogen's VisitArrayLiteral. - MUST_USE_RESULT static MaybeHandle CreateArrayLiteralBoilerplate( - Isolate* isolate, Handle literals, - Handle elements, bool is_strong); - static MaybeHandle GetInternalProperties(Isolate* isolate, Handle); }; From a855b300d5fc25a6a6ac5e352d595ebcc53af583 Mon Sep 17 00:00:00 2001 From: cjihrig Date: Wed, 13 Jul 2016 11:18:31 -0400 Subject: [PATCH 15/34] cluster: remove bind() and self MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This commit removes the use of self and bind() from the cluster module in favor of arrow functions. PR-URL: https://github.com/nodejs/node/pull/7710 Reviewed-By: Michaël Zasso Reviewed-By: Santiago Gimeno Reviewed-By: Minwoo Jung --- lib/cluster.js | 34 ++++++++++++++++------------------ 1 file changed, 16 insertions(+), 18 deletions(-) diff --git a/lib/cluster.js b/lib/cluster.js index 8462ec34fc9aeb..5396573c3597a4 100644 --- a/lib/cluster.js +++ b/lib/cluster.js @@ -127,12 +127,11 @@ function RoundRobinHandle(key, address, port, addressType, backlog, fd) { else this.server.listen(address); // UNIX socket path. - var self = this; - this.server.once('listening', function() { - self.handle = self.server._handle; - self.handle.onconnection = self.distribute.bind(self); - self.server._handle = null; - self.server = null; + this.server.once('listening', () => { + this.handle = this.server._handle; + this.handle.onconnection = (err, handle) => this.distribute(err, handle); + this.server._handle = null; + this.server = null; }); } @@ -140,18 +139,17 @@ RoundRobinHandle.prototype.add = function(worker, send) { assert(worker.id in this.all === false); this.all[worker.id] = worker; - var self = this; - function done() { - if (self.handle.getsockname) { + const done = () => { + if (this.handle.getsockname) { var out = {}; - self.handle.getsockname(out); + this.handle.getsockname(out); // TODO(bnoordhuis) Check err. send(null, { sockname: out }, null); } else { send(null, null, null); // UNIX socket. } - self.handoff(worker); // In case there are connections pending. - } + this.handoff(worker); // In case there are connections pending. + }; if (this.server === null) return done(); // Still busy binding. @@ -193,13 +191,13 @@ RoundRobinHandle.prototype.handoff = function(worker) { return; } var message = { act: 'newconn', key: this.key }; - var self = this; - sendHelper(worker.process, message, handle, function(reply) { + + sendHelper(worker.process, message, handle, (reply) => { if (reply.accepted) handle.close(); else - self.distribute(0, handle); // Worker is shutting down. Send to another. - self.handoff(worker); + this.distribute(0, handle); // Worker is shutting down. Send to another. + this.handoff(worker); }); }; @@ -414,7 +412,7 @@ function masterInit() { cluster.disconnect = function(cb) { var workers = Object.keys(cluster.workers); if (workers.length === 0) { - process.nextTick(intercom.emit.bind(intercom, 'disconnect')); + process.nextTick(() => intercom.emit('disconnect')); } else { for (var key in workers) { key = workers[key]; @@ -436,7 +434,7 @@ function masterInit() { signo = signo || 'SIGTERM'; var proc = this.process; if (this.isConnected()) { - this.once('disconnect', proc.kill.bind(proc, signo)); + this.once('disconnect', () => proc.kill(signo)); this.disconnect(); return; } From 46b9ef6db22887058f1d4bddfc6a1271e52f712a Mon Sep 17 00:00:00 2001 From: Kevin Donahue Date: Thu, 14 Jul 2016 12:55:31 -0400 Subject: [PATCH 16/34] doc: fix typo in stream doc MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix small typo in Buffering section of stream doc. PR-URL: https://github.com/nodejs/node/pull/7738 Reviewed-By: Brian White Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Michaël Zasso Reviewed-By: Anna Henningsen --- doc/api/stream.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index 4be7f3c3f07880..124b1490fd6f29 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -87,7 +87,7 @@ total size of the internal write buffer is below the threshold set by the size of the internal buffer reaches or exceeds the `highWaterMark`, `false` will be returned. -A key goal of the `stream` API, an in particular the [`stream.pipe()`] method, +A key goal of the `stream` API, and in particular the [`stream.pipe()`] method, is to limit the buffering of data to acceptable levels such that sources and destinations of differing speeds will not overwhelm the available memory. From c726ffb29ca7a4a58960ba853f304407a950ef40 Mon Sep 17 00:00:00 2001 From: Lance Ball Date: Mon, 25 Apr 2016 15:48:50 -0400 Subject: [PATCH 17/34] doc: Warn against `uncaughtException` dependency. State in the documentation that `uncaughtException` is not a reliable way to restart a crashed application, and clarify that an application may crash in ways that do not trigger this event. Use a documented synchronous function in example code. Fixes: https://github.com/nodejs/node/issues/6223 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: James M Snell PR-URL: https://github.com/nodejs/node/pull/6378 --- doc/api/process.md | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/doc/api/process.md b/doc/api/process.md index d2f101419d6d48..6472f7cfc84ca1 100644 --- a/doc/api/process.md +++ b/doc/api/process.md @@ -149,10 +149,11 @@ most convenient for scripts). added: v0.1.18 --> -The `'uncaughtException'` event is emitted when an exception bubbles all the -way back to the event loop. By default, Node.js handles such exceptions by -printing the stack trace to `stderr` and exiting. Adding a handler for the -`'uncaughtException'` event overrides this default behavior. +The `'uncaughtException'` event is emitted when an uncaught JavaScript +exception bubbles all the way back to the event loop. By default, Node.js +handles such exceptions by printing the stack trace to `stderr` and exiting. +Adding a handler for the `'uncaughtException'` event overrides this default +behavior. The listener function is called with the `Error` object passed as the only argument. @@ -161,7 +162,7 @@ For example: ```js process.on('uncaughtException', (err) => { - console.log(`Caught exception: ${err}`); + fs.writeSync(1, `Caught exception: ${err}`); }); setTimeout(() => { @@ -192,8 +193,12 @@ times nothing happens - but the 10th time, the system becomes corrupted. The correct use of `'uncaughtException'` is to perform synchronous cleanup of allocated resources (e.g. file descriptors, handles, etc) before shutting -down the process. It is not safe to resume normal operation after -`'uncaughtException'`. +down the process. **It is not safe to resume normal operation after +`'uncaughtException'`.** + +To restart a crashed application in a more reliable way, whether `uncaughtException` +is emitted or not, an external monitor should be employed in a separate process +to detect application failures and recover or restart as needed. ### Event: 'unhandledRejection' The `'unhandledRejection`' event is emitted whenever a `Promise` is rejected and -no error handler is attached to the promise within a turn of the event loop. +no error handler is attached to the promise within a turn of the event loop. When programming with Promises, exceptions are encapsulated as "rejected promises". Rejections can be caught and handled using [`promise.catch()`][] and are propagated through a `Promise` chain. The `'unhandledRejection'` event is -useful for detecting and keeping track of promises that were rejected whose +useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled. The listener function is called with the following arguments: @@ -637,7 +642,7 @@ An example of this object looks like: SHLVL: '1', HOME: '/Users/maciej', LOGNAME: 'maciej', - _: '/usr/local/bin/node' + _: '/usr/local/bin/node' } ``` @@ -1108,10 +1113,10 @@ console.log(util.inspect(process.memoryUsage())); Will generate: ```js -{ +{ rss: 4935680, heapTotal: 1826816, - heapUsed: 650472 + heapUsed: 650472 } ``` From 9d9bd3cabbab1a2327843e65e0377affadb4dd43 Mon Sep 17 00:00:00 2001 From: Jeremy Whitlock Date: Thu, 23 Jul 2015 18:09:21 -0600 Subject: [PATCH 18/34] timers: fix processing of nested timers Whenever a timer is scheduled within another timer, there are a few known issues that we are fixing: * Whenever the timer being scheduled has the same timeout value as the outer timer, the newly created timer can fire on the same tick of the event loop instead of during the next tick of the event loop * Whenever a timer is added in another timer's callback, its underlying timer handle will be started with a timeout that is actually incorrect This commit consists of https://github.com/nodejs/node-v0.x-archive/pull/17203 and https://github.com/nodejs/node-v0.x-archive/pull/25763. Fixes: https://github.com/nodejs/node-v0.x-archive/issues/9333 Fixes: https://github.com/nodejs/node-v0.x-archive/issues/15447 Fixes: https://github.com/nodejs/node-v0.x-archive/issues/25607 Fixes: https://github.com/nodejs/node/issues/5426 PR-URL: https://github.com/nodejs/node/pull/3063 --- lib/timers.js | 8 +- test/common.js | 7 ++ .../parallel/test-timers-blocking-callback.js | 81 +++++++++++++++++++ test/parallel/test-timers-nested.js | 39 +++++++++ 4 files changed, 133 insertions(+), 2 deletions(-) create mode 100644 test/parallel/test-timers-blocking-callback.js create mode 100644 test/parallel/test-timers-nested.js diff --git a/lib/timers.js b/lib/timers.js index 9dbae32405cf6e..7379cfe3591e02 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -160,7 +160,7 @@ function listOnTimeout() { debug('timeout callback %d', msecs); var now = TimerWrap.now(); - debug('now: %s', now); + debug('now: %d', now); var diff, timer; while (timer = L.peek(list)) { @@ -169,7 +169,11 @@ function listOnTimeout() { // Check if this loop iteration is too early for the next timer. // This happens if there are more timers scheduled for later in the list. if (diff < msecs) { - this.start(msecs - diff, 0); + var timeRemaining = msecs - (TimerWrap.now() - timer._idleStart); + if (timeRemaining < 0) { + timeRemaining = 0; + } + this.start(timeRemaining, 0); debug('%d list wait because diff is %d', msecs, diff); return; } diff --git a/test/common.js b/test/common.js index f9d80ff1490e42..308411a13d3427 100644 --- a/test/common.js +++ b/test/common.js @@ -7,6 +7,7 @@ var os = require('os'); var child_process = require('child_process'); const stream = require('stream'); const util = require('util'); +const Timer = process.binding('timer_wrap').Timer; const testRoot = path.resolve(process.env.NODE_TEST_DIR || path.dirname(__filename)); @@ -484,3 +485,9 @@ exports.nodeProcessAborted = function nodeProcessAborted(exitCode, signal) { return expectedExitCodes.indexOf(exitCode) > -1; } }; + +exports.busyLoop = function busyLoop(time) { + var startTime = Timer.now(); + var stopTime = startTime + time; + while (Timer.now() < stopTime) {} +}; diff --git a/test/parallel/test-timers-blocking-callback.js b/test/parallel/test-timers-blocking-callback.js new file mode 100644 index 00000000000000..114c435a6af726 --- /dev/null +++ b/test/parallel/test-timers-blocking-callback.js @@ -0,0 +1,81 @@ +'use strict'; + +/* + * This is a regression test for https://github.com/joyent/node/issues/15447 + * and https://github.com/joyent/node/issues/9333. + * + * When a timer is added in another timer's callback, its underlying timer + * handle was started with a timeout that was actually incorrect. + * + * The reason was that the value that represents the current time was not + * updated between the time the original callback was called and the time + * the added timer was processed by timers.listOnTimeout. That lead the + * logic in timers.listOnTimeout to do an incorrect computation that made + * the added timer fire with a timeout of scheduledTimeout + + * timeSpentInCallback. + * + * This test makes sure that a timer added by another timer's callback + * fire with the expected timeout. + * + * It makes sure that it works when the timers list for a given timeout is + * empty (see testAddingTimerToEmptyTimersList) and when the timers list + * is not empty (see testAddingTimerToNonEmptyTimersList). + */ + +const assert = require('assert'); +const common = require('../common'); +const Timer = process.binding('timer_wrap').Timer; + +const TIMEOUT = 100; + +var nbBlockingCallbackCalls = 0; +var latestDelay = 0; +var timeCallbackScheduled = 0; + +function initTest() { + nbBlockingCallbackCalls = 0; + latestDelay = 0; + timeCallbackScheduled = 0; +} + +function blockingCallback(callback) { + ++nbBlockingCallbackCalls; + + if (nbBlockingCallbackCalls > 1) { + latestDelay = Timer.now() - timeCallbackScheduled; + // Even if timers can fire later than when they've been scheduled + // to fire, they should more than 50% later with a timeout of + // 100ms. Firing later than that would mean that we hit the regression + // highlighted in + // https://github.com/nodejs/node-v0.x-archive/issues/15447 and + // https://github.com/nodejs/node-v0.x-archive/issues/9333.. + assert(latestDelay < TIMEOUT * 1.5); + if (callback) + return callback(); + } else { + // block by busy-looping to trigger the issue + common.busyLoop(TIMEOUT); + + timeCallbackScheduled = Timer.now(); + setTimeout(blockingCallback, TIMEOUT); + } +} + +function testAddingTimerToEmptyTimersList(callback) { + initTest(); + // Call setTimeout just once to make sure the timers list is + // empty when blockingCallback is called. + setTimeout(blockingCallback.bind(null, callback), TIMEOUT); +} + +function testAddingTimerToNonEmptyTimersList() { + initTest(); + // Call setTimeout twice with the same timeout to make + // sure the timers list is not empty when blockingCallback is called. + setTimeout(blockingCallback, TIMEOUT); + setTimeout(blockingCallback, TIMEOUT); +} + +// Run the test for the empty timers list case, and then for the non-empty +// timers list one +testAddingTimerToEmptyTimersList(testAddingTimerToNonEmptyTimersList); diff --git a/test/parallel/test-timers-nested.js b/test/parallel/test-timers-nested.js new file mode 100644 index 00000000000000..17b397d33cd860 --- /dev/null +++ b/test/parallel/test-timers-nested.js @@ -0,0 +1,39 @@ +'use strict'; + +const assert = require('assert'); +const common = require('../common'); + +// Make sure we test 0ms timers, since they would had always wanted to run on +// the current tick, and greater than 0ms timers, for scenarios where the +// outer timer takes longer to complete than the delay of the nested timer. +// Since the process of recreating this is identical regardless of the timer +// delay, these scenarios are in one test. +const scenarios = [0, 100]; + +scenarios.forEach(function(delay) { + var nestedCalled = false; + + setTimeout(function A() { + // Create the nested timer with the same delay as the outer timer so that it + // gets added to the current list of timers being processed by + // listOnTimeout. + setTimeout(function B() { + nestedCalled = true; + }, delay); + + // Busy loop for the same timeout used for the nested timer to ensure that + // we are in fact expiring the nested timer. + common.busyLoop(delay); + + // The purpose of running this assert in nextTick is to make sure it runs + // after A but before the next iteration of the libuv event loop. + process.nextTick(function() { + assert.ok(!nestedCalled); + }); + + // Ensure that the nested callback is indeed called prior to process exit. + process.on('exit', function onExit() { + assert.ok(nestedCalled); + }); + }, delay); +}); From 669af6e6c8a1a58110ea123975ad26e19bde28c4 Mon Sep 17 00:00:00 2001 From: saadq Date: Thu, 14 Jul 2016 22:41:29 -0700 Subject: [PATCH 19/34] doc: fix inconsistencies in code style MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds missing semicolons, removes extra white space, and properly indents various code snippets in the documentation. Reviewed-By: Evan Lucas Reviewed-By: targos - Michaël Zasso PR-URL: https://github.com/nodejs/node/pull/7745 --- doc/api/assert.md | 4 ++-- doc/api/buffer.md | 2 +- doc/api/crypto.md | 2 +- doc/api/fs.md | 4 ++-- doc/api/http.md | 6 +++--- doc/api/https.md | 4 ++-- doc/api/path.md | 2 +- doc/api/readline.md | 6 +++--- doc/api/repl.md | 2 +- doc/api/stream.md | 8 ++++---- doc/api/util.md | 8 ++++---- 11 files changed, 24 insertions(+), 24 deletions(-) diff --git a/doc/api/assert.md b/doc/api/assert.md index e54e81d22e384e..bc5c0b833ae5aa 100644 --- a/doc/api/assert.md +++ b/doc/api/assert.md @@ -71,7 +71,7 @@ const obj3 = { a : { b : 1 } -} +}; const obj4 = Object.create(obj1); assert.deepEqual(obj1, obj1); @@ -230,7 +230,7 @@ const assert = require('assert'); assert.ifError(0); // OK assert.ifError(1); // Throws 1 -assert.ifError('error') // Throws 'error' +assert.ifError('error'); // Throws 'error' assert.ifError(new Error()); // Throws Error ``` diff --git a/doc/api/buffer.md b/doc/api/buffer.md index fb8065a645fdab..92908fd38b8177 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -247,7 +247,7 @@ Buffers can be iterated over using the ECMAScript 2015 (ES6) `for..of` syntax: const buf = Buffer.from([1, 2, 3]); for (var b of buf) - console.log(b) + console.log(b); // Prints: // 1 diff --git a/doc/api/crypto.md b/doc/api/crypto.md index 2738b395e655a7..283f87ccbc9f09 100644 --- a/doc/api/crypto.md +++ b/doc/api/crypto.md @@ -236,7 +236,7 @@ var decrypted = ''; decipher.on('readable', () => { var data = decipher.read(); if (data) - decrypted += data.toString('utf8'); + decrypted += data.toString('utf8'); }); decipher.on('end', () => { console.log(decrypted); diff --git a/doc/api/fs.md b/doc/api/fs.md index 268b6db9b49b3d..e8b158ac5edbcb 100644 --- a/doc/api/fs.md +++ b/doc/api/fs.md @@ -1022,12 +1022,12 @@ will be returned._ // OS X and Linux fs.open('', 'a+', (err, fd) => { // => [Error: EISDIR: illegal operation on a directory, open ] -}) +}); // Windows and FreeBSD fs.open('', 'a+', (err, fd) => { // => null, -}) +}); ``` ## fs.openSync(path, flags[, mode]) diff --git a/doc/api/http.md b/doc/api/http.md index 1a09e96395c7b8..2646d95c06592a 100644 --- a/doc/api/http.md +++ b/doc/api/http.md @@ -90,7 +90,7 @@ http.get({ agent: false // create a new agent just for this one request }, (res) => { // Do stuff with response -}) +}); ``` ### new Agent([options]) @@ -1451,8 +1451,8 @@ var req = http.request(options, (res) => { console.log(`BODY: ${chunk}`); }); res.on('end', () => { - console.log('No more data in response.') - }) + console.log('No more data in response.'); + }); }); req.on('error', (e) => { diff --git a/doc/api/https.md b/doc/api/https.md index c76f1ef837c9ab..620b6b36c74906 100644 --- a/doc/api/https.md +++ b/doc/api/https.md @@ -231,7 +231,7 @@ options.agent = new https.Agent(options); var req = https.request(options, (res) => { ... -} +}); ``` Alternatively, opt out of connection pooling by not using an `Agent`. @@ -251,7 +251,7 @@ var options = { var req = https.request(options, (res) => { ... -} +}); ``` [`Agent`]: #https_class_https_agent diff --git a/doc/api/path.md b/doc/api/path.md index f18ed52730623f..fd07cd6802df9a 100644 --- a/doc/api/path.md +++ b/doc/api/path.md @@ -234,7 +234,7 @@ path.format({ base : "file.txt", ext : ".txt", name : "file" -}) +}); // returns 'C:\\path\\dir\\file.txt' ``` diff --git a/doc/api/readline.md b/doc/api/readline.md index 385540908331c2..9025f6fe7da821 100644 --- a/doc/api/readline.md +++ b/doc/api/readline.md @@ -398,10 +398,10 @@ For instance: `[[substr1, substr2, ...], originalsubstring]`. ```js function completer(line) { - var completions = '.help .error .exit .quit .q'.split(' ') - var hits = completions.filter((c) => { return c.indexOf(line) == 0 }) + var completions = '.help .error .exit .quit .q'.split(' '); + var hits = completions.filter((c) => { return c.indexOf(line) == 0 }); // show all completions if none found - return [hits.length ? hits : completions, line] + return [hits.length ? hits : completions, line]; } ``` diff --git a/doc/api/repl.md b/doc/api/repl.md index 9d44a701fc379d..56efa5df5d79aa 100644 --- a/doc/api/repl.md +++ b/doc/api/repl.md @@ -492,7 +492,7 @@ net.createServer((socket) => { output: socket }).on('exit', () => { socket.end(); - }) + }); }).listen('/tmp/node-repl-sock'); net.createServer((socket) => { diff --git a/doc/api/stream.md b/doc/api/stream.md index 124b1490fd6f29..ad014a2a69b5bb 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -1227,9 +1227,9 @@ const Writable = require('stream').Writable; const myWritable = new Writable({ write(chunk, encoding, callback) { if (chunk.toString().indexOf('a') >= 0) { - callback(new Error('chunk is invalid')) + callback(new Error('chunk is invalid')); } else { - callback() + callback(); } } }); @@ -1252,9 +1252,9 @@ class MyWritable extends Writable { _write(chunk, encoding, callback) { if (chunk.toString().indexOf('a') >= 0) { - callback(new Error('chunk is invalid')) + callback(new Error('chunk is invalid')); } else { - callback() + callback(); } } } diff --git a/doc/api/util.md b/doc/api/util.md index 56ea9a474d8cb8..12849d1be8a917 100644 --- a/doc/api/util.md +++ b/doc/api/util.md @@ -145,14 +145,14 @@ const util = require('util'); const EventEmitter = require('events'); function MyStream() { - EventEmitter.call(this); + EventEmitter.call(this); } util.inherits(MyStream, EventEmitter); MyStream.prototype.write = function(data) { - this.emit('data', data); -} + this.emit('data', data); +}; const stream = new MyStream(); @@ -161,7 +161,7 @@ console.log(MyStream.super_ === EventEmitter); // true stream.on('data', (data) => { console.log(`Received data: "${data}"`); -}) +}); stream.write('It works!'); // Received data: "It works!" ``` From 17591c3964c310f149bdd6c2e2a4687b0dca4b7c Mon Sep 17 00:00:00 2001 From: cjihrig Date: Thu, 14 Jul 2016 11:26:35 -0400 Subject: [PATCH 20/34] test: s/assert.fail/common.fail as appropriate Many tests use assert.fail(null, null, msg) where it would be simpler to use common.fail(msg). This is largely because common.fail() is fairly new. This commit makes the replacement when applicable. PR-URL: https://github.com/nodejs/node/pull/7735 Reviewed-By: Sakthipriyan Vairamani Reviewed-By: Ben Noordhuis Reviewed-By: Jeremiah Senkpiel --- test/internet/test-dgram-send-cb-quelches-error.js | 2 +- .../test-event-emitter-listeners-side-effects.js | 12 ++++++------ test/parallel/test-event-emitter-once.js | 4 ++-- ...http-client-reject-chunked-with-content-length.js | 2 +- test/parallel/test-http-client-reject-cr-no-lf.js | 2 +- test/parallel/test-http-createConnection.js | 2 +- test/parallel/test-http-double-content-length.js | 3 +-- test/parallel/test-http-localaddress-bind-error.js | 4 ++-- .../test-http-response-multi-content-length.js | 2 +- test/parallel/test-http-response-splitting.js | 2 +- ...http-server-reject-chunked-with-content-length.js | 4 ++-- test/parallel/test-http-server-reject-cr-no-lf.js | 4 ++-- test/parallel/test-https-localaddress-bind-error.js | 2 +- test/parallel/test-net-connect-immediate-destroy.js | 5 ++--- test/parallel/test-net-connect-paused-connection.js | 5 ++--- ...t-listen-close-server-callback-is-not-function.js | 8 +++----- test/parallel/test-net-listen-port-option.js | 4 ++-- ...ver-max-connections-close-makes-more-available.js | 4 ++-- test/parallel/test-net-write-slow.js | 5 ++--- test/parallel/test-path-parse-format.js | 4 ++-- test/parallel/test-process-exit-from-before-exit.js | 5 ++--- test/parallel/test-repl-reset-event.js | 2 +- test/parallel/test-repl-tab.js | 6 ++---- test/parallel/test-spawn-cmd-named-pipe.js | 2 +- .../test-stream2-base64-single-char-read-end.js | 4 ++-- test/parallel/test-tls-client-mindhsize.js | 2 +- test/sequential/test-child-process-emfile.js | 3 +-- 27 files changed, 47 insertions(+), 57 deletions(-) diff --git a/test/internet/test-dgram-send-cb-quelches-error.js b/test/internet/test-dgram-send-cb-quelches-error.js index 64b354c3eb3bfc..56612edead4fd2 100644 --- a/test/internet/test-dgram-send-cb-quelches-error.js +++ b/test/internet/test-dgram-send-cb-quelches-error.js @@ -28,7 +28,7 @@ function callbackOnly(err) { } function onEvent(err) { - assert.fail(null, null, 'Error should not be emitted if there is callback'); + common.fail('Error should not be emitted if there is callback'); } function onError(err) { diff --git a/test/parallel/test-event-emitter-listeners-side-effects.js b/test/parallel/test-event-emitter-listeners-side-effects.js index fec5a7a89767f6..1bed99f3641e98 100644 --- a/test/parallel/test-event-emitter-listeners-side-effects.js +++ b/test/parallel/test-event-emitter-listeners-side-effects.js @@ -1,6 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var EventEmitter = require('events').EventEmitter; @@ -14,12 +14,12 @@ assert(fl.length === 0); assert(!(e._events instanceof Object)); assert.deepStrictEqual(Object.keys(e._events), []); -e.on('foo', assert.fail); +e.on('foo', common.fail); fl = e.listeners('foo'); -assert(e._events.foo === assert.fail); +assert(e._events.foo === common.fail); assert(Array.isArray(fl)); assert(fl.length === 1); -assert(fl[0] === assert.fail); +assert(fl[0] === common.fail); e.listeners('bar'); @@ -28,12 +28,12 @@ fl = e.listeners('foo'); assert(Array.isArray(e._events.foo)); assert(e._events.foo.length === 2); -assert(e._events.foo[0] === assert.fail); +assert(e._events.foo[0] === common.fail); assert(e._events.foo[1] === assert.ok); assert(Array.isArray(fl)); assert(fl.length === 2); -assert(fl[0] === assert.fail); +assert(fl[0] === common.fail); assert(fl[1] === assert.ok); console.log('ok'); diff --git a/test/parallel/test-event-emitter-once.js b/test/parallel/test-event-emitter-once.js index d007ef663fdede..1df03d6660e145 100644 --- a/test/parallel/test-event-emitter-once.js +++ b/test/parallel/test-event-emitter-once.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var events = require('events'); @@ -16,7 +16,7 @@ e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b'); var remove = function() { - assert.fail(1, 0, 'once->foo should not be emitted', '!'); + common.fail('once->foo should not be emitted'); }; e.once('foo', remove); diff --git a/test/parallel/test-http-client-reject-chunked-with-content-length.js b/test/parallel/test-http-client-reject-chunked-with-content-length.js index 324ba004d58a7d..daa0591cd75506 100644 --- a/test/parallel/test-http-client-reject-chunked-with-content-length.js +++ b/test/parallel/test-http-client-reject-chunked-with-content-length.js @@ -18,7 +18,7 @@ server.listen(0, () => { // both a Content-Length header and a Transfer-Encoding: chunked // header, which is a violation of the HTTP spec. const req = http.get({port: server.address().port}, (res) => { - assert.fail(null, null, 'callback should not be called'); + common.fail('callback should not be called'); }); req.on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); diff --git a/test/parallel/test-http-client-reject-cr-no-lf.js b/test/parallel/test-http-client-reject-cr-no-lf.js index e396637aaa448d..4cabfa0107bbc8 100644 --- a/test/parallel/test-http-client-reject-cr-no-lf.js +++ b/test/parallel/test-http-client-reject-cr-no-lf.js @@ -17,7 +17,7 @@ server.listen(0, () => { // The callback should not be called because the server is sending a // header field that ends only in \r with no following \n const req = http.get({port: server.address().port}, (res) => { - assert.fail(null, null, 'callback should not be called'); + common.fail('callback should not be called'); }); req.on('error', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); diff --git a/test/parallel/test-http-createConnection.js b/test/parallel/test-http-createConnection.js index 04d7f3dc0dc6cb..69592eb09ff487 100644 --- a/test/parallel/test-http-createConnection.js +++ b/test/parallel/test-http-createConnection.js @@ -21,7 +21,7 @@ const server = http.createServer(common.mustCall(function(req, res) { res.resume(); fn = common.mustCall(createConnectionError); http.get({ createConnection: fn }, function(res) { - assert.fail(null, null, 'Unexpected response callback'); + common.fail('Unexpected response callback'); }).on('error', common.mustCall(function(err) { assert.equal(err.message, 'Could not create socket'); server.close(); diff --git a/test/parallel/test-http-double-content-length.js b/test/parallel/test-http-double-content-length.js index ac70168601aaf5..a73cf49854ed35 100644 --- a/test/parallel/test-http-double-content-length.js +++ b/test/parallel/test-http-double-content-length.js @@ -23,8 +23,7 @@ server.listen(0, () => { // Send two content-length header values. headers: {'Content-Length': [1, 2]}}, (res) => { - assert.fail(null, null, 'an error should have occurred'); - server.close(); + common.fail('an error should have occurred'); } ); req.on('error', common.mustCall(() => { diff --git a/test/parallel/test-http-localaddress-bind-error.js b/test/parallel/test-http-localaddress-bind-error.js index 51605fab6aa10e..5b537b00e7ead7 100644 --- a/test/parallel/test-http-localaddress-bind-error.js +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -24,7 +24,7 @@ server.listen(0, '127.0.0.1', function() { method: 'GET', localAddress: invalidLocalAddress }, function(res) { - assert.fail(null, null, 'unexpectedly got response from server'); + common.fail('unexpectedly got response from server'); }).on('error', function(e) { console.log('client got error: ' + e.message); gotError = true; diff --git a/test/parallel/test-http-response-multi-content-length.js b/test/parallel/test-http-response-multi-content-length.js index dd6ad6a1cd4a0c..098061002b003c 100644 --- a/test/parallel/test-http-response-multi-content-length.js +++ b/test/parallel/test-http-response-multi-content-length.js @@ -19,7 +19,7 @@ const server = http.createServer((req, res) => { res.writeHead(200, {'content-length': [1, 2]}); break; default: - assert.fail(null, null, 'should never get here'); + common.fail('should never get here'); } res.end('ok'); }); diff --git a/test/parallel/test-http-response-splitting.js b/test/parallel/test-http-response-splitting.js index 07ced3fd146f9c..e4021e78317759 100644 --- a/test/parallel/test-http-response-splitting.js +++ b/test/parallel/test-http-response-splitting.js @@ -38,7 +38,7 @@ const server = http.createServer((req, res) => { })); break; default: - assert.fail(null, null, 'should not get to here.'); + common.fail('should not get to here.'); } if (count === 3) server.close(); diff --git a/test/parallel/test-http-server-reject-chunked-with-content-length.js b/test/parallel/test-http-server-reject-chunked-with-content-length.js index b3284c368546b5..d8697cd38cde72 100644 --- a/test/parallel/test-http-server-reject-chunked-with-content-length.js +++ b/test/parallel/test-http-server-reject-chunked-with-content-length.js @@ -10,7 +10,7 @@ const reqstr = 'POST / HTTP/1.1\r\n' + 'Transfer-Encoding: chunked\r\n\r\n'; const server = http.createServer((req, res) => { - assert.fail(null, null, 'callback should not be invoked'); + common.fail('callback should not be invoked'); }); server.on('clientError', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); @@ -25,7 +25,7 @@ server.listen(0, () => { client.on('data', (data) => { // Should not get to this point because the server should simply // close the connection without returning any data. - assert.fail(null, null, 'no data should be returned by the server'); + common.fail('no data should be returned by the server'); }); client.on('end', common.mustCall(() => {})); }); diff --git a/test/parallel/test-http-server-reject-cr-no-lf.js b/test/parallel/test-http-server-reject-cr-no-lf.js index 6c55dead96f19f..81a7208d982334 100644 --- a/test/parallel/test-http-server-reject-cr-no-lf.js +++ b/test/parallel/test-http-server-reject-cr-no-lf.js @@ -12,7 +12,7 @@ const str = 'GET / HTTP/1.1\r\n' + const server = http.createServer((req, res) => { - assert.fail(null, null, 'this should not be called'); + common.fail('this should not be called'); }); server.on('clientError', common.mustCall((err) => { assert(/^Parse Error/.test(err.message)); @@ -22,7 +22,7 @@ server.on('clientError', common.mustCall((err) => { server.listen(0, () => { const client = net.connect({port: server.address().port}, () => { client.on('data', (chunk) => { - assert.fail(null, null, 'this should not be called'); + common.fail('this should not be called'); }); client.on('end', common.mustCall(() => { server.close(); diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js index 5e5f900c7a809b..1ce94a0ac0eaca 100644 --- a/test/parallel/test-https-localaddress-bind-error.js +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -35,7 +35,7 @@ server.listen(0, '127.0.0.1', function() { method: 'GET', localAddress: invalidLocalAddress }, function(res) { - assert.fail(null, null, 'unexpectedly got response from server'); + common.fail('unexpectedly got response from server'); }).on('error', function(e) { console.log('client got error: ' + e.message); gotError = true; diff --git a/test/parallel/test-net-connect-immediate-destroy.js b/test/parallel/test-net-connect-immediate-destroy.js index 37dc4b2d9a2391..f8d22d92d0a985 100644 --- a/test/parallel/test-net-connect-immediate-destroy.js +++ b/test/parallel/test-net-connect-immediate-destroy.js @@ -1,8 +1,7 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const net = require('net'); -const socket = net.connect(common.PORT, common.localhostIPv4, assert.fail); -socket.on('error', assert.fail); +const socket = net.connect(common.PORT, common.localhostIPv4, common.fail); +socket.on('error', common.fail); socket.destroy(); diff --git a/test/parallel/test-net-connect-paused-connection.js b/test/parallel/test-net-connect-paused-connection.js index 857b287b62174f..8c0e1c93cfb208 100644 --- a/test/parallel/test-net-connect-paused-connection.js +++ b/test/parallel/test-net-connect-paused-connection.js @@ -1,6 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var net = require('net'); @@ -10,6 +9,6 @@ net.createServer(function(conn) { net.connect(this.address().port, 'localhost').pause(); setTimeout(function() { - assert.fail(null, null, 'expected to exit'); + common.fail('expected to exit'); }, 1000).unref(); }).unref(); diff --git a/test/parallel/test-net-listen-close-server-callback-is-not-function.js b/test/parallel/test-net-listen-close-server-callback-is-not-function.js index b0fe8c2fe15b71..6fdb61e85dd4e0 100644 --- a/test/parallel/test-net-listen-close-server-callback-is-not-function.js +++ b/test/parallel/test-net-listen-close-server-callback-is-not-function.js @@ -1,18 +1,16 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var server = net.createServer(assert.fail); +var server = net.createServer(common.fail); var closeEvents = 0; server.on('close', function() { ++closeEvents; }); -server.listen(0, function() { - assert(false); -}); +server.listen(0, common.fail); server.close('bad argument'); diff --git a/test/parallel/test-net-listen-port-option.js b/test/parallel/test-net-listen-port-option.js index 18b256c973eaec..77c9cb42f0a930 100644 --- a/test/parallel/test-net-listen-port-option.js +++ b/test/parallel/test-net-listen-port-option.js @@ -17,12 +17,12 @@ net.Server().listen({ port: '' + common.PORT }, close); '-Infinity' ].forEach(function(port) { assert.throws(function() { - net.Server().listen({ port: port }, assert.fail); + net.Server().listen({ port: port }, common.fail); }, /"port" argument must be >= 0 and < 65536/i); }); [null, true, false].forEach(function(port) { assert.throws(function() { - net.Server().listen({ port: port }, assert.fail); + net.Server().listen({ port: port }, common.fail); }, /invalid listen argument/i); }); diff --git a/test/parallel/test-net-server-max-connections-close-makes-more-available.js b/test/parallel/test-net-server-max-connections-close-makes-more-available.js index 08e5bbc2bc74b6..2f8bee1a8d68d9 100644 --- a/test/parallel/test-net-server-max-connections-close-makes-more-available.js +++ b/test/parallel/test-net-server-max-connections-close-makes-more-available.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -86,5 +86,5 @@ process.on('exit', function() { process.on('unhandledRejection', function() { console.error('promise rejected'); - assert.fail(null, null, 'A promise in the chain rejected'); + common.fail('A promise in the chain rejected'); }); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js index 9acc1b31c37430..7abee7d0e7dffb 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); @@ -13,8 +13,7 @@ var server = net.createServer(function(socket) { socket.setNoDelay(); socket.setTimeout(9999); socket.on('timeout', function() { - assert.fail(null, null, 'flushed: ' + flushed + - ', received: ' + received + '/' + SIZE * N); + common.fail(`flushed: ${flushed}, received: ${received}/${SIZE * N}`); }); for (var i = 0; i < N; ++i) { diff --git a/test/parallel/test-path-parse-format.js b/test/parallel/test-path-parse-format.js index a42794790d1459..2db4c27dce072a 100644 --- a/test/parallel/test-path-parse-format.js +++ b/test/parallel/test-path-parse-format.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const path = require('path'); @@ -169,7 +169,7 @@ function checkErrors(path) { return; } - assert.fail(null, null, 'should have thrown'); + common.fail('should have thrown'); }); } diff --git a/test/parallel/test-process-exit-from-before-exit.js b/test/parallel/test-process-exit-from-before-exit.js index 30d358cb76da9d..b37df0a5bd340d 100644 --- a/test/parallel/test-process-exit-from-before-exit.js +++ b/test/parallel/test-process-exit-from-before-exit.js @@ -1,9 +1,8 @@ 'use strict'; -var assert = require('assert'); var common = require('../common'); process.on('beforeExit', common.mustCall(function() { - setTimeout(assert.fail, 5); + setTimeout(common.fail, 5); process.exit(0); // Should execute immediately even if we schedule new work. - assert.fail(); + common.fail(); })); diff --git a/test/parallel/test-repl-reset-event.js b/test/parallel/test-repl-reset-event.js index 0bd43dcd6c370e..eee61ac17356f4 100644 --- a/test/parallel/test-repl-reset-event.js +++ b/test/parallel/test-repl-reset-event.js @@ -42,7 +42,7 @@ function testResetGlobal(cb) { } var timeout = setTimeout(function() { - assert.fail(null, null, 'Timeout, REPL did not emit reset events'); + common.fail('Timeout, REPL did not emit reset events'); }, 5000); testReset(function() { diff --git a/test/parallel/test-repl-tab.js b/test/parallel/test-repl-tab.js index 6474d8e4088167..c075b8d4f1125f 100644 --- a/test/parallel/test-repl-tab.js +++ b/test/parallel/test-repl-tab.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var repl = require('repl'); var zlib = require('zlib'); @@ -10,9 +10,7 @@ var testMe = repl.start('', putIn, function(cmd, context, filename, callback) { callback(null, cmd); }); -testMe._domain.on('error', function(e) { - assert.fail(); -}); +testMe._domain.on('error', common.fail); testMe.complete('', function(err, results) { assert.equal(err, null); diff --git a/test/parallel/test-spawn-cmd-named-pipe.js b/test/parallel/test-spawn-cmd-named-pipe.js index fafc5b2167ba59..c463bf6140053f 100644 --- a/test/parallel/test-spawn-cmd-named-pipe.js +++ b/test/parallel/test-spawn-cmd-named-pipe.js @@ -39,7 +39,7 @@ if (!process.argv[2]) { const comspec = process.env['comspec']; if (!comspec || comspec.length === 0) { - assert.fail(null, null, 'Failed to get COMSPEC'); + common.fail('Failed to get COMSPEC'); } const args = ['/c', process.execPath, __filename, 'child', diff --git a/test/parallel/test-stream2-base64-single-char-read-end.js b/test/parallel/test-stream2-base64-single-char-read-end.js index 07244dc0fbbf78..50bafc3737385d 100644 --- a/test/parallel/test-stream2-base64-single-char-read-end.js +++ b/test/parallel/test-stream2-base64-single-char-read-end.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var R = require('_stream_readable'); var W = require('_stream_writable'); var assert = require('assert'); @@ -33,5 +33,5 @@ src.on('end', function() { src.pipe(dst); timeout = setTimeout(function() { - assert.fail(null, null, 'timed out waiting for _write'); + common.fail('timed out waiting for _write'); }, 100); diff --git a/test/parallel/test-tls-client-mindhsize.js b/test/parallel/test-tls-client-mindhsize.js index 0012dec4d07d58..9956c971ffbbf3 100644 --- a/test/parallel/test-tls-client-mindhsize.js +++ b/test/parallel/test-tls-client-mindhsize.js @@ -75,7 +75,7 @@ function testDHE2048() { testDHE1024(); -assert.throws(() => test(512, true, assert.fail), +assert.throws(() => test(512, true, common.fail), /DH parameter is less than 1024 bits/); [0, -1, -Infinity, NaN].forEach((minDHSize) => { diff --git a/test/sequential/test-child-process-emfile.js b/test/sequential/test-child-process-emfile.js index f186db54016a40..8f59842f99563b 100644 --- a/test/sequential/test-child-process-emfile.js +++ b/test/sequential/test-child-process-emfile.js @@ -44,8 +44,7 @@ proc.on('error', common.mustCall(function(err) { })); proc.on('exit', function() { - const msg = '"exit" should not be emitted (the process never spawned!)'; - assert.fail(null, null, msg); + common.fail('"exit" should not be emitted (the process never spawned!)'); }); // close one fd for LSan From 3bd40ff5ca069cc0a2e3275c12c3ed948195038f Mon Sep 17 00:00:00 2001 From: Fedor Indutny Date: Sat, 16 Jul 2016 00:04:07 -0400 Subject: [PATCH 21/34] deps: no /safeseh for ml64.exe `ml64.exe` doesn't support `/safeseh` option. Do not attempt to use it if `target_arch=="x64"`. See: https://msdn.microsoft.com/en-us/library/s0ksfwcf.aspx PR-URL: https://github.com/nodejs/node/pull/7759 Reviewed-By: Ben Noordhuis Reviewed-By: Robert Jefe Lindstaedt Reviewed-By: Minwoo Jung --- deps/openssl/openssl.gyp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/deps/openssl/openssl.gyp b/deps/openssl/openssl.gyp index b25efe60d5e8e6..ae5c980e06a5ab 100644 --- a/deps/openssl/openssl.gyp +++ b/deps/openssl/openssl.gyp @@ -121,15 +121,17 @@ }], # end of conditions of openssl_no_asm ['OS=="win"', { 'defines' : ['<@(openssl_defines_all_win)'], + }, { + 'defines' : ['<@(openssl_defines_all_non_win)'] + }], + ['target_arch=="ia32" and OS=="win"', { 'msvs_settings': { 'MASM': { # Use /safeseh, see commit: 01fa5ee 'UseSafeExceptionHandlers': 'true', }, }, - }, { - 'defines' : ['<@(openssl_defines_all_non_win)'] - }] + }], ], 'include_dirs': ['<@(openssl_include_dirs)'], 'direct_dependent_settings': { From 60c459c90f204e161f8404540c5f30d1df026365 Mon Sep 17 00:00:00 2001 From: Anna Henningsen Date: Sat, 9 Jul 2016 22:27:38 +0200 Subject: [PATCH 22/34] util: inspect boxed symbols like other primitives MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Inspect boxed symbol objects in the same way other boxed primitives are inspected. Fixes: https://github.com/nodejs/node/issues/7639 PR-URL: https://github.com/nodejs/node/pull/7641 Reviewed-By: Michaël Zasso Reviewed-By: Ben Noordhuis Reviewed-By: Benjamin Gruenbaum Reviewed-By: Colin Ihrig Reviewed-By: Sakthipriyan Vairamani --- lib/util.js | 4 ++++ test/parallel/test-util-inspect.js | 1 + 2 files changed, 5 insertions(+) diff --git a/lib/util.js b/lib/util.js index d4b87eaeb0a58f..bb588cf475e236 100644 --- a/lib/util.js +++ b/lib/util.js @@ -413,6 +413,10 @@ function formatValue(ctx, value, recurseTimes) { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[String: ' + formatted + ']', 'string'); } + if (typeof raw === 'symbol') { + formatted = formatPrimitiveNoColor(ctx, raw); + return ctx.stylize('[Symbol: ' + formatted + ']', 'symbol'); + } if (typeof raw === 'number') { formatted = formatPrimitiveNoColor(ctx, raw); return ctx.stylize('[Number: ' + formatted + ']', 'number'); diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index b25a3190c94d6c..0817f54a9bdc1f 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -474,6 +474,7 @@ test_lines({ // test boxed primitives output the correct values assert.equal(util.inspect(new String('test')), '[String: \'test\']'); +assert.equal(util.inspect(Object(Symbol('test'))), '[Symbol: Symbol(test)]'); assert.equal(util.inspect(new Boolean(false)), '[Boolean: false]'); assert.equal(util.inspect(new Boolean(true)), '[Boolean: true]'); assert.equal(util.inspect(new Number(0)), '[Number: 0]'); From ba6ab7cb3776146e45effdf097bd16744944ed6b Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Wed, 6 Jul 2016 21:57:39 -0700 Subject: [PATCH 23/34] buffer: optimize hex_decode PR-URL: https://github.com/nodejs/node/pull/7602 Reviewed-By: Anna Henningsen --- benchmark/buffers/buffer-hex.js | 26 +++++++++++++++++ src/string_bytes.cc | 37 ++++++++++++++++--------- test/parallel/test-buffer-badhex.js | 43 +++++++++++++++++++++++++++++ 3 files changed, 93 insertions(+), 13 deletions(-) create mode 100644 benchmark/buffers/buffer-hex.js create mode 100644 test/parallel/test-buffer-badhex.js diff --git a/benchmark/buffers/buffer-hex.js b/benchmark/buffers/buffer-hex.js new file mode 100644 index 00000000000000..d05bb832b3068c --- /dev/null +++ b/benchmark/buffers/buffer-hex.js @@ -0,0 +1,26 @@ +'use strict'; + +const common = require('../common.js'); + +const bench = common.createBenchmark(main, { + len: [0, 1, 64, 1024], + n: [1e7] +}); + +function main(conf) { + const len = conf.len | 0; + const n = conf.n | 0; + const buf = Buffer.alloc(len); + + for (let i = 0; i < buf.length; i++) + buf[i] = i & 0xff; + + const hex = buf.toString('hex'); + + bench.start(); + + for (let i = 0; i < n; i += 1) + Buffer.from(hex, 'hex'); + + bench.end(n); +} diff --git a/src/string_bytes.cc b/src/string_bytes.cc index 882340ae048bf3..935c6f178112c4 100644 --- a/src/string_bytes.cc +++ b/src/string_bytes.cc @@ -143,16 +143,27 @@ const int8_t unbase64_table[256] = }; -template -unsigned hex2bin(TypeName c) { - if (c >= '0' && c <= '9') - return c - '0'; - if (c >= 'A' && c <= 'F') - return 10 + (c - 'A'); - if (c >= 'a' && c <= 'f') - return 10 + (c - 'a'); - return static_cast(-1); -} +static const int8_t unhex_table[256] = + { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + +#define unhex(x) \ + static_cast(unhex_table[static_cast(x)]) template @@ -162,11 +173,11 @@ size_t hex_decode(char* buf, const size_t srcLen) { size_t i; for (i = 0; i < len && i * 2 + 1 < srcLen; ++i) { - unsigned a = hex2bin(src[i * 2 + 0]); - unsigned b = hex2bin(src[i * 2 + 1]); + unsigned a = unhex(src[i * 2 + 0]); + unsigned b = unhex(src[i * 2 + 1]); if (!~a || !~b) return i; - buf[i] = a * 16 + b; + buf[i] = (a << 4) | b; } return i; diff --git a/test/parallel/test-buffer-badhex.js b/test/parallel/test-buffer-badhex.js new file mode 100644 index 00000000000000..3611ba3a09cdae --- /dev/null +++ b/test/parallel/test-buffer-badhex.js @@ -0,0 +1,43 @@ +'use strict'; +require('../common'); +const assert = require('assert'); +const Buffer = require('buffer').Buffer; + +// Test hex strings and bad hex strings +{ + const buf1 = Buffer.alloc(4); + assert.strictEqual(buf1.length, 4); + assert.deepStrictEqual(buf1, new Buffer([0, 0, 0, 0])); + assert.strictEqual(buf1.write('abcdxx', 0, 'hex'), 2); + assert.deepStrictEqual(buf1, new Buffer([0xab, 0xcd, 0x00, 0x00])); + assert.strictEqual(buf1.toString('hex'), 'abcd0000'); + assert.strictEqual(buf1.write('abcdef01', 0, 'hex'), 4); + assert.deepStrictEqual(buf1, new Buffer([0xab, 0xcd, 0xef, 0x01])); + assert.strictEqual(buf1.toString('hex'), 'abcdef01'); + + const buf2 = Buffer.from(buf1.toString('hex'), 'hex'); + assert.strictEqual(buf1.toString('hex'), buf2.toString('hex')); + + const buf3 = Buffer.alloc(5); + assert.strictEqual(buf3.write('abcdxx', 1, 'hex'), 2); + assert.strictEqual(buf3.toString('hex'), '00abcd0000'); + + const buf4 = Buffer.alloc(4); + assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0])); + assert.strictEqual(buf4.write('xxabcd', 0, 'hex'), 0); + assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0])); + assert.strictEqual(buf4.write('xxab', 1, 'hex'), 0); + assert.deepStrictEqual(buf4, new Buffer([0, 0, 0, 0])); + assert.strictEqual(buf4.write('cdxxab', 0, 'hex'), 1); + assert.deepStrictEqual(buf4, new Buffer([0xcd, 0, 0, 0])); + + const buf5 = Buffer.alloc(256); + for (let i = 0; i < 256; i++) + buf5[i] = i; + + const hex = buf5.toString('hex'); + assert.deepStrictEqual(Buffer.from(hex, 'hex'), buf5); + + const badHex = hex.slice(0, 256) + 'xx' + hex.slice(256, 510); + assert.deepStrictEqual(Buffer.from(badHex, 'hex'), buf5.slice(0, 128)); +} From aa045cd22656bf99f8ec0dc46bc2a79ec08265c4 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 13 Jul 2016 09:12:59 -0700 Subject: [PATCH 24/34] test: fix flaky test-http-server-consumed-timeout Using identical timeout values appears to have eliminated the flakiness in the test. Fixes: https://github.com/nodejs/node/issues/7643 PR-URL: https://github.com/nodejs/node/pull/7717 Reviewed-By: Fedor Indutny --- test/parallel/test-http-server-consumed-timeout.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/test/parallel/test-http-server-consumed-timeout.js b/test/parallel/test-http-server-consumed-timeout.js index 362b052ee78d58..799992e2c4a6ba 100644 --- a/test/parallel/test-http-server-consumed-timeout.js +++ b/test/parallel/test-http-server-consumed-timeout.js @@ -1,7 +1,6 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const http = require('http'); const server = http.createServer((req, res) => { @@ -11,7 +10,7 @@ const server = http.createServer((req, res) => { res.flushHeaders(); req.setTimeout(common.platformTimeout(200), () => { - assert(false, 'Should not happen'); + common.fail('Request timeout should not fire'); }); req.resume(); req.once('end', common.mustCall(() => { @@ -30,7 +29,7 @@ server.listen(0, common.mustCall(() => { setTimeout(() => { clearInterval(interval); req.end(); - }, common.platformTimeout(400)); + }, common.platformTimeout(200)); }); req.write('.'); })); From f7d3af67aadb50b20d4c1cb7e62adff184ce74f7 Mon Sep 17 00:00:00 2001 From: "Italo A. Casas" Date: Mon, 13 Jun 2016 10:32:44 -0400 Subject: [PATCH 25/34] doc: add `added:` information for stream Ref: https://github.com/nodejs/node/issues/6578 PR-URL: https://github.com/nodejs/node/pull/7287 Reviewed-By: Anna Henningsen Reviewed-By: Claudio Rodriguez --- doc/api/stream.md | 93 +++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 90 insertions(+), 3 deletions(-) diff --git a/doc/api/stream.md b/doc/api/stream.md index ad014a2a69b5bb..2afdbf51fa25c9 100644 --- a/doc/api/stream.md +++ b/doc/api/stream.md @@ -116,7 +116,7 @@ const server = http.createServer( (req, res) => { // req is an http.IncomingMessage, which is a Readable Stream // res is an http.ServerResponse, which is a Writable Stream - var body = ''; + let body = ''; // Get the data as utf8 strings. // If an encoding is not set, Buffer objects will be received. req.setEncoding('utf8'); @@ -205,10 +205,16 @@ myStream.end('done writing data'); ``` #### Class: stream.Writable + ##### Event: 'close' + The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates @@ -217,6 +223,9 @@ that no more events will be emitted, and no further computation will occur. Not all Writable streams will emit the `'close'` event. ##### Event: 'drain' + If a call to [`stream.write(chunk)`][stream-write] returns `false`, the `'drain'` event will be emitted when it is appropriate to resume writing data @@ -226,7 +235,7 @@ to the stream. // Write the data to the supplied writable stream one million times. // Be attentive to back-pressure. function writeOneMillionTimes(writer, data, encoding, callback) { - var i = 1000000; + let i = 1000000; write(); function write() { var ok = true; @@ -251,6 +260,9 @@ function writeOneMillionTimes(writer, data, encoding, callback) { ``` ##### Event: 'error' + * {Error} @@ -260,6 +272,9 @@ data. The listener callback is passed a single `Error` argument when called. *Note*: The stream is not closed when the `'error'` event is emitted. ##### Event: 'finish' + The `'finish'` event is emitted after the [`stream.end()`][stream-end] method has been called, and all data has been flushed to the underlying system. @@ -276,6 +291,9 @@ writer.on('finish', () => { ``` ##### Event: 'pipe' + * `src` {stream.Readable} source stream that is piping to this writable @@ -293,6 +311,9 @@ reader.pipe(writer); ``` ##### Event: 'unpipe' + * `src` {[Readable][] Stream} The source stream that [unpiped][`stream.unpipe()`] this writable @@ -313,6 +334,9 @@ reader.unpipe(writer); ``` ##### writable.cork() + The `writable.cork()` method forces all written data to be buffered in memory. The buffered data will be flushed when either the [`stream.uncork()`][] or @@ -325,6 +349,9 @@ implementations that implement the `writable._writev()` method can perform buffered writes in a more optimized manner. ##### writable.end([chunk][, encoding][, callback]) + * `chunk` {String|Buffer|any} Optional data to write. For streams not operating in object mode, `chunk` must be a string or a `Buffer`. For object mode @@ -350,6 +377,9 @@ file.end('world!'); ``` ##### writable.setDefaultEncoding(encoding) + * `encoding` {String} The new default encoding * Return: `this` @@ -358,6 +388,9 @@ The `writable.setDefaultEncoding()` method sets the default `encoding` for a [Writable][] stream. ##### writable.uncork() + The `writable.uncork()` method flushes all data buffered since [`stream.cork()`][] was called. @@ -391,6 +424,9 @@ process.nextTick(() => { ``` ##### writable.write(chunk[, encoding][, callback]) + * `chunk` {String|Buffer} The data to write * `encoding` {String} The encoding, if `chunk` is a String @@ -516,10 +552,16 @@ require more fine-grained control over the transfer and generation of data can use the [`EventEmitter`][] and `readable.pause()`/`readable.resume()` APIs. #### Class: stream.Readable + ##### Event: 'close' + The `'close'` event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates @@ -528,6 +570,9 @@ that no more events will be emitted, and no further computation will occur. Not all [Readable][] streams will emit the `'close'` event. ##### Event: 'data' + * `chunk` {Buffer|String|any} The chunk of data. For streams that are not operating in object mode, the chunk will be either a string or `Buffer`. @@ -558,6 +603,9 @@ readable.on('data', (chunk) => { ``` ##### Event: 'end' + The `'end'` event is emitted when there is no more data to be consumed from the stream. @@ -578,6 +626,9 @@ readable.on('end', () => { ``` ##### Event: 'error' + * {Error} @@ -589,6 +640,9 @@ to push an invalid chunk of data. The listener callback will be passed a single `Error` object. ##### Event: 'readable' + The `'readable'` event is emitted when there is data available to be read from the stream. In some cases, attaching a listener for the `'readable'` event will @@ -632,6 +686,9 @@ end preferred over the use of the `'readable'` event. ##### readable.isPaused() + * Return: {Boolean} @@ -651,6 +708,9 @@ readable.isPaused() // === false ``` ##### readable.pause() + * Return: `this` @@ -672,6 +732,9 @@ readable.on('data', (chunk) => { ``` ##### readable.pipe(destination[, options]) + * `destination` {stream.Writable} The destination for writing data * `options` {Object} Pipe options @@ -727,6 +790,9 @@ never closed until the Node.js process exits, regardless of the specified options. ##### readable.read([size]) + * `size` {Number} Optional argument to specify how much data to read. * Return {String|Buffer|Null} @@ -774,6 +840,9 @@ event will also be emitted. event has been emitted will return `null`. No runtime error will be raised. ##### readable.resume() + * Return: `this` @@ -793,6 +862,9 @@ getReadableStreamSomehow() ``` ##### readable.setEncoding(encoding) + * `encoding` {String} The encoding to use. * Return: `this` @@ -825,6 +897,9 @@ readable.on('data', (chunk) => { ``` ##### readable.unpipe([destination]) + * `destination` {stream.Writable} Optional specific stream to unpipe @@ -851,6 +926,9 @@ setTimeout(() => { ``` ##### readable.unshift(chunk) + * `chunk` {Buffer|String} Chunk of data to unshift onto the read queue @@ -911,6 +989,9 @@ appropriately, however it is best to simply avoid calling `readable.unshift()` while in the process of performing a read. ##### readable.wrap(stream) + * `stream` {Stream} An "old style" readable stream @@ -943,6 +1024,9 @@ myReader.on('readable', () => { ### Duplex and Transform Streams #### Class: stream.Duplex + @@ -956,6 +1040,9 @@ Examples of Duplex streams include: * [crypto streams][crypto] #### Class: stream.Transform + @@ -1579,7 +1666,7 @@ For Duplex streams, `objectMode` can be set exclusively for either the Readable or Writable side using the `readableObjectMode` and `writableObjectMode` options respectively. -In the following example, for instance, a new Transform stream (which is a +In the following example, for instance, a new Transform stream (which is a type of [Duplex][] stream) is created that has an object mode Writable side that accepts JavaScript numbers that are converted to hexidecimal strings on the Readable side. From 06bfb9e93c8643503d0c9bd9fceedc0a426e87ad Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 13 Jul 2016 16:06:18 +0200 Subject: [PATCH 26/34] src: fix handle leak in Buffer::New() Fix handle leaks in Buffer::New() and Buffer::Copy() by creating the handle scope before looking up the env with Environment::GetCurrent(). Environment::GetCurrent() calls v8::Isolate::GetCurrentContext(), which creates a handle in the current scope, i.e., the scope created by the caller of Buffer::New() or Buffer::Copy(). PR-URL: https://github.com/nodejs/node/pull/7711 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Trevor Norris --- src/node_buffer.cc | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 042f4219efeb6e..e9551eba8cca08 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -320,8 +320,8 @@ MaybeLocal New(Environment* env, size_t length) { MaybeLocal Copy(Isolate* isolate, const char* data, size_t length) { + EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); - EscapableHandleScope handle_scope(env->isolate()); Local obj; if (Buffer::Copy(env, data, length).ToLocal(&obj)) return handle_scope.Escape(obj); @@ -370,8 +370,8 @@ MaybeLocal New(Isolate* isolate, size_t length, FreeCallback callback, void* hint) { + EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); - EscapableHandleScope handle_scope(env->isolate()); Local obj; if (Buffer::New(env, data, length, callback, hint).ToLocal(&obj)) return handle_scope.Escape(obj); @@ -409,8 +409,8 @@ MaybeLocal New(Environment* env, MaybeLocal New(Isolate* isolate, char* data, size_t length) { + EscapableHandleScope handle_scope(isolate); Environment* env = Environment::GetCurrent(isolate); - EscapableHandleScope handle_scope(env->isolate()); Local obj; if (Buffer::New(env, data, length).ToLocal(&obj)) return handle_scope.Escape(obj); From 978362d3b652f7d4534e49dec6399e020f142f96 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 13 Jul 2016 16:16:40 +0200 Subject: [PATCH 27/34] src: fix handle leak in BuildStatsObject() Create a handle scope before performing a check that creates a handle, otherwise the handle is leaked into the handle scope of the caller. PR-URL: https://github.com/nodejs/node/pull/7711 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Trevor Norris --- src/node_file.cc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/node_file.cc b/src/node_file.cc index 968284788a4b72..1fdef68ca6129b 100644 --- a/src/node_file.cc +++ b/src/node_file.cc @@ -420,11 +420,11 @@ static void Close(const FunctionCallbackInfo& args) { Local BuildStatsObject(Environment* env, const uv_stat_t* s) { + EscapableHandleScope handle_scope(env->isolate()); + // If you hit this assertion, you forgot to enter the v8::Context first. CHECK_EQ(env->context(), env->isolate()->GetCurrentContext()); - EscapableHandleScope handle_scope(env->isolate()); - // The code below is very nasty-looking but it prevents a segmentation fault // when people run JS code like the snippet below. It's apparently more // common than you would expect, several people have reported this crash... From e46efd9244aafbd459212d56dea571154ce3adb0 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 13 Jul 2016 16:16:52 +0200 Subject: [PATCH 28/34] src: fix handle leak in UDPWrap::Instantiate() Create a handle scope before performing a check that creates a handle, otherwise the handle is leaked into the handle scope of the caller. PR-URL: https://github.com/nodejs/node/pull/7711 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Trevor Norris --- src/udp_wrap.cc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/udp_wrap.cc b/src/udp_wrap.cc index bd7aa418bd89cf..a0d8b1f7613b61 100644 --- a/src/udp_wrap.cc +++ b/src/udp_wrap.cc @@ -436,9 +436,9 @@ void UDPWrap::OnRecv(uv_udp_t* handle, Local UDPWrap::Instantiate(Environment* env, AsyncWrap* parent) { + EscapableHandleScope scope(env->isolate()); // If this assert fires then Initialize hasn't been called yet. CHECK_EQ(env->udp_constructor_function().IsEmpty(), false); - EscapableHandleScope scope(env->isolate()); Local ptr = External::New(env->isolate(), parent); return scope.Escape(env->udp_constructor_function() ->NewInstance(env->context(), 1, &ptr).ToLocalChecked()); From 61d88d959fdee1abc13ca6b1295aff0bc1f65d48 Mon Sep 17 00:00:00 2001 From: Ben Noordhuis Date: Wed, 13 Jul 2016 16:38:27 +0200 Subject: [PATCH 29/34] src: remove unnecessary HandleScopes API function callbacks run inside an implicit HandleScope. We don't need to explicitly create one and in fact introduce some unnecessary overhead when we do. PR-URL: https://github.com/nodejs/node/pull/7711 Reviewed-By: Anna Henningsen Reviewed-By: Colin Ihrig Reviewed-By: Trevor Norris --- src/node_crypto.cc | 7 ------- 1 file changed, 7 deletions(-) diff --git a/src/node_crypto.cc b/src/node_crypto.cc index a7964cde94ac54..2b85d1a60980dd 100644 --- a/src/node_crypto.cc +++ b/src/node_crypto.cc @@ -1822,8 +1822,6 @@ template void SSLWrap::SetOCSPResponse( const v8::FunctionCallbackInfo& args) { #ifdef NODE__HAVE_TLSEXT_STATUS_CB - HandleScope scope(args.GetIsolate()); - Base* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); Environment* env = w->env(); @@ -1842,8 +1840,6 @@ template void SSLWrap::RequestOCSP( const v8::FunctionCallbackInfo& args) { #ifdef NODE__HAVE_TLSEXT_STATUS_CB - HandleScope scope(args.GetIsolate()); - Base* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); @@ -1901,7 +1897,6 @@ void SSLWrap::GetEphemeralKeyInfo( template void SSLWrap::SetMaxSendFragment( const v8::FunctionCallbackInfo& args) { - HandleScope scope(args.GetIsolate()); CHECK(args.Length() >= 1 && args[0]->IsNumber()); Base* w; @@ -2204,7 +2199,6 @@ template void SSLWrap::GetALPNNegotiatedProto( const FunctionCallbackInfo& args) { #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation - HandleScope scope(args.GetIsolate()); Base* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); @@ -2226,7 +2220,6 @@ template void SSLWrap::SetALPNProtocols( const FunctionCallbackInfo& args) { #ifdef TLSEXT_TYPE_application_layer_protocol_negotiation - HandleScope scope(args.GetIsolate()); Base* w; ASSIGN_OR_RETURN_UNWRAP(&w, args.Holder()); Environment* env = w->env(); From 62a3ff27d07b157f193a9ffdf0a9de82960c70b3 Mon Sep 17 00:00:00 2001 From: "Hargobind S. Khalsa" Date: Sun, 17 Jul 2016 16:01:52 -0600 Subject: [PATCH 30/34] doc: correct sample output of buf.compare Comparing the buffers `ABC` and `ABCD` returns `-1` not `1`. PR-URL: https://github.com/nodejs/node/pull/7777 Reviewed-By: Colin Ihrig Reviewed-By: Anna Henningsen --- doc/api/buffer.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/api/buffer.md b/doc/api/buffer.md index 92908fd38b8177..413d5b7167da18 100644 --- a/doc/api/buffer.md +++ b/doc/api/buffer.md @@ -806,7 +806,7 @@ console.log(buf1.compare(buf1)); console.log(buf1.compare(buf2)); // Prints: -1 console.log(buf1.compare(buf3)); - // Prints: 1 + // Prints: -1 console.log(buf2.compare(buf1)); // Prints: 1 console.log(buf2.compare(buf3)); From 9d59b7d1f7a52ace4b49f7e0f0c668e18ff7d522 Mon Sep 17 00:00:00 2001 From: Gireesh Punathil Date: Wed, 13 Jul 2016 02:03:55 -0400 Subject: [PATCH 31/34] test: avoid usage of mixed IPV6 addresses The test case fails in AIX due to the mixed-use of unspecified and loopback addresses. This is not a problem in most platforms but fails in AIX. (In Windows too, but does not manifest as the test is omitted in Windows for a different reason). There exists no documented evidence which supports the mixed use of unspecified and loopback addresses. While AIX strictly follows the IPV6 specification with respect to unspecified address ('::') and loopback address ('::1'), the test case latches on to the behavior exhibited by other platforms, and hence it fails in AIX. The proposed fix is to make it work in all platforms including AIX by using the loopback address for the client to connect, as that is the address at which the server listens. Fixes: https://github.com/nodejs/node/issues/7563 PR-URL: https://github.com/nodejs/node/pull/7702 Reviewed-By: Michael Dawson Reviewed-By: Rich Trott Reviewed-By: Ben Noordhuis Reviewed-By: Colin Ihrig --- test/parallel/test-cluster-disconnect-handles.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/parallel/test-cluster-disconnect-handles.js b/test/parallel/test-cluster-disconnect-handles.js index 49b8218ab9c8d3..680e316cf0ba92 100644 --- a/test/parallel/test-cluster-disconnect-handles.js +++ b/test/parallel/test-cluster-disconnect-handles.js @@ -92,7 +92,7 @@ if (cluster.isMaster) { debugger; }; if (common.hasIPv6) - server.listen(cb); + server.listen(0, '::1', cb); else server.listen(0, common.localhostIPv4, cb); process.on('disconnect', process.exit); From 059a721ec5b940c8bbf09c312095f33f91d7a8b1 Mon Sep 17 00:00:00 2001 From: Rich Trott Date: Wed, 13 Jul 2016 15:30:08 -0700 Subject: [PATCH 32/34] doc: update CTC governance information MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update some outdated material. Provide some minor fixes. Wrap to 80 characters. PR-URL: https://github.com/nodejs/node/pull/7719 Reviewed-By: Rod Vagg Reviewed-By: Ben Noordhuis Reviewed-By: Jeremiah Senkpiel Reviewed-By: Michael Dawson Reviewed-By: Julien Gilli Reviewed-By: Colin Ihrig Reviewed-By: Ali Ijaz Sheikh Reviewed-By: Evan Lucas Reviewed-By: Fedor Indutny Reviewed-By: Сковорода Никита Андреевич Reviewed-By: Trevor Norris --- GOVERNANCE.md | 45 +++++++++++++++++++-------------------------- 1 file changed, 19 insertions(+), 26 deletions(-) diff --git a/GOVERNANCE.md b/GOVERNANCE.md index 06cec91e7db8b6..34b2f5fd1ec936 100644 --- a/GOVERNANCE.md +++ b/GOVERNANCE.md @@ -2,8 +2,8 @@ ## Core Technical Committee -The Node.js project is jointly governed by a Core Technical Committee (CTC) -which is responsible for high-level guidance of the project. +The Node.js project is governed by a Core Technical Committee (CTC) which is +responsible for high-level guidance of the project. The CTC has final authority over this project including: @@ -14,11 +14,6 @@ The CTC has final authority over this project including: * Conduct guidelines * Maintaining the list of additional Collaborators -Initial membership invitations to the CTC were given to individuals who -had been active contributors to Node.js, and who have significant -experience with the management of the Node.js project. Membership is -expected to evolve over time according to the needs of the project. - For the current list of CTC members, see the project [README.md](./README.md#current-project-team-members). @@ -46,8 +41,8 @@ responsibility for the change. In the case of pull requests proposed by an existing Collaborator, an additional Collaborator is required for sign-off. Consensus should be sought if additional Collaborators participate and there is disagreement around a particular -modification. See [Consensus Seeking Process](#consensus-seeking-process) below for further detail -on the consensus model used for governance. +modification. See [Consensus Seeking Process](#consensus-seeking-process) below +for further detail on the consensus model used for governance. Collaborators may opt to elevate significant or controversial modifications, or modifications that have not found consensus to the @@ -87,9 +82,8 @@ members affiliated with the over-represented employer(s). ## CTC Meetings -The CTC meets weekly on a Google Hangout On Air. The meeting is run by -a designated moderator approved by the CTC. Each meeting should be -published to YouTube. +The CTC meets weekly in a voice conference call. The meeting is run by a +designated moderator approved by the CTC. Each meeting is streamed on YouTube. Items are added to the CTC agenda which are considered contentious or are modifications of governance, contribution policy, CTC membership, @@ -100,20 +94,20 @@ That should happen continuously on GitHub and be handled by the larger group of Collaborators. Any community member or contributor can ask that something be added to -the next meeting's agenda by logging a GitHub Issue. Any Collaborator, +the next meeting's agenda by logging a GitHub issue. Any Collaborator, CTC member or the moderator can add the item to the agenda by adding the ***ctc-agenda*** tag to the issue. -Prior to each CTC meeting, the moderator will share the Agenda with -members of the CTC. CTC members can add any items they like to the -agenda at the beginning of each meeting. The moderator and the CTC -cannot veto or remove items. +Prior to each CTC meeting, the moderator will share the agenda with +members of the CTC. CTC members can also add items to the agenda at the +beginning of each meeting. The moderator and the CTC cannot veto or remove +items. The CTC may invite persons or representatives from certain projects to participate in a non-voting capacity. -The moderator is responsible for summarizing the discussion of each -agenda item and sending it as a pull request after the meeting. +The moderator is responsible for summarizing the discussion of each agenda item +and sending it as a pull request after the meeting. ## Consensus Seeking Process @@ -121,11 +115,10 @@ The CTC follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. -When an agenda item has appeared to reach a consensus, the moderator -will ask "Does anyone object?" as a final call for dissent from the -consensus. +When an agenda item has appeared to reach a consensus, the moderator will ask +"Does anyone object?" as a final call for dissent from the consensus. -If an agenda item cannot reach a consensus, a CTC member can call for -either a closing vote or a vote to table the issue to the next -meeting. The call for a vote must be approved by a majority of the CTC -or else the discussion will continue. Simple majority wins. +If an agenda item cannot reach a consensus, a CTC member can call for either a +closing vote or a vote to table the issue to the next meeting. The call for a +vote must be approved by a simple majority of the CTC or else the discussion +will continue. From f3182f6971c67a79ffe994135124675ae86c447b Mon Sep 17 00:00:00 2001 From: Ali Ijaz Sheikh Date: Fri, 15 Jul 2016 09:05:20 -0700 Subject: [PATCH 33/34] deps: v8_inspector no longer depends on wtf MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove wtf files as v8_inspector no longer needs them. Ref: https://github.com/nodejs/node/issues/7123 PR-URL: https://github.com/nodejs/node/pull/7751 Reviewed-By: Colin Ihrig Reviewed-By: Michaël Zasso Reviewed-By: Minwoo Jung --- deps/v8_inspector/deps/wtf/README.md | 1 - deps/v8_inspector/deps/wtf/wtf/Assertions.h | 40 --- deps/v8_inspector/deps/wtf/wtf/Compiler.h | 54 ---- deps/v8_inspector/deps/wtf/wtf/PtrUtil.h | 275 -------------------- 4 files changed, 370 deletions(-) delete mode 100644 deps/v8_inspector/deps/wtf/README.md delete mode 100644 deps/v8_inspector/deps/wtf/wtf/Assertions.h delete mode 100644 deps/v8_inspector/deps/wtf/wtf/Compiler.h delete mode 100644 deps/v8_inspector/deps/wtf/wtf/PtrUtil.h diff --git a/deps/v8_inspector/deps/wtf/README.md b/deps/v8_inspector/deps/wtf/README.md deleted file mode 100644 index 6fe75ce24cd74a..00000000000000 --- a/deps/v8_inspector/deps/wtf/README.md +++ /dev/null @@ -1 +0,0 @@ -# wtf diff --git a/deps/v8_inspector/deps/wtf/wtf/Assertions.h b/deps/v8_inspector/deps/wtf/wtf/Assertions.h deleted file mode 100644 index 18f21cacb740f0..00000000000000 --- a/deps/v8_inspector/deps/wtf/wtf/Assertions.h +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2003, 2006, 2007 Apple Inc. All rights reserved. - * Copyright (C) 2013 Google Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WTF_Assertions_h -#define WTF_Assertions_h - -#ifndef CHECK -#define CHECK(condition) ((void) 0) -#endif -#define DCHECK(condition) ((void) 0) -#define NOTREACHED() -#define DCHECK_GE(i, j) DCHECK(i >= j) - -template -inline void USE(T) { } - -#endif /* WTF_Assertions_h */ diff --git a/deps/v8_inspector/deps/wtf/wtf/Compiler.h b/deps/v8_inspector/deps/wtf/wtf/Compiler.h deleted file mode 100644 index 61926a054fa1b9..00000000000000 --- a/deps/v8_inspector/deps/wtf/wtf/Compiler.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2011, 2012 Apple Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY - * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE - * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -#ifndef WTF_Compiler_h -#define WTF_Compiler_h - -/* COMPILER() - the compiler being used to build the project */ -#define COMPILER(WTF_FEATURE) (defined WTF_COMPILER_##WTF_FEATURE && WTF_COMPILER_##WTF_FEATURE) - -/* ==== COMPILER() - the compiler being used to build the project ==== */ - -/* COMPILER(CLANG) - Clang */ -#if defined(__clang__) -#define WTF_COMPILER_CLANG 1 -#endif - -/* COMPILER(MSVC) - Microsoft Visual C++ (and Clang when compiling for Windows). */ -#if defined(_MSC_VER) -#define WTF_COMPILER_MSVC 1 -#endif - -/* COMPILER(GCC) - GNU Compiler Collection (and Clang when compiling for platforms other than Windows). */ -#if defined(__GNUC__) -#define WTF_COMPILER_GCC 1 -#define GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) -#define GCC_VERSION_AT_LEAST(major, minor, patch) (GCC_VERSION >= (major * 10000 + minor * 100 + patch)) -#else -/* Define this for !GCC compilers, just so we can write things like GCC_VERSION_AT_LEAST(4, 1, 0). */ -#define GCC_VERSION_AT_LEAST(major, minor, patch) 0 -#endif - -#endif /* WTF_Compiler_h */ diff --git a/deps/v8_inspector/deps/wtf/wtf/PtrUtil.h b/deps/v8_inspector/deps/wtf/wtf/PtrUtil.h deleted file mode 100644 index 0d5a7fdd810141..00000000000000 --- a/deps/v8_inspector/deps/wtf/wtf/PtrUtil.h +++ /dev/null @@ -1,275 +0,0 @@ -/* - * Copyright (C) 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved. - * Copyright (C) 2013 Intel Corporation. All rights reserved. - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Library General Public - * License as published by the Free Software Foundation; either - * version 2 of the License, or (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Library General Public License for more details. - * - * You should have received a copy of the GNU Library General Public License - * along with this library; see the file COPYING.LIB. If not, write to - * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, - * Boston, MA 02110-1301, USA. - * - */ - -#ifndef WTF_PtrUtil_h -#define WTF_PtrUtil_h - -#include "wtf/Assertions.h" -#include - -#if defined(__APPLE__) && !defined(_LIBCPP_VERSION) - -namespace std { - -template -struct is_convertible -{ -private: - struct True_ { char x[2]; }; - struct False_ { }; - - static True_ helper(T2 const &); - static False_ helper(...); - -public: - static bool const value = ( - sizeof(True_) == sizeof(is_convertible::helper(T1())) - ); -}; - -template -struct enable_if {}; - -template -struct enable_if -{ - typedef T type; -}; - -template -struct remove_extent { typedef T type; }; - -template -struct remove_extent { typedef T type; }; - -template -struct remove_extent { typedef T type;}; - -typedef decltype(nullptr) nullptr_t; - -template -struct integral_constant { - static constexpr T value = v; - typedef T value_type; - typedef integral_constant type; - constexpr operator value_type() const noexcept { return value; } - constexpr value_type operator()() const noexcept { return value; } //since c++14 -}; - -typedef integral_constant true_type; -typedef integral_constant false_type; - -template -struct is_array : false_type {}; - -template -struct is_array : true_type {}; - -template -struct is_array : true_type {}; - -template -struct OwnedPtrDeleter { - static void deletePtr(T* ptr) - { - static_assert(sizeof(T) > 0, "type must be complete"); - delete ptr; - } -}; - -template -struct OwnedPtrDeleter { - static void deletePtr(T* ptr) - { - static_assert(sizeof(T) > 0, "type must be complete"); - delete[] ptr; - } -}; - -template -struct OwnedPtrDeleter { - static_assert(sizeof(T) < 0, "do not use array with size as type"); -}; - - -template class unique_ptr { -public: - typedef typename remove_extent::type ValueType; - typedef ValueType* PtrType; - - unique_ptr() : m_ptr(nullptr) {} - unique_ptr(std::nullptr_t) : m_ptr(nullptr) {} - unique_ptr(unique_ptr&&); - template ::value>::type> unique_ptr(unique_ptr&&); - - ~unique_ptr() - { - OwnedPtrDeleter::deletePtr(m_ptr); - m_ptr = nullptr; - } - - PtrType get() const { return m_ptr; } - - void reset(PtrType ptr = nullptr); - PtrType release(); - - ValueType& operator*() const { DCHECK(m_ptr); return *m_ptr; } - PtrType operator->() const { DCHECK(m_ptr); return m_ptr; } - - ValueType& operator[](std::ptrdiff_t i) const; - - bool operator!() const { return !m_ptr; } - explicit operator bool() const { return m_ptr; } - - unique_ptr& operator=(std::nullptr_t) { reset(); return *this; } - - - unique_ptr& operator=(unique_ptr&&); - template unique_ptr& operator=(unique_ptr&&); - - void swap(unique_ptr& o) { std::swap(m_ptr, o.m_ptr); } - - static T* hashTableDeletedValue() { return reinterpret_cast(-1); } - - explicit unique_ptr(PtrType ptr) : m_ptr(ptr) {} - -private: - - // We should never have two unique_ptrs for the same underlying object - // (otherwise we'll get double-destruction), so these equality operators - // should never be needed. - template bool operator==(const unique_ptr&) const - { - static_assert(!sizeof(U*), "unique_ptrs should never be equal"); - return false; - } - template bool operator!=(const unique_ptr&) const - { - static_assert(!sizeof(U*), "unique_ptrs should never be equal"); - return false; - } - - PtrType m_ptr; -}; - - -template inline void unique_ptr::reset(PtrType ptr) -{ - PtrType p = m_ptr; - m_ptr = ptr; - OwnedPtrDeleter::deletePtr(p); -} - -template inline typename unique_ptr::PtrType unique_ptr::release() -{ - PtrType ptr = m_ptr; - m_ptr = nullptr; - return ptr; -} - -template inline typename unique_ptr::ValueType& unique_ptr::operator[](std::ptrdiff_t i) const -{ - static_assert(is_array::value, "elements access is possible for arrays only"); - DCHECK(m_ptr); - DCHECK(i >= 0); - return m_ptr[i]; -} - -template inline unique_ptr::unique_ptr(unique_ptr&& o) - : m_ptr(o.release()) -{ -} - -template -template inline unique_ptr::unique_ptr(unique_ptr&& o) - : m_ptr(o.release()) -{ - static_assert(!is_array::value, "pointers to array must never be converted"); -} - -template inline unique_ptr& unique_ptr::operator=(unique_ptr&& o) -{ - PtrType ptr = m_ptr; - m_ptr = o.release(); - DCHECK(!ptr || m_ptr != ptr); - OwnedPtrDeleter::deletePtr(ptr); - - return *this; -} - -template -template inline unique_ptr& unique_ptr::operator=(unique_ptr&& o) -{ - static_assert(!is_array::value, "pointers to array must never be converted"); - PtrType ptr = m_ptr; - m_ptr = o.release(); - DCHECK(!ptr || m_ptr != ptr); - OwnedPtrDeleter::deletePtr(ptr); - - return *this; -} - -template inline void swap(unique_ptr& a, unique_ptr& b) -{ - a.swap(b); -} - -template inline bool operator==(const unique_ptr& a, U* b) -{ - return a.get() == b; -} - -template inline bool operator==(T* a, const unique_ptr& b) -{ - return a == b.get(); -} - -template inline bool operator!=(const unique_ptr& a, U* b) -{ - return a.get() != b; -} - -template inline bool operator!=(T* a, const unique_ptr& b) -{ - return a != b.get(); -} - -template inline typename unique_ptr::PtrType getPtr(const unique_ptr& p) -{ - return p.get(); -} - -template -unique_ptr move(unique_ptr& ptr) -{ - return unique_ptr(ptr.release()); -} - -} - -#endif - -template -std::unique_ptr wrapUnique(T* ptr) { - return std::unique_ptr(ptr); -} - -#endif // WTF_PtrUtil_h From cd4eb32334c75bd829e8e195f66f35af6bbe7a3f Mon Sep 17 00:00:00 2001 From: cjihrig Date: Fri, 15 Jul 2016 15:43:24 -0400 Subject: [PATCH 34/34] test: use mustCall() for simple flow tracking Many of the tests use variables to track when callback functions are invoked or events are emitted. These variables are then asserted on process exit. This commit replaces this pattern in straightforward cases with common.mustCall(). This makes the tests easier to reason about, leads to a net reduction in lines of code, and uncovered a few bugs in tests. This commit also replaces some callbacks that should never be called with common.fail(). PR-URL: https://github.com/nodejs/node/pull/7753 Reviewed-By: Wyatt Preul Reviewed-By: Minwoo Jung Reviewed-By: Ben Noordhuis Conflicts: test/parallel/test-file-read-noexist.js --- test/addons/async-hello-world/test.js | 15 +-- test/internet/test-http-dns-fail.js | 8 +- .../internet/test-http-https-default-ports.js | 19 +--- test/internet/test-net-connect-timeout.js | 23 +--- test/internet/test-net-connect-unref.js | 19 +--- test/parallel/test-child-process-buffering.js | 21 +--- .../parallel/test-child-process-disconnect.js | 14 +-- .../test-child-process-exec-buffer.js | 21 +--- test/parallel/test-child-process-exec-cwd.js | 25 +--- .../parallel/test-child-process-exec-error.js | 11 +- test/parallel/test-child-process-exit-code.js | 19 +--- .../test-child-process-fork-and-spawn.js | 16 +-- .../parallel/test-child-process-fork-close.js | 18 +-- test/parallel/test-child-process-fork.js | 13 +-- test/parallel/test-child-process-internal.js | 21 ++-- test/parallel/test-child-process-kill.js | 37 ++---- .../test-child-process-set-blocking.js | 12 +- .../test-child-process-spawn-error.js | 11 +- test/parallel/test-child-process-stdin-ipc.js | 13 +-- test/parallel/test-child-process-stdin.js | 29 +---- test/parallel/test-cluster-http-pipe.js | 9 +- test/parallel/test-cluster-listening-port.js | 11 +- test/parallel/test-cluster-net-listen.js | 9 +- .../test-cluster-setup-master-emit.js | 29 ++--- .../test-cluster-uncaught-exception.js | 14 +-- test/parallel/test-cluster-worker-death.js | 18 +-- test/parallel/test-cluster-worker-destroy.js | 33 +----- .../test-cluster-worker-forced-exit.js | 20 +--- test/parallel/test-crypto-domains.js | 10 +- test/parallel/test-crypto-hash-stream-pipe.js | 11 +- test/parallel/test-delayed-require.js | 16 +-- .../test-dgram-close-is-not-callback.js | 11 +- test/parallel/test-dgram-close.js | 19 +--- test/parallel/test-dgram-implicit-bind.js | 11 +- test/parallel/test-dgram-unref.js | 14 +-- test/parallel/test-domain-implicit-fs.js | 16 +-- test/parallel/test-domain-timers.js | 24 ++-- test/parallel/test-error-reporting.js | 37 +++--- test/parallel/test-eval.js | 22 +--- .../test-event-emitter-max-listeners.js | 13 +-- ...mitter-no-error-provided-to-error-event.js | 14 +-- test/parallel/test-event-emitter-once.js | 25 +--- test/parallel/test-event-emitter-subclass.js | 8 +- test/parallel/test-exception-handler.js | 18 +-- test/parallel/test-file-read-noexist.js | 17 +-- test/parallel/test-fs-exists.js | 21 ++-- test/parallel/test-fs-long-path.js | 14 +-- test/parallel/test-fs-open.js | 20 +--- test/parallel/test-fs-read-buffer.js | 20 ++-- test/parallel/test-fs-read.js | 21 ++-- test/parallel/test-fs-readfile-error.js | 16 +-- .../test-fs-readfile-zero-byte-liar.js | 13 +-- test/parallel/test-fs-realpath.js | 11 +- test/parallel/test-fs-stat.js | 107 +++++++----------- test/parallel/test-fs-stream-double-close.js | 19 +--- .../test-fs-symlink-dir-junction-relative.js | 12 +- test/parallel/test-fs-symlink-dir-junction.js | 27 ++--- test/parallel/test-fs-truncate-fd.js | 8 +- test/parallel/test-fs-truncate.js | 16 +-- test/parallel/test-fs-write-buffer.js | 35 +++--- test/parallel/test-fs-write-file.js | 62 ++++------ test/parallel/test-fs-write-string-coerce.js | 17 +-- test/parallel/test-fs-write.js | 31 +++-- test/parallel/test-http-abort-before-end.js | 6 +- test/parallel/test-http-abort-client.js | 23 +--- test/parallel/test-http-agent-no-protocol.js | 22 +--- test/parallel/test-http-agent-null.js | 22 +--- test/parallel/test-http-bind-twice.js | 27 ++--- test/parallel/test-http-blank-header.js | 14 +-- test/parallel/test-http-buffer-sanity.js | 18 ++- test/parallel/test-http-byteswritten.js | 17 +-- test/parallel/test-http-client-abort-event.js | 23 ++-- test/parallel/test-http-client-get-url.js | 13 +-- test/parallel/test-http-client-readable.js | 12 +- .../test-http-client-response-domain.js | 12 +- test/parallel/test-http-client-upload-buf.js | 36 +++--- test/parallel/test-http-client-upload.js | 37 +++--- test/parallel/test-http-conn-reset.js | 16 +-- test/parallel/test-http-connect-req-res.js | 8 +- test/parallel/test-http-connect.js | 10 +- .../test-http-end-throw-socket-handling.js | 10 +- test/parallel/test-http-extra-response.js | 24 ++-- test/parallel/test-http-full-response.js | 25 ++-- test/parallel/test-http-head-request.js | 22 ++-- ...test-http-head-response-has-no-body-end.js | 23 ++-- .../test-http-head-response-has-no-body.js | 23 ++-- test/parallel/test-http-hex-write.js | 35 +++--- test/parallel/test-http-legacy.js | 24 ++-- .../test-http-localaddress-bind-error.js | 15 +-- test/parallel/test-http-multi-line-headers.js | 20 ++-- test/parallel/test-http-no-content-length.js | 23 ++-- .../test-http-pause-resume-one-end.js | 29 ++--- test/parallel/test-http-pipe-fs.js | 11 +- test/parallel/test-http-pipeline-flood.js | 10 +- test/parallel/test-http-request-end.js | 8 +- test/parallel/test-http-request-methods.js | 28 ++--- .../parallel/test-http-res-write-after-end.js | 19 +--- test/parallel/test-http-response-close.js | 25 ++-- .../parallel/test-http-response-no-headers.js | 21 ++-- test/parallel/test-http-unix-socket.js | 26 +---- test/parallel/test-http-upgrade-agent.js | 21 +--- test/parallel/test-http-upgrade-client.js | 16 +-- test/parallel/test-http-upgrade-client2.js | 24 ++-- test/parallel/test-http-upgrade-server2.js | 13 +-- test/parallel/test-http-wget.js | 30 ++--- test/parallel/test-http-write-empty-string.js | 21 ++-- .../test-https-agent-session-eviction.js | 5 +- .../test-https-client-checkServerIdentity.js | 15 +-- test/parallel/test-https-client-get-url.js | 11 +- test/parallel/test-https-client-reject.js | 19 +--- test/parallel/test-https-client-resume.js | 11 +- .../parallel/test-https-connecting-to-http.js | 35 +----- test/parallel/test-https-eof-for-eom.js | 28 ++--- test/parallel/test-https-foafssl.js | 37 +++--- .../test-https-localaddress-bind-error.js | 15 +-- test/parallel/test-https-pfx.js | 20 ++-- test/parallel/test-https-req-split.js | 13 +-- .../parallel/test-https-set-timeout-server.js | 90 +++++---------- test/parallel/test-https-timeout-server.js | 11 +- test/parallel/test-listen-fd-ebadf.js | 13 +-- test/parallel/test-net-after-close.js | 16 +-- test/parallel/test-net-bind-twice.js | 27 ++--- test/parallel/test-net-can-reset-timeout.js | 21 +--- .../test-net-connect-handle-econnrefused.js | 11 +- test/parallel/test-net-connect-options.js | 30 ++--- test/parallel/test-net-dns-custom-lookup.js | 14 +-- test/parallel/test-net-dns-error.js | 14 +-- test/parallel/test-net-dns-lookup.js | 16 +-- test/parallel/test-net-during-close.js | 12 +- test/parallel/test-net-large-string.js | 18 ++- ...n-close-server-callback-is-not-function.js | 10 +- test/parallel/test-net-listen-close-server.js | 12 +- test/parallel/test-net-listen-error.js | 17 +-- test/parallel/test-net-local-address-port.js | 11 +- .../test-net-pause-resume-connecting.js | 12 +- test/parallel/test-net-pipe-connect-errors.js | 17 +-- test/parallel/test-net-remote-address-port.js | 11 +- .../test-net-server-unref-persistent.js | 13 +-- test/parallel/test-net-server-unref.js | 14 +-- .../parallel/test-net-socket-destroy-twice.js | 18 +-- test/parallel/test-net-socket-timeout.js | 15 +-- test/parallel/test-net-write-after-close.js | 28 ++--- test/parallel/test-net-write-connect-write.js | 19 ++-- test/parallel/test-net-write-slow.js | 13 +-- test/parallel/test-next-tick.js | 35 ++---- test/parallel/test-pipe-address.js | 17 +-- test/parallel/test-pipe-head.js | 12 +- test/parallel/test-pipe-unref.js | 12 +- test/parallel/test-process-next-tick.js | 14 +-- ...est-process-remove-all-signal-listeners.js | 13 +-- test/parallel/test-regress-GH-1531.js | 17 +-- test/parallel/test-regress-GH-3542.js | 10 +- test/parallel/test-regress-GH-746.js | 15 +-- test/parallel/test-sigint-infinite-loop.js | 10 +- test/parallel/test-signal-handler.js | 24 +--- test/parallel/test-socket-write-after-fin.js | 41 +++---- test/parallel/test-stdout-close-unref.js | 11 +- test/parallel/test-stdout-stderr-reading.js | 17 +-- test/parallel/test-stdout-to-file.js | 14 +-- test/parallel/test-stream-end-paused.js | 12 +- .../test-stream-pipe-error-handling.js | 8 +- test/parallel/test-stream-wrap.js | 12 +- .../test-stream2-httpclient-response-end.js | 20 +--- .../parallel/test-stream2-large-read-stall.js | 9 +- test/parallel/test-stream2-read-sync-stack.js | 13 +-- .../test-stream2-readable-legacy-drain.js | 18 +-- .../test-stream2-readable-non-empty-end.js | 11 +- .../test-stream2-readable-wrap-empty.js | 10 +- test/parallel/test-tls-0-dns-altname.js | 15 +-- test/parallel/test-tls-cert-regression.js | 14 +-- test/parallel/test-tls-client-abort2.js | 15 +-- test/parallel/test-tls-client-destroy-soon.js | 27 ++--- test/parallel/test-tls-client-reject.js | 23 +--- test/parallel/test-tls-client-resume.js | 11 +- test/parallel/test-tls-close-error.js | 24 +--- test/parallel/test-tls-close-notify.js | 20 +--- test/parallel/test-tls-connect-pipe.js | 23 +--- test/parallel/test-tls-connect.js | 24 +--- .../parallel/test-tls-delayed-attach-error.js | 18 +-- test/parallel/test-tls-ecdh-disable.js | 11 +- test/parallel/test-tls-ecdh.js | 22 ++-- test/parallel/test-tls-getcipher.js | 11 +- test/parallel/test-tls-handshake-error.js | 24 ++-- test/parallel/test-tls-invoke-queued.js | 20 ++-- test/parallel/test-tls-legacy-onselect.js | 15 +-- test/parallel/test-tls-max-send-fragment.js | 20 ++-- test/parallel/test-tls-no-rsa-key.js | 18 +-- test/parallel/test-tls-passphrase.js | 13 +-- .../test-tls-peer-certificate-encoding.js | 14 +-- .../test-tls-peer-certificate-multi-keys.js | 14 +-- test/parallel/test-tls-peer-certificate.js | 14 +-- test/parallel/test-tls-request-timeout.js | 15 +-- test/parallel/test-tls-securepair-server.js | 19 ++-- test/parallel/test-tls-set-ciphers.js | 7 +- test/parallel/test-tls-set-encoding.js | 11 +- test/parallel/test-tls-timeout-server.js | 12 +- test/parallel/test-tls-zero-clear-in.js | 16 +-- test/parallel/test-zerolengthbufferbug.js | 25 +--- test/parallel/test-zlib-close-after-write.js | 17 +-- test/parallel/test-zlib-random-byte-pipes.js | 10 +- test/parallel/test-zlib-write-after-close.js | 16 +-- test/parallel/test-zlib-zero-byte.js | 22 +--- test/pummel/test-http-client-reconnect-bug.js | 28 +---- test/pummel/test-https-large-response.js | 33 ++---- test/pummel/test-net-pingpong-delay.js | 16 +-- test/pummel/test-net-timeout2.js | 14 +-- test/pummel/test-timer-wrap.js | 11 +- test/pummel/test-timers.js | 9 +- test/pummel/test-tls-server-large-request.js | 21 +--- test/pummel/test-tls-throttle.js | 9 +- test/sequential/test-net-GH-5504.js | 26 +---- test/sequential/test-regress-GH-4027.js | 10 +- test/sequential/test-util-debug.js | 12 +- 213 files changed, 1101 insertions(+), 2881 deletions(-) diff --git a/test/addons/async-hello-world/test.js b/test/addons/async-hello-world/test.js index 14b80b711b9b35..2ed003e4445d5d 100644 --- a/test/addons/async-hello-world/test.js +++ b/test/addons/async-hello-world/test.js @@ -1,17 +1,10 @@ 'use strict'; -require('../../common'); +const common = require('../../common'); var assert = require('assert'); var binding = require('./build/Release/binding'); -var called = false; -process.on('exit', function() { - assert(called); -}); - -binding(5, function(err, val) { +binding(5, common.mustCall(function(err, val) { assert.equal(null, err); assert.equal(10, val); - process.nextTick(function() { - called = true; - }); -}); + process.nextTick(common.mustCall(function() {})); +})); diff --git a/test/internet/test-http-dns-fail.js b/test/internet/test-http-dns-fail.js index 7e2f8cd402d658..c83b89f8ccd37e 100644 --- a/test/internet/test-http-dns-fail.js +++ b/test/internet/test-http-dns-fail.js @@ -4,11 +4,10 @@ * should trigger the error event after each attempt. */ -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); -var resDespiteError = false; var hadError = 0; function httpreq(count) { @@ -19,9 +18,7 @@ function httpreq(count) { port: 80, path: '/', method: 'GET' - }, function(res) { - resDespiteError = true; - }); + }, common.fail); req.on('error', function(e) { console.log(e.message); @@ -37,6 +34,5 @@ httpreq(0); process.on('exit', function() { - assert.equal(false, resDespiteError); assert.equal(2, hadError); }); diff --git a/test/internet/test-http-https-default-ports.js b/test/internet/test-http-https-default-ports.js index 33d5436733f545..8b00e434e9cba6 100644 --- a/test/internet/test-http-https-default-ports.js +++ b/test/internet/test-http-https-default-ports.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -9,21 +8,11 @@ if (!common.hasCrypto) { var https = require('https'); var http = require('http'); -var gotHttpsResp = false; -var gotHttpResp = false; -process.on('exit', function() { - assert(gotHttpsResp); - assert(gotHttpResp); - console.log('ok'); -}); - -https.get('https://www.google.com/', function(res) { - gotHttpsResp = true; +https.get('https://www.google.com/', common.mustCall(function(res) { res.resume(); -}); +})); -http.get('http://www.google.com/', function(res) { - gotHttpResp = true; +http.get('http://www.google.com/', common.mustCall(function(res) { res.resume(); -}); +})); diff --git a/test/internet/test-net-connect-timeout.js b/test/internet/test-net-connect-timeout.js index fd78a2936bd88b..0f58622aa19912 100644 --- a/test/internet/test-net-connect-timeout.js +++ b/test/internet/test-net-connect-timeout.js @@ -3,16 +3,12 @@ // https://groups.google.com/forum/#!topic/nodejs/UE0ZbfLt6t8 // https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw -require('../common'); +const common = require('../common'); var net = require('net'); var assert = require('assert'); var start = new Date(); -var gotTimeout = false; - -var gotConnect = false; - var T = 100; // 192.0.2.1 is part of subnet assigned as "TEST-NET" in RFC 5737. @@ -23,22 +19,11 @@ var socket = net.createConnection(9999, '192.0.2.1'); socket.setTimeout(T); -socket.on('timeout', function() { +socket.on('timeout', common.mustCall(function() { console.error('timeout'); - gotTimeout = true; var now = new Date(); assert.ok(now - start < T + 500); socket.destroy(); -}); - -socket.on('connect', function() { - console.error('connect'); - gotConnect = true; - socket.destroy(); -}); - +})); -process.on('exit', function() { - assert.ok(gotTimeout); - assert.ok(!gotConnect); -}); +socket.on('connect', common.fail); diff --git a/test/internet/test-net-connect-unref.js b/test/internet/test-net-connect-unref.js index ad24683b34d49e..52929d2152774d 100644 --- a/test/internet/test-net-connect-unref.js +++ b/test/internet/test-net-connect-unref.js @@ -1,25 +1,14 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var net = require('net'); -var client, killed = false, ended = false; +var client; var TIMEOUT = 10 * 1000; client = net.createConnection(53, '8.8.8.8', function() { client.unref(); }); -client.on('close', function() { - ended = true; -}); - -setTimeout(function() { - killed = true; - client.end(); -}, TIMEOUT).unref(); +client.on('close', common.fail); -process.on('exit', function() { - assert.strictEqual(killed, false, 'A client should have connected'); - assert.strictEqual(ended, false, 'A client should stay connected'); -}); +setTimeout(common.fail, TIMEOUT).unref(); diff --git a/test/parallel/test-child-process-buffering.js b/test/parallel/test-child-process-buffering.js index 1efa5a65f9cea8..29ea8b5c4563c9 100644 --- a/test/parallel/test-child-process-buffering.js +++ b/test/parallel/test-child-process-buffering.js @@ -2,10 +2,6 @@ var common = require('../common'); var assert = require('assert'); -var pwd_called = false; -var childClosed = false; -var childExited = false; - function pwd(callback) { var output = ''; var child = common.spawnPwd(); @@ -16,17 +12,14 @@ function pwd(callback) { output += s; }); - child.on('exit', function(c) { + child.on('exit', common.mustCall(function(c) { console.log('exit: ' + c); assert.equal(0, c); - childExited = true; - }); + })); - child.on('close', function() { + child.on('close', common.mustCall(function() { callback(output); - pwd_called = true; - childClosed = true; - }); + })); } @@ -35,9 +28,3 @@ pwd(function(result) { assert.equal(true, result.length > 1); assert.equal('\n', result[result.length - 1]); }); - -process.on('exit', function() { - assert.equal(true, pwd_called); - assert.equal(true, childExited); - assert.equal(true, childClosed); -}); diff --git a/test/parallel/test-child-process-disconnect.js b/test/parallel/test-child-process-disconnect.js index 4ef95a3732e3bd..ad63cbb78bad8e 100644 --- a/test/parallel/test-child-process-disconnect.js +++ b/test/parallel/test-child-process-disconnect.js @@ -48,21 +48,16 @@ if (process.argv[2] === 'child') { var child = fork(process.argv[1], ['child']); var childFlag = false; - var childSelfTerminate = false; - var parentEmit = false; var parentFlag = false; // when calling .disconnect the event should emit // and the disconnected flag should be true. - child.on('disconnect', function() { - parentEmit = true; + child.on('disconnect', common.mustCall(function() { parentFlag = child.connected; - }); + })); // the process should also self terminate without using signals - child.on('exit', function() { - childSelfTerminate = true; - }); + child.on('exit', common.mustCall(function() {})); // when child is listening child.on('message', function(obj) { @@ -91,8 +86,5 @@ if (process.argv[2] === 'child') { process.on('exit', function() { assert.equal(childFlag, false); assert.equal(parentFlag, false); - - assert.ok(childSelfTerminate); - assert.ok(parentEmit); }); } diff --git a/test/parallel/test-child-process-exec-buffer.js b/test/parallel/test-child-process-exec-buffer.js index 6f19ac859a783f..47879c05b2ce97 100644 --- a/test/parallel/test-child-process-exec-buffer.js +++ b/test/parallel/test-child-process-exec-buffer.js @@ -1,33 +1,22 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; var os = require('os'); - -var success_count = 0; - var str = 'hello'; // default encoding -exec('echo ' + str, function(err, stdout, stderr) { +exec('echo ' + str, common.mustCall(function(err, stdout, stderr) { assert.ok('string', typeof stdout, 'Expected stdout to be a string'); assert.ok('string', typeof stderr, 'Expected stderr to be a string'); assert.equal(str + os.EOL, stdout); - - success_count++; -}); +})); // no encoding (Buffers expected) exec('echo ' + str, { encoding: null -}, function(err, stdout, stderr) { +}, common.mustCall(function(err, stdout, stderr) { assert.ok(stdout instanceof Buffer, 'Expected stdout to be a Buffer'); assert.ok(stderr instanceof Buffer, 'Expected stderr to be a Buffer'); assert.equal(str + os.EOL, stdout.toString()); - - success_count++; -}); - -process.on('exit', function() { - assert.equal(2, success_count); -}); +})); diff --git a/test/parallel/test-child-process-exec-cwd.js b/test/parallel/test-child-process-exec-cwd.js index c259ffffda3dee..b1a24aca761458 100644 --- a/test/parallel/test-child-process-exec-cwd.js +++ b/test/parallel/test-child-process-exec-cwd.js @@ -3,9 +3,6 @@ const common = require('../common'); var assert = require('assert'); var exec = require('child_process').exec; -var success_count = 0; -var error_count = 0; - var pwdcommand, dir; if (common.isWindows) { @@ -16,21 +13,7 @@ if (common.isWindows) { dir = '/dev'; } -exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { - if (err) { - error_count++; - console.log('error!: ' + err.code); - console.log('stdout: ' + JSON.stringify(stdout)); - console.log('stderr: ' + JSON.stringify(stderr)); - assert.equal(false, err.killed); - } else { - success_count++; - console.log(stdout); - assert.ok(stdout.indexOf(dir) == 0); - } -}); - -process.on('exit', function() { - assert.equal(1, success_count); - assert.equal(0, error_count); -}); +exec(pwdcommand, {cwd: dir}, common.mustCall(function(err, stdout, stderr) { + assert.ifError(err); + assert.ok(stdout.indexOf(dir) == 0); +})); diff --git a/test/parallel/test-child-process-exec-error.js b/test/parallel/test-child-process-exec-error.js index 416eb165147b15..006a2eebb912d0 100644 --- a/test/parallel/test-child-process-exec-error.js +++ b/test/parallel/test-child-process-exec-error.js @@ -4,17 +4,10 @@ var assert = require('assert'); var child_process = require('child_process'); function test(fun, code) { - var errors = 0; - - fun('does-not-exist', function(err) { + fun('does-not-exist', common.mustCall(function(err) { assert.equal(err.code, code); assert(/does\-not\-exist/.test(err.cmd)); - errors++; - }); - - process.on('exit', function() { - assert.equal(errors, 1); - }); + })); } if (common.isWindows) { diff --git a/test/parallel/test-child-process-exit-code.js b/test/parallel/test-child-process-exit-code.js index 0ccbb46a91562c..3a393f126fbe13 100644 --- a/test/parallel/test-child-process-exit-code.js +++ b/test/parallel/test-child-process-exit-code.js @@ -4,29 +4,18 @@ var assert = require('assert'); var spawn = require('child_process').spawn; var path = require('path'); -var exits = 0; - var exitScript = path.join(common.fixturesDir, 'exit.js'); var exitChild = spawn(process.argv[0], [exitScript, 23]); -exitChild.on('exit', function(code, signal) { +exitChild.on('exit', common.mustCall(function(code, signal) { assert.strictEqual(code, 23); assert.strictEqual(signal, null); - - exits++; -}); +})); var errorScript = path.join(common.fixturesDir, 'child_process_should_emit_error.js'); var errorChild = spawn(process.argv[0], [errorScript]); -errorChild.on('exit', function(code, signal) { +errorChild.on('exit', common.mustCall(function(code, signal) { assert.ok(code !== 0); assert.strictEqual(signal, null); - - exits++; -}); - - -process.on('exit', function() { - assert.equal(2, exits); -}); +})); diff --git a/test/parallel/test-child-process-fork-and-spawn.js b/test/parallel/test-child-process-fork-and-spawn.js index eb0e1785751747..50615ecb79d0c6 100644 --- a/test/parallel/test-child-process-fork-and-spawn.js +++ b/test/parallel/test-child-process-fork-and-spawn.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; var fork = require('child_process').fork; @@ -7,12 +7,11 @@ var fork = require('child_process').fork; // Fork, then spawn. The spawned process should not hang. switch (process.argv[2] || '') { case '': - fork(__filename, ['fork']).on('exit', checkExit); - process.on('exit', haveExit); + fork(__filename, ['fork']).on('exit', common.mustCall(checkExit)); break; case 'fork': - spawn(process.execPath, [__filename, 'spawn']).on('exit', checkExit); - process.on('exit', haveExit); + spawn(process.execPath, [__filename, 'spawn']) + .on('exit', common.mustCall(checkExit)); break; case 'spawn': break; @@ -20,14 +19,7 @@ switch (process.argv[2] || '') { assert(0); } -var seenExit = false; - function checkExit(statusCode) { - seenExit = true; assert.equal(statusCode, 0); process.nextTick(process.exit); } - -function haveExit() { - assert.equal(seenExit, true); -} diff --git a/test/parallel/test-child-process-fork-close.js b/test/parallel/test-child-process-fork-close.js index cec3c88f0fa11c..8af22e7dcf6951 100644 --- a/test/parallel/test-child-process-fork-close.js +++ b/test/parallel/test-child-process-fork-close.js @@ -9,28 +9,22 @@ let gotMessage = false; let gotExit = false; let gotClose = false; -cp.on('message', function(message) { +cp.on('message', common.mustCall(function(message) { assert(!gotMessage); assert(!gotClose); assert.strictEqual(message, 'hello'); gotMessage = true; -}); +})); -cp.on('exit', function() { +cp.on('exit', common.mustCall(function() { assert(!gotExit); assert(!gotClose); gotExit = true; -}); +})); -cp.on('close', function() { +cp.on('close', common.mustCall(function() { assert(gotMessage); assert(gotExit); assert(!gotClose); gotClose = true; -}); - -process.on('exit', function() { - assert(gotMessage); - assert(gotExit); - assert(gotClose); -}); +})); diff --git a/test/parallel/test-child-process-fork.js b/test/parallel/test-child-process-fork.js index ab253d04c2c790..5ae231ef0357ac 100644 --- a/test/parallel/test-child-process-fork.js +++ b/test/parallel/test-child-process-fork.js @@ -1,6 +1,6 @@ 'use strict'; +const common = require('../common'); var assert = require('assert'); -var common = require('../common'); var fork = require('child_process').fork; var args = ['foo', 'bar']; @@ -19,11 +19,6 @@ assert.throws(function() { n.send(); }, TypeError); n.send({ hello: 'world' }); -var childExitCode = -1; -n.on('exit', function(c) { - childExitCode = c; -}); - -process.on('exit', function() { - assert.ok(childExitCode == 0); -}); +n.on('exit', common.mustCall(function(c) { + assert.strictEqual(c, 0); +})); diff --git a/test/parallel/test-child-process-internal.js b/test/parallel/test-child-process-internal.js index e6db1f82a04957..f3e452ef87ea76 100644 --- a/test/parallel/test-child-process-internal.js +++ b/test/parallel/test-child-process-internal.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); //messages @@ -21,18 +21,11 @@ if (process.argv[2] === 'child') { var fork = require('child_process').fork; var child = fork(process.argv[1], ['child']); - var gotNormal; - child.once('message', function(data) { - gotNormal = data; - }); + child.once('message', common.mustCall(function(data) { + assert.deepStrictEqual(data, normal); + })); - var gotInternal; - child.once('internalMessage', function(data) { - gotInternal = data; - }); - - process.on('exit', function() { - assert.deepStrictEqual(gotNormal, normal); - assert.deepStrictEqual(gotInternal, internal); - }); + child.once('internalMessage', common.mustCall(function(data) { + assert.deepStrictEqual(data, internal); + })); } diff --git a/test/parallel/test-child-process-kill.js b/test/parallel/test-child-process-kill.js index 745816bb68766d..9f6f8f6e796196 100644 --- a/test/parallel/test-child-process-kill.js +++ b/test/parallel/test-child-process-kill.js @@ -1,41 +1,18 @@ 'use strict'; var common = require('../common'); var assert = require('assert'); - var spawn = require('child_process').spawn; - -var exitCode; -var termSignal; -var gotStdoutEOF = false; -var gotStderrEOF = false; - var cat = spawn(common.isWindows ? 'cmd' : 'cat'); +cat.stdout.on('end', common.mustCall(function() {})); +cat.stderr.on('data', common.fail); +cat.stderr.on('end', common.mustCall(function() {})); -cat.stdout.on('end', function() { - gotStdoutEOF = true; -}); - -cat.stderr.on('data', function(chunk) { - assert.ok(false); -}); - -cat.stderr.on('end', function() { - gotStderrEOF = true; -}); - -cat.on('exit', function(code, signal) { - exitCode = code; - termSignal = signal; -}); +cat.on('exit', common.mustCall(function(code, signal) { + assert.strictEqual(code, null); + assert.strictEqual(signal, 'SIGTERM'); +})); assert.equal(cat.killed, false); cat.kill(); assert.equal(cat.killed, true); - -process.on('exit', function() { - assert.strictEqual(exitCode, null); - assert.strictEqual(termSignal, 'SIGTERM'); - assert.ok(gotStdoutEOF); - assert.ok(gotStderrEOF); -}); diff --git a/test/parallel/test-child-process-set-blocking.js b/test/parallel/test-child-process-set-blocking.js index 6cdfbbc9a24c71..fb0b11f433130a 100644 --- a/test/parallel/test-child-process-set-blocking.js +++ b/test/parallel/test-child-process-set-blocking.js @@ -1,20 +1,14 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var ch = require('child_process'); var SIZE = 100000; -var childGone = false; var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { stdio: 'inherit' }); -cp.on('exit', function(code) { - childGone = true; +cp.on('exit', common.mustCall(function(code) { assert.equal(0, code); -}); - -process.on('exit', function() { - assert.ok(childGone); -}); +})); diff --git a/test/parallel/test-child-process-spawn-error.js b/test/parallel/test-child-process-spawn-error.js index e80955635e17ee..eaf9c1303966a5 100644 --- a/test/parallel/test-child-process-spawn-error.js +++ b/test/parallel/test-child-process-spawn-error.js @@ -3,22 +3,15 @@ var common = require('../common'); var spawn = require('child_process').spawn; var assert = require('assert'); -var errors = 0; - var enoentPath = 'foo123'; var spawnargs = ['bar']; assert.equal(common.fileExists(enoentPath), false); var enoentChild = spawn(enoentPath, spawnargs); -enoentChild.on('error', function(err) { +enoentChild.on('error', common.mustCall(function(err) { assert.equal(err.code, 'ENOENT'); assert.equal(err.errno, 'ENOENT'); assert.equal(err.syscall, 'spawn ' + enoentPath); assert.equal(err.path, enoentPath); assert.deepStrictEqual(err.spawnargs, spawnargs); - errors++; -}); - -process.on('exit', function() { - assert.equal(1, errors); -}); +})); diff --git a/test/parallel/test-child-process-stdin-ipc.js b/test/parallel/test-child-process-stdin-ipc.js index 79e60f333b9d6b..2ce7c66c2053e0 100644 --- a/test/parallel/test-child-process-stdin-ipc.js +++ b/test/parallel/test-child-process-stdin-ipc.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; @@ -14,11 +14,6 @@ var proc = spawn(process.execPath, [__filename, 'child'], { stdio: ['ipc', 'inherit', 'inherit'] }); -var childCode = -1; -proc.on('exit', function(code) { - childCode = code; -}); - -process.on('exit', function() { - assert.equal(childCode, 0); -}); +proc.on('exit', common.mustCall(function(code) { + assert.strictEqual(code, 0); +})); diff --git a/test/parallel/test-child-process-stdin.js b/test/parallel/test-child-process-stdin.js index 4a371b83fb045b..f30ad83c381602 100644 --- a/test/parallel/test-child-process-stdin.js +++ b/test/parallel/test-child-process-stdin.js @@ -15,8 +15,6 @@ assert.ok(!cat.stdin.readable); cat.stdin.end(); var response = ''; -var exitStatus = -1; -var closed = false; cat.stdout.setEncoding('utf8'); cat.stdout.on('data', function(chunk) { @@ -26,33 +24,18 @@ cat.stdout.on('data', function(chunk) { cat.stdout.on('end', common.mustCall(function() {})); -cat.stderr.on('data', function(chunk) { - // shouldn't get any stderr output - assert.ok(false); -}); +cat.stderr.on('data', common.fail); cat.stderr.on('end', common.mustCall(function() {})); -cat.on('exit', function(status) { - console.log('exit event'); - exitStatus = status; -}); - -cat.on('close', function() { - closed = true; - if (common.isWindows) { - assert.equal('hello world\r\n', response); - } else { - assert.equal('hello world', response); - } -}); +cat.on('exit', common.mustCall(function(status) { + assert.strictEqual(0, status); +})); -process.on('exit', function() { - assert.equal(0, exitStatus); - assert(closed); +cat.on('close', common.mustCall(function() { if (common.isWindows) { assert.equal('hello world\r\n', response); } else { assert.equal('hello world', response); } -}); +})); diff --git a/test/parallel/test-cluster-http-pipe.js b/test/parallel/test-cluster-http-pipe.js index 8ea634b3034ebb..0d6cb422be80c2 100644 --- a/test/parallel/test-cluster-http-pipe.js +++ b/test/parallel/test-cluster-http-pipe.js @@ -13,18 +13,13 @@ if (common.isWindows) { if (cluster.isMaster) { common.refreshTmpDir(); - var ok = false; var worker = cluster.fork(); - worker.on('message', function(msg) { + worker.on('message', common.mustCall(function(msg) { assert.equal(msg, 'DONE'); - ok = true; - }); + })); worker.on('exit', function() { process.exit(); }); - process.on('exit', function() { - assert(ok); - }); return; } diff --git a/test/parallel/test-cluster-listening-port.js b/test/parallel/test-cluster-listening-port.js index 810364a92648e4..b0fbf9499041d2 100644 --- a/test/parallel/test-cluster-listening-port.js +++ b/test/parallel/test-cluster-listening-port.js @@ -5,20 +5,15 @@ var cluster = require('cluster'); var net = require('net'); if (cluster.isMaster) { - var port = null; cluster.fork(); - cluster.on('listening', function(worker, address) { - port = address.port; + cluster.on('listening', common.mustCall(function(worker, address) { + const port = address.port; // ensure that the port is not 0 or null assert(port); // ensure that the port is numerical assert.strictEqual(typeof port, 'number'); worker.kill(); - }); - process.on('exit', function() { - // ensure that the 'listening' handler has been called - assert(port); - }); + })); } else { net.createServer(common.fail).listen(0); } diff --git a/test/parallel/test-cluster-net-listen.js b/test/parallel/test-cluster-net-listen.js index 81bd1641d3b761..829d1806d52889 100644 --- a/test/parallel/test-cluster-net-listen.js +++ b/test/parallel/test-cluster-net-listen.js @@ -6,14 +6,9 @@ var net = require('net'); if (cluster.isMaster) { // ensure that the worker exits peacefully - var worker = cluster.fork(); - worker.on('exit', function(statusCode) { + cluster.fork().on('exit', common.mustCall(function(statusCode) { assert.equal(statusCode, 0); - worker = null; - }); - process.on('exit', function() { - assert.equal(worker, null); - }); + })); } else { // listen() without port should not trigger a libuv assert net.createServer(common.fail).listen(process.exit); diff --git a/test/parallel/test-cluster-setup-master-emit.js b/test/parallel/test-cluster-setup-master-emit.js index ad15c084c5924d..aad1cea75eda97 100644 --- a/test/parallel/test-cluster-setup-master-emit.js +++ b/test/parallel/test-cluster-setup-master-emit.js @@ -1,39 +1,26 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); assert(cluster.isMaster); -var assertsRun = 0; - function emitAndCatch(next) { - cluster.once('setup', function(settings) { + cluster.once('setup', common.mustCall(function(settings) { assert.strictEqual(settings.exec, 'new-exec'); - console.log('ok "setup" emitted with options set'); - assertsRun += 1; setImmediate(next); - }); + })); cluster.setupMaster({ exec: 'new-exec' }); } function emitAndCatch2(next) { - cluster.once('setup', function(settings) { + cluster.once('setup', common.mustCall(function(settings) { assert('exec' in settings); - console.log('ok "setup" emitted without options set'); - assertsRun += 1; setImmediate(next); - }); + })); cluster.setupMaster(); } -process.on('exit', function() { - assert.strictEqual(assertsRun, 2); - console.log('ok correct number of assertions'); -}); - -emitAndCatch(function() { - emitAndCatch2(function() { - console.log('ok emitted and caught'); - }); -}); +emitAndCatch(common.mustCall(function() { + emitAndCatch2(common.mustCall(function() {})); +})); diff --git a/test/parallel/test-cluster-uncaught-exception.js b/test/parallel/test-cluster-uncaught-exception.js index 1f04b71f01ac73..1091b6fec759a1 100644 --- a/test/parallel/test-cluster-uncaught-exception.js +++ b/test/parallel/test-cluster-uncaught-exception.js @@ -3,7 +3,7 @@ // one that the cluster module installs. // https://github.com/joyent/node/issues/2556 -require('../common'); +const common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); var fork = require('child_process').fork; @@ -13,16 +13,10 @@ var MAGIC_EXIT_CODE = 42; var isTestRunner = process.argv[2] != 'child'; if (isTestRunner) { - var exitCode = -1; - - process.on('exit', function() { - assert.equal(exitCode, MAGIC_EXIT_CODE); - }); - var master = fork(__filename, ['child']); - master.on('exit', function(code) { - exitCode = code; - }); + master.on('exit', common.mustCall(function(code) { + assert.strictEqual(code, MAGIC_EXIT_CODE); + })); } else if (cluster.isMaster) { process.on('uncaughtException', function() { process.nextTick(function() { diff --git a/test/parallel/test-cluster-worker-death.js b/test/parallel/test-cluster-worker-death.js index aec745b8b71f6d..8bbf46de568eb0 100644 --- a/test/parallel/test-cluster-worker-death.js +++ b/test/parallel/test-cluster-worker-death.js @@ -1,25 +1,17 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); if (!cluster.isMaster) { process.exit(42); } else { - var seenExit = 0; - var seenDeath = 0; var worker = cluster.fork(); - worker.on('exit', function(exitCode, signalCode) { + worker.on('exit', common.mustCall(function(exitCode, signalCode) { assert.equal(exitCode, 42); assert.equal(signalCode, null); - seenExit++; - }); - cluster.on('exit', function(worker_) { + })); + cluster.on('exit', common.mustCall(function(worker_) { assert.equal(worker_, worker); - seenDeath++; - }); - process.on('exit', function() { - assert.equal(seenExit, 1); - assert.equal(seenDeath, 1); - }); + })); } diff --git a/test/parallel/test-cluster-worker-destroy.js b/test/parallel/test-cluster-worker-destroy.js index 8e5ca63e13c6be..c802177530e4af 100644 --- a/test/parallel/test-cluster-worker-destroy.js +++ b/test/parallel/test-cluster-worker-destroy.js @@ -7,26 +7,18 @@ * both code paths. */ -require('../common'); +const common = require('../common'); var cluster = require('cluster'); -var assert = require('assert'); - -var worker1, worker2, workerExited, workerDisconnected; +var worker1, worker2; if (cluster.isMaster) { worker1 = cluster.fork(); worker2 = cluster.fork(); - workerExited = 0; - workerDisconnected = 0; - [worker1, worker2].forEach(function(worker) { - worker.on('disconnect', ondisconnect); - worker.on('exit', onexit); + worker.on('disconnect', common.mustCall(function() {})); + worker.on('exit', common.mustCall(function() {})); }); - - process.on('exit', onProcessExit); - } else { if (cluster.worker.id === 1) { // Call destroy when worker is disconnected @@ -40,20 +32,3 @@ if (cluster.isMaster) { cluster.worker.destroy(); } } - -function onProcessExit() { - assert.equal(workerExited, - 2, - 'When master exits, all workers should have exited too'); - assert.equal(workerDisconnected, - 2, - 'When master exits, all workers should have disconnected'); -} - -function ondisconnect() { - ++workerDisconnected; -} - -function onexit() { - ++workerExited; -} diff --git a/test/parallel/test-cluster-worker-forced-exit.js b/test/parallel/test-cluster-worker-forced-exit.js index 4f42532b553059..0592cbfd01ac69 100644 --- a/test/parallel/test-cluster-worker-forced-exit.js +++ b/test/parallel/test-cluster-worker-forced-exit.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var cluster = require('cluster'); @@ -24,14 +24,6 @@ if (cluster.isWorker) { return; } -var unforcedOk; -var forcedOk; - -process.on('exit', function() { - assert(forcedOk); - assert(unforcedOk); -}); - checkUnforced(); checkForced(); @@ -40,10 +32,9 @@ function checkUnforced() { .on('online', function() { this.disconnect(); }) - .on('exit', function(status) { + .on('exit', common.mustCall(function(status) { assert.equal(status, SENTINEL); - unforcedOk = true; - }); + })); } function checkForced() { @@ -51,8 +42,7 @@ function checkForced() { .on('online', function() { this.process.disconnect(); }) - .on('exit', function(status) { + .on('exit', common.mustCall(function(status) { assert.equal(status, 0); - forcedOk = true; - }); + })); } diff --git a/test/parallel/test-crypto-domains.js b/test/parallel/test-crypto-domains.js index 9036228bf6b16d..5d8caf37ee2f41 100644 --- a/test/parallel/test-crypto-domains.js +++ b/test/parallel/test-crypto-domains.js @@ -4,7 +4,6 @@ var domain = require('domain'); var assert = require('assert'); var d = domain.create(); var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; -var errors = 0; if (!common.hasCrypto) { common.skip('missing crypto'); @@ -12,14 +11,9 @@ if (!common.hasCrypto) { } var crypto = require('crypto'); -process.on('exit', function() { - assert.equal(errors, 3); -}); - -d.on('error', function(e) { +d.on('error', common.mustCall(function(e) { assert.equal(e.message, expect.shift()); - errors += 1; -}); +}, 3)); d.run(function() { one(); diff --git a/test/parallel/test-crypto-hash-stream-pipe.js b/test/parallel/test-crypto-hash-stream-pipe.js index a2b19a69e5bb31..0ad9f18b0b45d8 100644 --- a/test/parallel/test-crypto-hash-stream-pipe.js +++ b/test/parallel/test-crypto-hash-stream-pipe.js @@ -12,16 +12,9 @@ var stream = require('stream'); var s = new stream.PassThrough(); var h = crypto.createHash('sha1'); var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e'; -var gotData = false; -process.on('exit', function() { - assert(gotData); - console.log('ok'); -}); - -s.pipe(h).on('data', function(c) { +s.pipe(h).on('data', common.mustCall(function(c) { assert.equal(c, expect); - gotData = true; -}).setEncoding('hex'); +})).setEncoding('hex'); s.end('aoeu'); diff --git a/test/parallel/test-delayed-require.js b/test/parallel/test-delayed-require.js index ceaa23d51093d7..bc110388fc0380 100644 --- a/test/parallel/test-delayed-require.js +++ b/test/parallel/test-delayed-require.js @@ -3,13 +3,9 @@ var common = require('../common'); var path = require('path'); var assert = require('assert'); -var a; -setTimeout(function() { - a = require(path.join(common.fixturesDir, 'a')); -}, 50); - -process.on('exit', function() { - assert.equal(true, 'A' in a); - assert.equal('A', a.A()); - assert.equal('D', a.D()); -}); +setTimeout(common.mustCall(function() { + const a = require(path.join(common.fixturesDir, 'a')); + assert.strictEqual(true, 'A' in a); + assert.strictEqual('A', a.A()); + assert.strictEqual('D', a.D()); +}), 50); diff --git a/test/parallel/test-dgram-close-is-not-callback.js b/test/parallel/test-dgram-close-is-not-callback.js index 29a364d8fab2ea..61e08200360452 100644 --- a/test/parallel/test-dgram-close-is-not-callback.js +++ b/test/parallel/test-dgram-close-is-not-callback.js @@ -1,21 +1,14 @@ 'use strict'; -var assert = require('assert'); var common = require('../common'); var dgram = require('dgram'); var buf = Buffer.alloc(1024, 42); var socket = dgram.createSocket('udp4'); -var closeEvents = 0; + socket.send(buf, 0, buf.length, common.PORT, 'localhost'); // if close callback is not function, ignore the argument. socket.close('bad argument'); -socket.on('close', function() { - ++closeEvents; -}); - -process.on('exit', function() { - assert.equal(closeEvents, 1); -}); +socket.on('close', common.mustCall(function() {})); diff --git a/test/parallel/test-dgram-close.js b/test/parallel/test-dgram-close.js index 7dbeee1efb9b61..41d28553ca8cb7 100644 --- a/test/parallel/test-dgram-close.js +++ b/test/parallel/test-dgram-close.js @@ -2,24 +2,18 @@ // Ensure that if a dgram socket is closed before the DNS lookup completes, it // won't crash. -const assert = require('assert'); const common = require('../common'); +const assert = require('assert'); const dgram = require('dgram'); var buf = Buffer.alloc(1024, 42); var socket = dgram.createSocket('udp4'); var handle = socket._handle; -var closeEvents = 0; -var closeCallbacks = 0; + socket.send(buf, 0, buf.length, common.PORT, 'localhost'); -assert.strictEqual(socket.close(function() { - ++closeCallbacks; -}), socket); -socket.on('close', function() { - assert.equal(closeCallbacks, 1); - ++closeEvents; -}); +assert.strictEqual(socket.close(common.mustCall(function() {})), socket); +socket.on('close', common.mustCall(function() {})); socket = null; // Verify that accessing handle after closure doesn't throw @@ -28,8 +22,3 @@ setImmediate(function() { console.log('Handle fd is: ', handle.fd); }); }); - -process.on('exit', function() { - assert.equal(closeEvents, 1); - assert.equal(closeCallbacks, 1); -}); diff --git a/test/parallel/test-dgram-implicit-bind.js b/test/parallel/test-dgram-implicit-bind.js index e874dc46cb3d19..8cbb3f771e2d47 100644 --- a/test/parallel/test-dgram-implicit-bind.js +++ b/test/parallel/test-dgram-implicit-bind.js @@ -1,24 +1,19 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var dgram = require('dgram'); var source = dgram.createSocket('udp4'); var target = dgram.createSocket('udp4'); var messages = 0; -process.on('exit', function() { - assert.equal(messages, 2); -}); - -target.on('message', function(buf) { +target.on('message', common.mustCall(function(buf) { if (buf.toString() === 'abc') ++messages; if (buf.toString() === 'def') ++messages; if (messages === 2) { source.close(); target.close(); } -}); +}, 2)); target.on('listening', function() { // Second .send() call should not throw a bind error. diff --git a/test/parallel/test-dgram-unref.js b/test/parallel/test-dgram-unref.js index 083dab6d29589c..e5f26b6f3387b8 100644 --- a/test/parallel/test-dgram-unref.js +++ b/test/parallel/test-dgram-unref.js @@ -1,19 +1,9 @@ 'use strict'; -require('../common'); -var assert = require('assert'); - +const common = require('../common'); var dgram = require('dgram'); -var closed = false; var s = dgram.createSocket('udp4'); s.bind(); s.unref(); -setTimeout(function() { - closed = true; - s.close(); -}, 1000).unref(); - -process.on('exit', function() { - assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); -}); +setTimeout(common.fail, 1000).unref(); diff --git a/test/parallel/test-domain-implicit-fs.js b/test/parallel/test-domain-implicit-fs.js index d0a468419b923e..a92653aff1de1c 100644 --- a/test/parallel/test-domain-implicit-fs.js +++ b/test/parallel/test-domain-implicit-fs.js @@ -1,15 +1,13 @@ 'use strict'; // Simple tests of most basic domain functionality. -require('../common'); +const common = require('../common'); var assert = require('assert'); var domain = require('domain'); -var caught = 0; -var expectCaught = 1; var d = new domain.Domain(); -d.on('error', function(er) { +d.on('error', common.mustCall(function(er) { console.error('caught', er); assert.strictEqual(er.domain, d); @@ -18,15 +16,7 @@ d.on('error', function(er) { assert.strictEqual(er.code, 'ENOENT'); assert.ok(/\bthis file does not exist\b/i.test(er.path)); assert.strictEqual(typeof er.errno, 'number'); - - caught++; -}); - -process.on('exit', function() { - console.error('exit'); - assert.equal(caught, expectCaught); - console.log('ok'); -}); +})); // implicit handling of thrown errors while in a domain, via the diff --git a/test/parallel/test-domain-timers.js b/test/parallel/test-domain-timers.js index 58989e812bba50..faa57df1277083 100644 --- a/test/parallel/test-domain-timers.js +++ b/test/parallel/test-domain-timers.js @@ -1,16 +1,16 @@ 'use strict'; -require('../common'); +const common = require('../common'); var domain = require('domain'); var assert = require('assert'); -var timeout_err, timeout, immediate_err; +var timeout; var timeoutd = domain.create(); -timeoutd.on('error', function(e) { - timeout_err = e; +timeoutd.on('error', common.mustCall(function(e) { + assert.equal(e.message, 'Timeout UNREFd', 'Domain should catch timer error'); clearTimeout(timeout); -}); +})); timeoutd.run(function() { setTimeout(function() { @@ -20,9 +20,10 @@ timeoutd.run(function() { var immediated = domain.create(); -immediated.on('error', function(e) { - immediate_err = e; -}); +immediated.on('error', common.mustCall(function(e) { + assert.equal(e.message, 'Immediate Error', + 'Domain should catch immediate error'); +})); immediated.run(function() { setImmediate(function() { @@ -31,10 +32,3 @@ immediated.run(function() { }); timeout = setTimeout(function() {}, 10 * 1000); - -process.on('exit', function() { - assert.equal(timeout_err.message, 'Timeout UNREFd', - 'Domain should catch timer error'); - assert.equal(immediate_err.message, 'Immediate Error', - 'Domain should catch immediate error'); -}); diff --git a/test/parallel/test-error-reporting.js b/test/parallel/test-error-reporting.js index 567642d3e83e2b..62525a5494d5a0 100644 --- a/test/parallel/test-error-reporting.js +++ b/test/parallel/test-error-reporting.js @@ -4,8 +4,6 @@ var assert = require('assert'); var exec = require('child_process').exec; var path = require('path'); -var exits = 0; - function errExec(script, callback) { var cmd = '"' + process.argv[0] + '" "' + path.join(common.fixturesDir, script) + '"'; @@ -21,52 +19,45 @@ function errExec(script, callback) { // Proxy the args for more tests. callback(err, stdout, stderr); - - // Count the tests - exits++; }); } // Simple throw error -errExec('throws_error.js', function(err, stdout, stderr) { +errExec('throws_error.js', common.mustCall(function(err, stdout, stderr) { assert.ok(/blah/.test(stderr)); -}); +})); // Trying to JSON.parse(undefined) -errExec('throws_error2.js', function(err, stdout, stderr) { +errExec('throws_error2.js', common.mustCall(function(err, stdout, stderr) { assert.ok(/SyntaxError/.test(stderr)); -}); +})); // Trying to JSON.parse(undefined) in nextTick -errExec('throws_error3.js', function(err, stdout, stderr) { +errExec('throws_error3.js', common.mustCall(function(err, stdout, stderr) { assert.ok(/SyntaxError/.test(stderr)); -}); +})); // throw ILLEGAL error -errExec('throws_error4.js', function(err, stdout, stderr) { +errExec('throws_error4.js', common.mustCall(function(err, stdout, stderr) { assert.ok(/\/\*\*/.test(stderr)); assert.ok(/SyntaxError/.test(stderr)); -}); +})); // Specific long exception line doesn't result in stack overflow -errExec('throws_error5.js', function(err, stdout, stderr) { +errExec('throws_error5.js', common.mustCall(function(err, stdout, stderr) { assert.ok(/SyntaxError/.test(stderr)); -}); +})); // Long exception line with length > errorBuffer doesn't result in assertion -errExec('throws_error6.js', function(err, stdout, stderr) { +errExec('throws_error6.js', common.mustCall(function(err, stdout, stderr) { assert.ok(/SyntaxError/.test(stderr)); -}); +})); // Object that throws in toString() doesn't print garbage -errExec('throws_error7.js', function(err, stdout, stderr) { +errExec('throws_error7.js', common.mustCall(function(err, stdout, stderr) { assert.ok(/ 0); - }); + })); res.writeHead(200, { 'Content-Type': 'text/plain' }); // Write 1.5mb to cause some requests to buffer @@ -34,7 +27,7 @@ var httpServer = http.createServer(function(req, res) { assert(res.connection.bytesWritten > 0); res.end(body); -}); +})); httpServer.listen(0, function() { http.get({ port: this.address().port }); diff --git a/test/parallel/test-http-client-abort-event.js b/test/parallel/test-http-client-abort-event.js index 8f98b578930cdb..c0c1f9e4c73c92 100644 --- a/test/parallel/test-http-client-abort-event.js +++ b/test/parallel/test-http-client-abort-event.js @@ -1,29 +1,20 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var http = require('http'); var server = http.createServer(function(req, res) { res.end(); }); -var count = 0; -server.listen(0, function() { + +server.listen(0, common.mustCall(function() { var req = http.request({ port: this.address().port - }, function() { - assert(false, 'should not receive data'); - }); + }, common.fail); - req.on('abort', function() { - // should only be emitted once - count++; + req.on('abort', common.mustCall(function() { server.close(); - }); + })); req.end(); req.abort(); req.abort(); -}); - -process.on('exit', function() { - assert.equal(count, 1); -}); +})); diff --git a/test/parallel/test-http-client-get-url.js b/test/parallel/test-http-client-get-url.js index d425dff3008e26..51f8413b675244 100644 --- a/test/parallel/test-http-client-get-url.js +++ b/test/parallel/test-http-client-get-url.js @@ -1,24 +1,17 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); -var seen_req = false; - -var server = http.createServer(function(req, res) { +var server = http.createServer(common.mustCall(function(req, res) { assert.equal('GET', req.method); assert.equal('/foo?bar', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); server.close(); - seen_req = true; -}); +})); server.listen(0, function() { http.get(`http://127.0.0.1:${this.address().port}/foo?bar`); }); - -process.on('exit', function() { - assert(seen_req); -}); diff --git a/test/parallel/test-http-client-readable.js b/test/parallel/test-http-client-readable.js index 8328afb01c6478..c035132eb0decc 100644 --- a/test/parallel/test-http-client-readable.js +++ b/test/parallel/test-http-client-readable.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var util = require('util'); @@ -39,22 +39,18 @@ FakeAgent.prototype.createConnection = function createConnection() { }; var received = ''; -var ended = 0; var req = http.request({ agent: new FakeAgent() -}, function(res) { +}, common.mustCall(function(res) { res.on('data', function(chunk) { received += chunk; }); - res.on('end', function() { - ended++; - }); -}); + res.on('end', common.mustCall(function() {})); +})); req.end(); process.on('exit', function() { assert.equal(received, 'hello world'); - assert.equal(ended, 1); }); diff --git a/test/parallel/test-http-client-response-domain.js b/test/parallel/test-http-client-response-domain.js index 3034b1087e4d33..5355a301e8031d 100644 --- a/test/parallel/test-http-client-response-domain.js +++ b/test/parallel/test-http-client-response-domain.js @@ -4,13 +4,8 @@ const assert = require('assert'); const http = require('http'); const domain = require('domain'); -var gotDomainError = false; var d; -process.on('exit', function() { - assert(gotDomainError); -}); - common.refreshTmpDir(); // first fire up a simple HTTP server @@ -22,15 +17,14 @@ var server = http.createServer(function(req, res) { server.listen(common.PIPE, function() { // create a domain d = domain.create(); - d.run(test); + d.run(common.mustCall(test)); }); function test() { - d.on('error', function(err) { - gotDomainError = true; + d.on('error', common.mustCall(function(err) { assert.equal('should be caught by domain', err.message); - }); + })); var req = http.get({ socketPath: common.PIPE, diff --git a/test/parallel/test-http-client-upload-buf.js b/test/parallel/test-http-client-upload-buf.js index cac3f5fcd89095..512a438ef82115 100644 --- a/test/parallel/test-http-client-upload-buf.js +++ b/test/parallel/test-http-client-upload-buf.js @@ -1,52 +1,44 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var N = 1024; -var bytesReceived = 0; -var server_req_complete = false; -var client_res_complete = false; -var server = http.createServer(function(req, res) { +var server = http.createServer(common.mustCall(function(req, res) { assert.equal('POST', req.method); + var bytesReceived = 0; + req.on('data', function(chunk) { bytesReceived += chunk.length; }); - req.on('end', function() { - server_req_complete = true; + req.on('end', common.mustCall(function() { + assert.strictEqual(N, bytesReceived); console.log('request complete from server'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); - }); -}); + })); +})); server.listen(0); -server.on('listening', function() { +server.on('listening', common.mustCall(function() { var req = http.request({ port: this.address().port, method: 'POST', path: '/' - }, function(res) { + }, common.mustCall(function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { console.log(chunk); }); - res.on('end', function() { - client_res_complete = true; + res.on('end', common.mustCall(function() { server.close(); - }); - }); + })); + })); req.write(Buffer.allocUnsafe(N)); req.end(); -}); - -process.on('exit', function() { - assert.equal(N, bytesReceived); - assert.equal(true, server_req_complete); - assert.equal(true, client_res_complete); -}); +})); diff --git a/test/parallel/test-http-client-upload.js b/test/parallel/test-http-client-upload.js index ad66329d5adf05..a5c8f5b92bc761 100644 --- a/test/parallel/test-http-client-upload.js +++ b/test/parallel/test-http-client-upload.js @@ -1,55 +1,46 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); -var sent_body = ''; -var server_req_complete = false; -var client_res_complete = false; - -var server = http.createServer(function(req, res) { +var server = http.createServer(common.mustCall(function(req, res) { assert.equal('POST', req.method); req.setEncoding('utf8'); + var sent_body = ''; + req.on('data', function(chunk) { console.log('server got: ' + JSON.stringify(chunk)); sent_body += chunk; }); - req.on('end', function() { - server_req_complete = true; + req.on('end', common.mustCall(function() { + assert.strictEqual('1\n2\n3\n', sent_body); console.log('request complete from server'); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); - }); -}); + })); +})); server.listen(0); -server.on('listening', function() { +server.on('listening', common.mustCall(function() { var req = http.request({ port: this.address().port, method: 'POST', path: '/' - }, function(res) { + }, common.mustCall(function(res) { res.setEncoding('utf8'); res.on('data', function(chunk) { console.log(chunk); }); - res.on('end', function() { - client_res_complete = true; + res.on('end', common.mustCall(function() { server.close(); - }); - }); + })); + })); req.write('1\n'); req.write('2\n'); req.write('3\n'); req.end(); -}); - -process.on('exit', function() { - assert.equal('1\n2\n3\n', sent_body); - assert.equal(true, server_req_complete); - assert.equal(true, client_res_complete); -}); +})); diff --git a/test/parallel/test-http-conn-reset.js b/test/parallel/test-http-conn-reset.js index 956b895b050d51..d7852bf32c9ec3 100644 --- a/test/parallel/test-http-conn-reset.js +++ b/test/parallel/test-http-conn-reset.js @@ -1,11 +1,9 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); -var caughtError = false; - var options = { host: '127.0.0.1', port: undefined @@ -16,7 +14,7 @@ var server = net.createServer(function(client) { client.destroy(); server.close(); }); -server.listen(0, options.host, onListen); +server.listen(0, options.host, common.mustCall(onListen)); // do a GET request, expect it to fail function onListen() { @@ -24,14 +22,8 @@ function onListen() { var req = http.request(options, function(res) { assert.ok(false, 'this should never run'); }); - req.on('error', function(err) { + req.on('error', common.mustCall(function(err) { assert.equal(err.code, 'ECONNRESET'); - caughtError = true; - }); + })); req.end(); } - -process.on('exit', function() { - assert.equal(caughtError, true); -}); - diff --git a/test/parallel/test-http-connect-req-res.js b/test/parallel/test-http-connect-req-res.js index c6b545b61e3b82..1cee61e4c2fb37 100644 --- a/test/parallel/test-http-connect-req-res.js +++ b/test/parallel/test-http-connect-req-res.js @@ -3,9 +3,7 @@ const common = require('../common'); const assert = require('assert'); const http = require('http'); -const server = http.createServer(function(req, res) { - assert(false); -}); +const server = http.createServer(common.fail); server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) { assert.equal(req.method, 'CONNECT'); assert.equal(req.url, 'example.com:443'); @@ -33,9 +31,7 @@ server.listen(0, common.mustCall(function() { port: this.address().port, method: 'CONNECT', path: 'example.com:443' - }, function(res) { - assert(false); - }); + }, common.fail); req.on('close', common.mustCall(function() { })); diff --git a/test/parallel/test-http-connect.js b/test/parallel/test-http-connect.js index b0efca64fa1cd9..9da199b8ee9a0d 100644 --- a/test/parallel/test-http-connect.js +++ b/test/parallel/test-http-connect.js @@ -1,14 +1,12 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var serverGotConnect = false; var clientGotConnect = false; -var server = http.createServer(function(req, res) { - assert(false); -}); +var server = http.createServer(common.fail); server.on('connect', function(req, socket, firstBodyChunk) { assert.equal(req.method, 'CONNECT'); assert.equal(req.url, 'google.com:443'); @@ -30,9 +28,7 @@ server.listen(0, function() { port: this.address().port, method: 'CONNECT', path: 'google.com:443' - }, function(res) { - assert(false); - }); + }, common.fail); var clientRequestClosed = false; req.on('close', function() { diff --git a/test/parallel/test-http-end-throw-socket-handling.js b/test/parallel/test-http-end-throw-socket-handling.js index bab5135555364b..cb4f125948a3c9 100644 --- a/test/parallel/test-http-end-throw-socket-handling.js +++ b/test/parallel/test-http-end-throw-socket-handling.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); // Make sure that throwing in 'end' handler doesn't lock // up the socket forever. @@ -29,11 +28,4 @@ server.listen(0, common.mustCall(() => { } })); -let errors = 0; -process.on('uncaughtException', () => { - errors++; -}); - -process.on('exit', () => { - assert.equal(errors, 10); -}); +process.on('uncaughtException', common.mustCall(() => {}, 10)); diff --git a/test/parallel/test-http-extra-response.js b/test/parallel/test-http-extra-response.js index 37bad7013e97b1..8364684a1ec23f 100644 --- a/test/parallel/test-http-extra-response.js +++ b/test/parallel/test-http-extra-response.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); @@ -20,9 +20,6 @@ var fullResponse = '\r\n' + body; -var gotResponse = false; - - var server = net.createServer(function(socket) { var postBody = ''; @@ -44,8 +41,8 @@ var server = net.createServer(function(socket) { }); -server.listen(0, function() { - http.get({ port: this.address().port }, function(res) { +server.listen(0, common.mustCall(function() { + http.get({ port: this.address().port }, common.mustCall(function(res) { var buffer = ''; console.log('Got res code: ' + res.statusCode); @@ -54,17 +51,10 @@ server.listen(0, function() { buffer += chunk; }); - res.on('end', function() { + res.on('end', common.mustCall(function() { console.log('Response ended, read ' + buffer.length + ' bytes'); assert.equal(body, buffer); server.close(); - gotResponse = true; - }); - }); -}); - - -process.on('exit', function() { - assert.ok(gotResponse); -}); - + })); + })); +})); diff --git a/test/parallel/test-http-full-response.js b/test/parallel/test-http-full-response.js index dad7ca8fb43caa..e59456a710aac3 100644 --- a/test/parallel/test-http-full-response.js +++ b/test/parallel/test-http-full-response.js @@ -17,8 +17,6 @@ var server = http.createServer(function(req, res) { res.end(body); }); -var runs = 0; - function runAb(opts, callback) { var command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; exec(command, function(err, stdout, stderr) { @@ -43,28 +41,21 @@ function runAb(opts, callback) { assert.equal(bodyLength, documentLength); assert.equal(completeRequests * documentLength, htmlTransfered); - runs++; - if (callback) callback(); }); } -server.listen(0, function() { - runAb('-c 1 -n 10', function() { +server.listen(0, common.mustCall(function() { + runAb('-c 1 -n 10', common.mustCall(function() { console.log('-c 1 -n 10 okay'); - runAb('-c 1 -n 100', function() { + runAb('-c 1 -n 100', common.mustCall(function() { console.log('-c 1 -n 100 okay'); - runAb('-c 1 -n 1000', function() { + runAb('-c 1 -n 1000', common.mustCall(function() { console.log('-c 1 -n 1000 okay'); server.close(); - }); - }); - }); - -}); - -process.on('exit', function() { - assert.equal(3, runs); -}); + })); + })); + })); +})); diff --git a/test/parallel/test-http-head-request.js b/test/parallel/test-http-head-request.js index 68aaace7c3e15e..e8626b18811bda 100644 --- a/test/parallel/test-http-head-request.js +++ b/test/parallel/test-http-head-request.js @@ -1,6 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var http = require('http'); var body = 'hello world\n'; @@ -13,27 +12,20 @@ function test(headers) { server.close(); }); - var gotEnd = false; - - server.listen(0, function() { + server.listen(0, common.mustCall(function() { var request = http.request({ port: this.address().port, method: 'HEAD', path: '/' - }, function(response) { + }, common.mustCall(function(response) { console.error('response start'); - response.on('end', function() { + response.on('end', common.mustCall(function() { console.error('response end'); - gotEnd = true; - }); + })); response.resume(); - }); + })); request.end(); - }); - - process.on('exit', function() { - assert.ok(gotEnd); - }); + })); } test({ diff --git a/test/parallel/test-http-head-response-has-no-body-end.js b/test/parallel/test-http-head-response-has-no-body-end.js index 2f7a2105a1c75c..87ce957df3499f 100644 --- a/test/parallel/test-http-head-response-has-no-body-end.js +++ b/test/parallel/test-http-head-response-has-no-body-end.js @@ -1,7 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); - +const common = require('../common'); var http = require('http'); // This test is to make sure that when the HTTP server @@ -14,23 +12,16 @@ var server = http.createServer(function(req, res) { }); server.listen(0); -var responseComplete = false; - -server.on('listening', function() { +server.on('listening', common.mustCall(function() { var req = http.request({ port: this.address().port, method: 'HEAD', path: '/' - }, function(res) { - res.on('end', function() { + }, common.mustCall(function(res) { + res.on('end', common.mustCall(function() { server.close(); - responseComplete = true; - }); + })); res.resume(); - }); + })); req.end(); -}); - -process.on('exit', function() { - assert.ok(responseComplete); -}); +})); diff --git a/test/parallel/test-http-head-response-has-no-body.js b/test/parallel/test-http-head-response-has-no-body.js index a36dec7cf2b1ce..445b522b8dea51 100644 --- a/test/parallel/test-http-head-response-has-no-body.js +++ b/test/parallel/test-http-head-response-has-no-body.js @@ -1,7 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); - +const common = require('../common'); var http = require('http'); // This test is to make sure that when the HTTP server @@ -14,23 +12,16 @@ var server = http.createServer(function(req, res) { }); server.listen(0); -var responseComplete = false; - -server.on('listening', function() { +server.on('listening', common.mustCall(function() { var req = http.request({ port: this.address().port, method: 'HEAD', path: '/' - }, function(res) { - res.on('end', function() { + }, common.mustCall(function(res) { + res.on('end', common.mustCall(function() { server.close(); - responseComplete = true; - }); + })); res.resume(); - }); + })); req.end(); -}); - -process.on('exit', function() { - assert.ok(responseComplete); -}); +})); diff --git a/test/parallel/test-http-hex-write.js b/test/parallel/test-http-hex-write.js index 5b5729712d8575..adfe18077a8259 100644 --- a/test/parallel/test-http-hex-write.js +++ b/test/parallel/test-http-hex-write.js @@ -1,18 +1,10 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var expect = 'hex\nutf8\n'; -var data = ''; -var ended = false; - -process.on('exit', function() { - assert(ended); - assert.equal(data, expect); - console.log('ok'); -}); http.createServer(function(q, s) { s.setHeader('content-length', expect.length); @@ -20,14 +12,17 @@ http.createServer(function(q, s) { s.write('utf8\n'); s.end(); this.close(); -}).listen(0, function() { - http.request({ port: this.address().port }).on('response', function(res) { - res.setEncoding('ascii'); - res.on('data', function(c) { - data += c; - }); - res.on('end', function() { - ended = true; - }); - }).end(); -}); +}).listen(0, common.mustCall(function() { + http.request({ port: this.address().port }) + .on('response', common.mustCall(function(res) { + var data = ''; + + res.setEncoding('ascii'); + res.on('data', function(c) { + data += c; + }); + res.on('end', common.mustCall(function() { + assert.strictEqual(data, expect); + })); + })).end(); +})); diff --git a/test/parallel/test-http-legacy.js b/test/parallel/test-http-legacy.js index 363c3a92362e6a..36165954cb8f8f 100644 --- a/test/parallel/test-http-legacy.js +++ b/test/parallel/test-http-legacy.js @@ -1,11 +1,10 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var url = require('url'); var responses_sent = 0; -var responses_recvd = 0; var body0 = ''; var body1 = ''; @@ -37,37 +36,32 @@ var server = http.createServer(function(req, res) { req.resume(); }); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var client = http.createClient(this.address().port); var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'}); setTimeout(function() { req.end(); }, 100); - req.on('response', function(res) { + req.on('response', common.mustCall(function(res) { assert.equal(200, res.statusCode); - responses_recvd += 1; res.setEncoding('utf8'); res.on('data', function(chunk) { body0 += chunk; }); console.error('Got /hello response'); - }); + })); - setTimeout(function() { + setTimeout(common.mustCall(function() { var req = client.request('POST', '/world'); req.end(); - req.on('response', function(res) { + req.on('response', common.mustCall(function(res) { assert.equal(200, res.statusCode); - responses_recvd += 1; res.setEncoding('utf8'); res.on('data', function(chunk) { body1 += chunk; }); console.error('Got /world response'); - }); - }, 1); -}); + })); + }), 1); +})); process.on('exit', function() { - console.error('responses_recvd: ' + responses_recvd); - assert.equal(2, responses_recvd); - console.error('responses_sent: ' + responses_sent); assert.equal(2, responses_sent); diff --git a/test/parallel/test-http-localaddress-bind-error.js b/test/parallel/test-http-localaddress-bind-error.js index 5b537b00e7ead7..0b828910f12873 100644 --- a/test/parallel/test-http-localaddress-bind-error.js +++ b/test/parallel/test-http-localaddress-bind-error.js @@ -1,10 +1,8 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); var http = require('http'); var invalidLocalAddress = '1.2.3.4'; -var gotError = false; var server = http.createServer(function(req, res) { console.log('Connect from: ' + req.connection.remoteAddress); @@ -16,7 +14,7 @@ var server = http.createServer(function(req, res) { req.resume(); }); -server.listen(0, '127.0.0.1', function() { +server.listen(0, '127.0.0.1', common.mustCall(function() { http.request({ host: 'localhost', port: this.address().port, @@ -25,13 +23,8 @@ server.listen(0, '127.0.0.1', function() { localAddress: invalidLocalAddress }, function(res) { common.fail('unexpectedly got response from server'); - }).on('error', function(e) { + }).on('error', common.mustCall(function(e) { console.log('client got error: ' + e.message); - gotError = true; server.close(); - }).end(); -}); - -process.on('exit', function() { - assert.ok(gotError); -}); + })).end(); +})); diff --git a/test/parallel/test-http-multi-line-headers.js b/test/parallel/test-http-multi-line-headers.js index 3a1f5f268948e9..f534b3b8db605c 100644 --- a/test/parallel/test-http-multi-line-headers.js +++ b/test/parallel/test-http-multi-line-headers.js @@ -1,12 +1,10 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); -var gotResponse = false; - var server = net.createServer(function(conn) { var body = 'Yet another node.js server.'; @@ -24,15 +22,13 @@ var server = net.createServer(function(conn) { server.close(); }); -server.listen(0, function() { - http.get({host: '127.0.0.1', port: this.address().port}, function(res) { +server.listen(0, common.mustCall(function() { + http.get({ + host: '127.0.0.1', + port: this.address().port + }, common.mustCall(function(res) { assert.equal(res.headers['content-type'], 'text/plain; x-unix-mode=0600; name="hello.txt"'); - gotResponse = true; res.destroy(); - }); -}); - -process.on('exit', function() { - assert.ok(gotResponse); -}); + })); +})); diff --git a/test/parallel/test-http-no-content-length.js b/test/parallel/test-http-no-content-length.js index dcdf00c402d1e1..b27ffda727129e 100644 --- a/test/parallel/test-http-no-content-length.js +++ b/test/parallel/test-http-no-content-length.js @@ -1,26 +1,23 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); -var body = ''; - var server = net.createServer(function(socket) { // Neither Content-Length nor Connection socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); -}).listen(0, function() { - http.get({port: this.address().port}, function(res) { +}).listen(0, common.mustCall(function() { + http.get({port: this.address().port}, common.mustCall(function(res) { + var body = ''; + res.setEncoding('utf8'); res.on('data', function(chunk) { body += chunk; }); - res.on('end', function() { + res.on('end', common.mustCall(function() { + assert.strictEqual(body, 'Hello'); server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(body, 'Hello'); -}); + })); + })); +})); diff --git a/test/parallel/test-http-pause-resume-one-end.js b/test/parallel/test-http-pause-resume-one-end.js index 76969775e604cc..2ebd3cbe619ac7 100644 --- a/test/parallel/test-http-pause-resume-one-end.js +++ b/test/parallel/test-http-pause-resume-one-end.js @@ -1,6 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var http = require('http'); var server = http.Server(function(req, res) { @@ -9,32 +8,20 @@ var server = http.Server(function(req, res) { server.close(); }); - -var dataCount = 0, endCount = 0; - -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var opts = { port: this.address().port, headers: { connection: 'close' } }; - http.get(opts, function(res) { - res.on('data', function(chunk) { - dataCount++; + http.get(opts, common.mustCall(function(res) { + res.on('data', common.mustCall(function(chunk) { res.pause(); setTimeout(function() { res.resume(); }); - }); - - res.on('end', function() { - endCount++; - }); - }); -}); - + })); -process.on('exit', function() { - assert.equal(1, dataCount); - assert.equal(1, endCount); -}); + res.on('end', common.mustCall(function() {})); + })); +})); diff --git a/test/parallel/test-http-pipe-fs.js b/test/parallel/test-http-pipe-fs.js index 89dfbb9c551e3a..3205802d7ab0f2 100644 --- a/test/parallel/test-http-pipe-fs.js +++ b/test/parallel/test-http-pipe-fs.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); var http = require('http'); var fs = require('fs'); var path = require('path'); @@ -8,17 +7,15 @@ var path = require('path'); common.refreshTmpDir(); var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); -var requests = 0; -var server = http.createServer(function(req, res) { - ++requests; +var server = http.createServer(common.mustCall(function(req, res) { var stream = fs.createWriteStream(file); req.pipe(stream); stream.on('close', function() { res.writeHead(200); res.end(); }); -}).listen(0, function() { +}, 2)).listen(0, function() { http.globalAgent.maxSockets = 1; for (var i = 0; i < 2; ++i) { @@ -45,7 +42,3 @@ var server = http.createServer(function(req, res) { }(i + 1)); } }); - -process.on('exit', function() { - assert.equal(requests, 2); -}); diff --git a/test/parallel/test-http-pipeline-flood.js b/test/parallel/test-http-pipeline-flood.js index b42834d2b0e164..4f6775656e4e49 100644 --- a/test/parallel/test-http-pipeline-flood.js +++ b/test/parallel/test-http-pipeline-flood.js @@ -1,6 +1,5 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); // Here we are testing the HTTP server module's flood prevention mechanism. // When writeable.write returns false (ie the underlying send() indicated the @@ -27,7 +26,6 @@ switch (process.argv[2]) { function parent() { const http = require('http'); const bigResponse = Buffer.alloc(10240, 'x'); - var connections = 0; var backloggedReqs = 0; const server = http.createServer(function(req, res) { @@ -48,9 +46,7 @@ function parent() { res.end(); }); - server.on('connection', function(conn) { - connections++; - }); + server.on('connection', common.mustCall(function(conn) {})); server.listen(0, function() { const spawn = require('child_process').spawn; @@ -64,10 +60,6 @@ function parent() { child.kill(); })); }); - - process.on('exit', function() { - assert.equal(connections, 1); - }); } function child() { diff --git a/test/parallel/test-http-request-end.js b/test/parallel/test-http-request-end.js index 5f03c60b7518e6..6beedae20d9e00 100644 --- a/test/parallel/test-http-request-end.js +++ b/test/parallel/test-http-request-end.js @@ -4,15 +4,17 @@ var assert = require('assert'); var http = require('http'); var expected = 'Post Body For Test'; -var result = ''; var server = http.Server(function(req, res) { + var result = ''; + req.setEncoding('utf8'); req.on('data', function(chunk) { result += chunk; }); req.on('end', function() { + assert.strictEqual(expected, result); server.close(); res.writeHead(200); res.end('hello world\n'); @@ -33,7 +35,3 @@ server.listen(0, function() { process.exit(1); }).end(expected); }); - -process.on('exit', function() { - assert.equal(expected, result); -}); diff --git a/test/parallel/test-http-request-methods.js b/test/parallel/test-http-request-methods.js index cbfbbbc2ed603a..7f42a9c00a85f3 100644 --- a/test/parallel/test-http-request-methods.js +++ b/test/parallel/test-http-request-methods.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); @@ -7,20 +7,18 @@ var http = require('http'); // Test that the DELETE, PATCH and PURGE verbs get passed through correctly ['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) { - var server_response = ''; - var received_method = null; - - var server = http.createServer(function(req, res) { - received_method = req.method; + var server = http.createServer(common.mustCall(function(req, res) { + assert.strictEqual(req.method, method); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello '); res.write('world\n'); res.end(); - }); + })); server.listen(0); - server.on('listening', function() { + server.on('listening', common.mustCall(function() { var c = net.createConnection(this.address().port); + var server_response = ''; c.setEncoding('utf8'); @@ -33,18 +31,14 @@ var http = require('http'); server_response += chunk; }); - c.on('end', function() { + c.on('end', common.mustCall(function() { + const m = server_response.split('\r\n\r\n'); + assert.strictEqual(m[1], 'hello world\n'); c.end(); - }); + })); c.on('close', function() { server.close(); }); - }); - - process.on('exit', function() { - var m = server_response.split('\r\n\r\n'); - assert.equal(m[1], 'hello world\n'); - assert.equal(received_method, method); - }); + })); }); diff --git a/test/parallel/test-http-res-write-after-end.js b/test/parallel/test-http-res-write-after-end.js index 8dca7adc9ec629..5a91c556340b1c 100644 --- a/test/parallel/test-http-res-write-after-end.js +++ b/test/parallel/test-http-res-write-after-end.js @@ -1,29 +1,22 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); -var responseError; - -var server = http.Server(function(req, res) { - res.on('error', function onResError(err) { - responseError = err; - }); +var server = http.Server(common.mustCall(function(req, res) { + res.on('error', common.mustCall(function onResError(err) { + assert.strictEqual(err.message, 'write after end'); + })); res.write('This should write.'); res.end(); var r = res.write('This should raise an error.'); assert.equal(r, true, 'write after end should return true'); -}); +})); server.listen(0, function() { http.get({port: this.address().port}, function(res) { server.close(); }); }); - -process.on('exit', function onProcessExit(code) { - assert(responseError, 'response should have emitted error'); - assert.equal(responseError.message, 'write after end'); -}); diff --git a/test/parallel/test-http-response-close.js b/test/parallel/test-http-response-close.js index 072136dfeeb811..54ee61efccf1ea 100644 --- a/test/parallel/test-http-response-close.js +++ b/test/parallel/test-http-response-close.js @@ -1,24 +1,18 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var http = require('http'); -var requestGotEnd = false; -var responseGotEnd = false; - -var server = http.createServer(function(req, res) { +var server = http.createServer(common.mustCall(function(req, res) { res.writeHead(200); res.write('a'); - req.on('close', function() { + req.on('close', common.mustCall(function() { console.error('request aborted'); - requestGotEnd = true; - }); - res.on('close', function() { + })); + res.on('close', common.mustCall(function() { console.error('response aborted'); - responseGotEnd = true; - }); -}); + })); +})); server.listen(0); server.on('listening', function() { @@ -34,8 +28,3 @@ server.on('listening', function() { }); }); }); - -process.on('exit', function() { - assert.ok(requestGotEnd); - assert.ok(responseGotEnd); -}); diff --git a/test/parallel/test-http-response-no-headers.js b/test/parallel/test-http-response-no-headers.js index 8f70bead33f824..4a3460bc645140 100644 --- a/test/parallel/test-http-response-no-headers.js +++ b/test/parallel/test-http-response-no-headers.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); @@ -10,13 +10,7 @@ var expected = { '1.1': '' }; -var gotExpected = false; - function test(httpVersion, callback) { - process.on('exit', function() { - assert(gotExpected); - }); - var server = net.createServer(function(conn) { var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + expected[httpVersion]; @@ -24,31 +18,30 @@ function test(httpVersion, callback) { conn.end(reply); }); - server.listen(0, '127.0.0.1', function() { + server.listen(0, '127.0.0.1', common.mustCall(function() { var options = { host: '127.0.0.1', port: this.address().port }; - var req = http.get(options, function(res) { + var req = http.get(options, common.mustCall(function(res) { var body = ''; res.on('data', function(data) { body += data; }); - res.on('end', function() { + res.on('end', common.mustCall(function() { assert.equal(body, expected[httpVersion]); - gotExpected = true; server.close(); if (callback) process.nextTick(callback); - }); - }); + })); + })); req.on('error', function(err) { throw err; }); - }); + })); } test('0.9', function() { diff --git a/test/parallel/test-http-unix-socket.js b/test/parallel/test-http-unix-socket.js index bdac0566c33a42..69c887b53bdbb1 100644 --- a/test/parallel/test-http-unix-socket.js +++ b/test/parallel/test-http-unix-socket.js @@ -3,10 +3,6 @@ var common = require('../common'); var assert = require('assert'); var http = require('http'); -var status_ok = false; // status code == 200? -var headers_ok = false; -var body_ok = false; - var server = http.createServer(function(req, res) { res.writeHead(200, { 'Content-Type': 'text/plain', @@ -19,19 +15,16 @@ var server = http.createServer(function(req, res) { common.refreshTmpDir(); -server.listen(common.PIPE, function() { +server.listen(common.PIPE, common.mustCall(function() { var options = { socketPath: common.PIPE, path: '/' }; - var req = http.get(options, function(res) { + var req = http.get(options, common.mustCall(function(res) { assert.equal(res.statusCode, 200); - status_ok = true; - assert.equal(res.headers['content-type'], 'text/plain'); - headers_ok = true; res.body = ''; res.setEncoding('utf8'); @@ -40,17 +33,16 @@ server.listen(common.PIPE, function() { res.body += chunk; }); - res.on('end', function() { + res.on('end', common.mustCall(function() { assert.equal(res.body, 'hello world\n'); - body_ok = true; server.close(function(error) { assert.equal(error, undefined); server.close(function(error) { assert.equal(error && error.message, 'Not running'); }); }); - }); - }); + })); + })); req.on('error', function(e) { console.log(e.stack); @@ -59,10 +51,4 @@ server.listen(common.PIPE, function() { req.end(); -}); - -process.on('exit', function() { - assert.ok(status_ok); - assert.ok(headers_ok); - assert.ok(body_ok); -}); +})); diff --git a/test/parallel/test-http-upgrade-agent.js b/test/parallel/test-http-upgrade-agent.js index 4e88e525b74fb2..48eaa16f898021 100644 --- a/test/parallel/test-http-upgrade-agent.js +++ b/test/parallel/test-http-upgrade-agent.js @@ -25,9 +25,7 @@ var srv = net.createServer(function(c) { }); }); -var gotUpgrade = false; - -srv.listen(0, '127.0.0.1', function() { +srv.listen(0, '127.0.0.1', common.mustCall(function() { var options = { port: this.address().port, @@ -42,7 +40,7 @@ srv.listen(0, '127.0.0.1', function() { var req = http.request(options); req.end(); - req.on('upgrade', function(res, socket, upgradeHead) { + req.on('upgrade', common.mustCall(function(res, socket, upgradeHead) { var recvData = upgradeHead; socket.on('data', function(d) { recvData += d; @@ -61,16 +59,9 @@ srv.listen(0, '127.0.0.1', function() { // Make sure this request got removed from the pool. assert(!http.globalAgent.sockets.hasOwnProperty(name)); - req.on('close', function() { + req.on('close', common.mustCall(function() { socket.end(); srv.close(); - - gotUpgrade = true; - }); - }); - -}); - -process.on('exit', function() { - assert.ok(gotUpgrade); -}); + })); + })); +})); diff --git a/test/parallel/test-http-upgrade-client.js b/test/parallel/test-http-upgrade-client.js index 85e9f8f3c2e90c..71ab1090d215da 100644 --- a/test/parallel/test-http-upgrade-client.js +++ b/test/parallel/test-http-upgrade-client.js @@ -25,9 +25,7 @@ var srv = net.createServer(function(c) { }); }); -var gotUpgrade = false; - -srv.listen(0, '127.0.0.1', function() { +srv.listen(0, '127.0.0.1', common.mustCall(function() { var req = http.get({ port: this.address().port, @@ -36,7 +34,7 @@ srv.listen(0, '127.0.0.1', function() { upgrade: 'websocket' } }); - req.on('upgrade', function(res, socket, upgradeHead) { + req.on('upgrade', common.mustCall(function(res, socket, upgradeHead) { var recvData = upgradeHead; socket.on('data', function(d) { recvData += d; @@ -54,11 +52,5 @@ srv.listen(0, '127.0.0.1', function() { socket.end(); srv.close(); - - gotUpgrade = true; - }); -}); - -process.on('exit', function() { - assert.ok(gotUpgrade); -}); + })); +})); diff --git a/test/parallel/test-http-upgrade-client2.js b/test/parallel/test-http-upgrade-client2.js index f48644ee735794..0c229a354add48 100644 --- a/test/parallel/test-http-upgrade-client2.js +++ b/test/parallel/test-http-upgrade-client2.js @@ -1,6 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var http = require('http'); var CRLF = '\r\n'; @@ -15,9 +14,7 @@ server.on('upgrade', function(req, socket, head) { }); }); -var successCount = 0; - -server.listen(0, function() { +server.listen(0, common.mustCall(function() { function upgradeRequest(fn) { console.log('req'); @@ -52,18 +49,11 @@ server.listen(0, function() { } - upgradeRequest(function() { - successCount++; - upgradeRequest(function() { - successCount++; + upgradeRequest(common.mustCall(function() { + upgradeRequest(common.mustCall(function() { // Test pass console.log('Pass!'); server.close(); - }); - }); - -}); - -process.on('exit', function() { - assert.equal(2, successCount); -}); + })); + })); +})); diff --git a/test/parallel/test-http-upgrade-server2.js b/test/parallel/test-http-upgrade-server2.js index b1616617294b5e..1644f54977af85 100644 --- a/test/parallel/test-http-upgrade-server2.js +++ b/test/parallel/test-http-upgrade-server2.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var net = require('net'); @@ -14,13 +14,10 @@ server.on('upgrade', function(req, socket, upgradeHead) { throw new Error('upgrade error'); }); -var gotError = false; - -process.on('uncaughtException', function(e) { +process.on('uncaughtException', common.mustCall(function(e) { assert.equal('upgrade error', e.message); - gotError = true; process.exit(0); -}); +})); server.listen(0, function() { @@ -41,7 +38,3 @@ server.listen(0, function() { server.close(); }); }); - -process.on('exit', function() { - assert.ok(gotError); -}); diff --git a/test/parallel/test-http-wget.js b/test/parallel/test-http-wget.js index 2c3ea3335d89dd..f7fb1a3656c623 100644 --- a/test/parallel/test-http-wget.js +++ b/test/parallel/test-http-wget.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); var http = require('http'); @@ -19,10 +19,6 @@ var http = require('http'); // content-length is not provided, that the connection is in fact // closed. -var server_response = ''; -var client_got_eof = false; -var connection_was_closed = false; - var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello '); @@ -31,8 +27,9 @@ var server = http.createServer(function(req, res) { }); server.listen(0); -server.on('listening', function() { +server.on('listening', common.mustCall(function() { var c = net.createConnection(this.address().port); + var server_response = ''; c.setEncoding('utf8'); @@ -46,22 +43,15 @@ server.on('listening', function() { server_response += chunk; }); - c.on('end', function() { - client_got_eof = true; + c.on('end', common.mustCall(function() { + const m = server_response.split('\r\n\r\n'); + assert.strictEqual(m[1], 'hello world\n'); console.log('got end'); c.end(); - }); + })); - c.on('close', function() { - connection_was_closed = true; + c.on('close', common.mustCall(function() { console.log('got close'); server.close(); - }); -}); - -process.on('exit', function() { - var m = server_response.split('\r\n\r\n'); - assert.equal(m[1], 'hello world\n'); - assert.ok(client_got_eof); - assert.ok(connection_was_closed); -}); + })); +})); diff --git a/test/parallel/test-http-write-empty-string.js b/test/parallel/test-http-write-empty-string.js index 6ae723e306bae2..534a55823accee 100644 --- a/test/parallel/test-http-write-empty-string.js +++ b/test/parallel/test-http-write-empty-string.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); @@ -17,20 +17,17 @@ var server = http.createServer(function(request, response) { this.close(); }); -var response = ''; +server.listen(0, common.mustCall(function() { + http.get({ port: this.address().port }, common.mustCall(function(res) { + var response = ''; -process.on('exit', function() { - assert.equal('1\n2\n3\n', response); -}); - - -server.listen(0, function() { - http.get({ port: this.address().port }, function(res) { assert.equal(200, res.statusCode); res.setEncoding('ascii'); res.on('data', function(chunk) { response += chunk; }); - }); -}); - + res.on('end', common.mustCall(function() { + assert.strictEqual('1\n2\n3\n', response); + })); + })); +})); diff --git a/test/parallel/test-https-agent-session-eviction.js b/test/parallel/test-https-agent-session-eviction.js index 8c30e7d8eda528..5a2c9061cd55cd 100644 --- a/test/parallel/test-https-agent-session-eviction.js +++ b/test/parallel/test-https-agent-session-eviction.js @@ -81,9 +81,6 @@ function third(server) { assert(!req.socket.isSessionReused()); server.close(); }); - req.on('error', function(err) { - // never called - assert(false); - }); + req.on('error', common.fail); req.end(); } diff --git a/test/parallel/test-https-client-checkServerIdentity.js b/test/parallel/test-https-client-checkServerIdentity.js index 4b4bbc9d0598ad..053a5630050748 100644 --- a/test/parallel/test-https-client-checkServerIdentity.js +++ b/test/parallel/test-https-client-checkServerIdentity.js @@ -16,14 +16,11 @@ var options = { cert: fs.readFileSync(path.join(common.fixturesDir, 'keys/agent3-cert.pem')) }; -var reqCount = 0; - -var server = https.createServer(options, function(req, res) { - ++reqCount; +var server = https.createServer(options, common.mustCall(function(req, res) { res.writeHead(200); res.end(); req.resume(); -}).listen(0, function() { +})).listen(0, function() { authorized(); }); @@ -32,9 +29,7 @@ function authorized() { port: server.address().port, rejectUnauthorized: true, ca: [fs.readFileSync(path.join(common.fixturesDir, 'keys/ca2-cert.pem'))] - }, function(res) { - assert(false); - }); + }, common.fail); req.on('error', function(err) { override(); }); @@ -60,7 +55,3 @@ function override() { }); req.end(); } - -process.on('exit', function() { - assert.equal(reqCount, 1); -}); diff --git a/test/parallel/test-https-client-get-url.js b/test/parallel/test-https-client-get-url.js index 1d816bee32ffda..84ef01786d2d49 100644 --- a/test/parallel/test-https-client-get-url.js +++ b/test/parallel/test-https-client-get-url.js @@ -13,27 +13,20 @@ var https = require('https'); var fs = require('fs'); -var seen_req = false; - var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = https.createServer(options, function(req, res) { +var server = https.createServer(options, common.mustCall(function(req, res) { assert.equal('GET', req.method); assert.equal('/foo?bar', req.url); res.writeHead(200, {'Content-Type': 'text/plain'}); res.write('hello\n'); res.end(); server.close(); - seen_req = true; -}); +})); server.listen(0, function() { https.get(`https://127.0.0.1:${this.address().port}/foo?bar`); }); - -process.on('exit', function() { - assert(seen_req); -}); diff --git a/test/parallel/test-https-client-reject.js b/test/parallel/test-https-client-reject.js index 1bf42e5df57090..b1708f24b10b83 100644 --- a/test/parallel/test-https-client-reject.js +++ b/test/parallel/test-https-client-reject.js @@ -16,14 +16,11 @@ var options = { cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; -var reqCount = 0; - -var server = https.createServer(options, function(req, res) { - ++reqCount; +var server = https.createServer(options, common.mustCall(function(req, res) { res.writeHead(200); res.end(); req.resume(); -}).listen(0, function() { +}, 2)).listen(0, function() { unauthorized(); }); @@ -47,9 +44,7 @@ function rejectUnauthorized() { port: server.address().port }; options.agent = new https.Agent(options); - var req = https.request(options, function(res) { - assert(false); - }); + var req = https.request(options, common.fail); req.on('error', function(err) { authorized(); }); @@ -67,12 +62,6 @@ function authorized() { assert(req.socket.authorized); server.close(); }); - req.on('error', function(err) { - assert(false); - }); + req.on('error', common.fail); req.end(); } - -process.on('exit', function() { - assert.equal(reqCount, 2); -}); diff --git a/test/parallel/test-https-client-resume.js b/test/parallel/test-https-client-resume.js index 9ddf20fa34a47c..734e8069021f78 100644 --- a/test/parallel/test-https-client-resume.js +++ b/test/parallel/test-https-client-resume.js @@ -19,13 +19,10 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; -var connections = 0; - // create server -var server = https.createServer(options, function(req, res) { +var server = https.createServer(options, common.mustCall(function(req, res) { res.end('Goodbye'); - connections++; -}); +}, 2)); // start listening server.listen(0, function() { @@ -66,7 +63,3 @@ server.listen(0, function() { }); }); }); - -process.on('exit', function() { - assert.equal(2, connections); -}); diff --git a/test/parallel/test-https-connecting-to-http.js b/test/parallel/test-https-connecting-to-http.js index 31eb0171ad87e6..53158595054714 100644 --- a/test/parallel/test-https-connecting-to-http.js +++ b/test/parallel/test-https-connecting-to-http.js @@ -2,7 +2,6 @@ // This tests the situation where you try to connect a https client // to an http server. You should get an error and exit. var common = require('../common'); -var assert = require('assert'); var http = require('http'); if (!common.hasCrypto) { @@ -11,35 +10,13 @@ if (!common.hasCrypto) { } var https = require('https'); -var reqCount = 0; -var resCount = 0; -var reqErrorCount = 0; -var body = 'hello world\n'; +var server = http.createServer(common.fail); +server.listen(0, common.mustCall(function() { + var req = https.get({ port: this.address().port }, common.fail); -var server = http.createServer(function(req, res) { - reqCount++; - console.log('got request'); - res.writeHead(200, { 'content-type': 'text/plain' }); - res.end(body); -}); - - -server.listen(0, function() { - var req = https.get({ port: this.address().port }, function(res) { - resCount++; - }); - - req.on('error', function(e) { + req.on('error', common.mustCall(function(e) { console.log('Got expected error: ', e.message); server.close(); - reqErrorCount++; - }); -}); - - -process.on('exit', function() { - assert.equal(0, reqCount); - assert.equal(0, resCount); - assert.equal(1, reqErrorCount); -}); + })); +})); diff --git a/test/parallel/test-https-eof-for-eom.js b/test/parallel/test-https-eof-for-eom.js index 924785e0aaefd1..1c814714bfef96 100644 --- a/test/parallel/test-https-eof-for-eom.js +++ b/test/parallel/test-https-eof-for-eom.js @@ -46,37 +46,27 @@ var server = tls.Server(options, function(socket) { }, 100); }); - -var gotHeaders = false; -var gotEnd = false; -var bodyBuffer = ''; - -server.listen(0, function() { +server.listen(0, common.mustCall(function() { console.log('1) Making Request'); https.get({ port: this.address().port, rejectUnauthorized: false - }, function(res) { + }, common.mustCall(function(res) { + var bodyBuffer = ''; + server.close(); console.log('3) Client got response headers.'); assert.equal('gws', res.headers.server); - gotHeaders = true; res.setEncoding('utf8'); res.on('data', function(s) { bodyBuffer += s; }); - res.on('end', function() { + res.on('end', common.mustCall(function() { console.log('5) Client got "end" event.'); - gotEnd = true; - }); - }); -}); - -process.on('exit', function() { - assert.ok(gotHeaders); - assert.ok(gotEnd); - assert.equal('hello world\nhello world\n', bodyBuffer); -}); + assert.strictEqual('hello world\nhello world\n', bodyBuffer); + })); + })); +})); diff --git a/test/parallel/test-https-foafssl.js b/test/parallel/test-https-foafssl.js index f8370e73902242..5c9fb613e6fa95 100644 --- a/test/parallel/test-https-foafssl.js +++ b/test/parallel/test-https-foafssl.js @@ -24,25 +24,31 @@ var options = { requestCert: true }; +const modulus = 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09BBC3A5519F' + + '349CD9B9C40BE436D0AA823A94147E26C89248ADA2BE3DD4D34E8C289646' + + '94B2047D217B4F1299371EA93A83C89AB9440724131E65F2B0161DE9560C' + + 'DE9C13455552B2F49CF0FB00D8D77532324913F6F80FF29D0A131D29DB06' + + 'AFF8BE191B7920DC2DAE1C26EA82A47847A10391EF3BF6AABB3CC40FF821' + + '00B03A4F0FF1809278E4DDFDA7DE954ED56DC7AD9A47EEBC37D771A366FC' + + '60A5BCB72373BEC180649B3EFA0E9092707210B41B90032BB18BC91F2046' + + 'EBDAF1191F4A4E26D71879C4C7867B62FCD508E8CE66E82D128A71E91580' + + '9FCF44E8DE774067F1DE5D70B9C03687'; + var CRLF = '\r\n'; var body = 'hello world\n'; var cert; -var subjectaltname; -var modulus; -var exponent; -var server = https.createServer(options, function(req, res) { +var server = https.createServer(options, common.mustCall(function(req, res) { console.log('got request'); cert = req.connection.getPeerCertificate(); - subjectaltname = cert.subjectaltname; - modulus = cert.modulus; - exponent = cert.exponent; - + assert.strictEqual(cert.subjectaltname, 'URI:http://example.com/#me'); + assert.strictEqual(cert.exponent, '0x10001'); + assert.strictEqual(cert.modulus, modulus); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); -}); +})); server.listen(0, function() { var args = ['s_client', @@ -70,16 +76,3 @@ server.listen(0, function() { throw error; }); }); - -process.on('exit', function() { - assert.equal(subjectaltname, 'URI:http://example.com/#me'); - assert.equal(modulus, 'A6F44A9C25791431214F5C87AF9E040177A8BB89AC803F7E09' + - 'BBC3A5519F349CD9B9C40BE436D0AA823A94147E26C89248ADA2BE3DD4D34E8C2896' + - '4694B2047D217B4F1299371EA93A83C89AB9440724131E65F2B0161DE9560CDE9C13' + - '455552B2F49CF0FB00D8D77532324913F6F80FF29D0A131D29DB06AFF8BE191B7920' + - 'DC2DAE1C26EA82A47847A10391EF3BF6AABB3CC40FF82100B03A4F0FF1809278E4DD' + - 'FDA7DE954ED56DC7AD9A47EEBC37D771A366FC60A5BCB72373BEC180649B3EFA0E90' + - '92707210B41B90032BB18BC91F2046EBDAF1191F4A4E26D71879C4C7867B62FCD508' + - 'E8CE66E82D128A71E915809FCF44E8DE774067F1DE5D70B9C03687'); - assert.equal(exponent, '0x10001'); -}); diff --git a/test/parallel/test-https-localaddress-bind-error.js b/test/parallel/test-https-localaddress-bind-error.js index 1ce94a0ac0eaca..91c3062a6e1896 100644 --- a/test/parallel/test-https-localaddress-bind-error.js +++ b/test/parallel/test-https-localaddress-bind-error.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); var fs = require('fs'); if (!common.hasCrypto) { @@ -15,7 +14,6 @@ var options = { }; var invalidLocalAddress = '1.2.3.4'; -var gotError = false; var server = https.createServer(options, function(req, res) { console.log('Connect from: ' + req.connection.remoteAddress); @@ -27,7 +25,7 @@ var server = https.createServer(options, function(req, res) { req.resume(); }); -server.listen(0, '127.0.0.1', function() { +server.listen(0, '127.0.0.1', common.mustCall(function() { https.request({ host: 'localhost', port: this.address().port, @@ -36,13 +34,8 @@ server.listen(0, '127.0.0.1', function() { localAddress: invalidLocalAddress }, function(res) { common.fail('unexpectedly got response from server'); - }).on('error', function(e) { + }).on('error', common.mustCall(function(e) { console.log('client got error: ' + e.message); - gotError = true; server.close(); - }).end(); -}); - -process.on('exit', function() { - assert.ok(gotError); -}); + })).end(); +})); diff --git a/test/parallel/test-https-pfx.js b/test/parallel/test-https-pfx.js index ab6db5f7226430..02715de60da3c8 100644 --- a/test/parallel/test-https-pfx.js +++ b/test/parallel/test-https-pfx.js @@ -28,16 +28,16 @@ var server = https.createServer(options, function(req, res) { res.end('OK'); }); -server.listen(0, options.host, function() { +server.listen(0, options.host, common.mustCall(function() { options.port = this.address().port; - var data = ''; - https.get(options, function(res) { - res.on('data', function(data_) { data += data_; }); - res.on('end', function() { server.close(); }); - }); + https.get(options, common.mustCall(function(res) { + var data = ''; - process.on('exit', function() { - assert.equal(data, 'OK'); - }); -}); + res.on('data', function(data_) { data += data_; }); + res.on('end', common.mustCall(function() { + assert.strictEqual(data, 'OK'); + server.close(); + })); + })); +})); diff --git a/test/parallel/test-https-req-split.js b/test/parallel/test-https-req-split.js index c9707ab43906d4..6dc6097dc216ae 100644 --- a/test/parallel/test-https-req-split.js +++ b/test/parallel/test-https-req-split.js @@ -3,7 +3,6 @@ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0'; var common = require('../common'); -var assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -14,8 +13,6 @@ var https = require('https'); var tls = require('tls'); var fs = require('fs'); -var seen_req = false; - var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') @@ -25,13 +22,12 @@ var options = { tls.SLAB_BUFFER_SIZE = 1; var server = https.createServer(options); -server.on('upgrade', function(req, socket, upgrade) { +server.on('upgrade', common.mustCall(function(req, socket, upgrade) { socket.on('data', function(data) { throw new Error('Unexpected data: ' + data); }); socket.end('HTTP/1.1 200 Ok\r\n\r\n'); - seen_req = true; -}); +})); server.listen(0, function() { var req = https.request({ @@ -49,8 +45,3 @@ server.listen(0, function() { req.end(); }); - -process.on('exit', function() { - assert(seen_req); - console.log('ok'); -}); diff --git a/test/parallel/test-https-set-timeout-server.js b/test/parallel/test-https-set-timeout-server.js index 298ec51587b07f..fd00a521a03cb5 100644 --- a/test/parallel/test-https-set-timeout-server.js +++ b/test/parallel/test-https-set-timeout-server.js @@ -35,42 +35,34 @@ function run() { } test(function serverTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); var server = https.createServer(serverOptions, function(req, res) { // just do nothing, we should get a timeout event. }); - server.listen(0, function() { - var s = server.setTimeout(50, function(socket) { - caughtTimeout = true; + server.listen(0, common.mustCall(function() { + var s = server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); - }); + })); assert.ok(s instanceof https.Server); https.get({ port: this.address().port, rejectUnauthorized: false }).on('error', function() {}); - }); + })); }); test(function serverRequestTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); - var server = https.createServer(serverOptions, function(req, res) { + function handler(req, res) { // just do nothing, we should get a timeout event. - req.setTimeout(50, function() { - caughtTimeout = true; + req.setTimeout(50, common.mustCall(function() { req.socket.destroy(); server.close(); cb(); - }); - }); + })); + } + + var server = https.createServer(serverOptions, common.mustCall(handler)); server.listen(0, function() { var req = https.request({ port: this.address().port, @@ -84,19 +76,16 @@ test(function serverRequestTimeout(cb) { }); test(function serverResponseTimeout(cb) { - var caughtTimeout = false; - process.on('exit', function() { - assert(caughtTimeout); - }); - var server = https.createServer(serverOptions, function(req, res) { + function handler(req, res) { // just do nothing, we should get a timeout event. - res.setTimeout(50, function() { - caughtTimeout = true; + res.setTimeout(50, common.mustCall(function() { res.socket.destroy(); server.close(); cb(); - }); - }); + })); + } + + var server = https.createServer(serverOptions, common.mustCall(handler)); server.listen(0, function() { https.get({ port: this.address().port, @@ -106,21 +95,12 @@ test(function serverResponseTimeout(cb) { }); test(function serverRequestNotTimeoutAfterEnd(cb) { - var caughtTimeoutOnRequest = false; - var caughtTimeoutOnResponse = false; - process.on('exit', function() { - assert(!caughtTimeoutOnRequest); - assert(caughtTimeoutOnResponse); - }); - var server = https.createServer(serverOptions, function(req, res) { + function handler(req, res) { // just do nothing, we should get a timeout event. - req.setTimeout(50, function(socket) { - caughtTimeoutOnRequest = true; - }); - res.on('timeout', function(socket) { - caughtTimeoutOnResponse = true; - }); - }); + req.setTimeout(50, common.fail); + res.on('timeout', common.mustCall(function(socket) {})); + } + var server = https.createServer(serverOptions, common.mustCall(handler)); server.on('timeout', function(socket) { socket.destroy(); server.close(); @@ -165,29 +145,17 @@ test(function serverResponseTimeoutWithPipeline(cb) { }); test(function idleTimeout(cb) { - var caughtTimeoutOnRequest = false; - var caughtTimeoutOnResponse = false; - var caughtTimeoutOnServer = false; - process.on('exit', function() { - assert(!caughtTimeoutOnRequest); - assert(!caughtTimeoutOnResponse); - assert(caughtTimeoutOnServer); - }); - var server = https.createServer(serverOptions, function(req, res) { - req.on('timeout', function(socket) { - caughtTimeoutOnRequest = true; - }); - res.on('timeout', function(socket) { - caughtTimeoutOnResponse = true; - }); - res.end(); - }); - server.setTimeout(50, function(socket) { - caughtTimeoutOnServer = true; + var server = https.createServer(serverOptions, + common.mustCall(function(req, res) { + req.on('timeout', common.fail); + res.on('timeout', common.fail); + res.end(); + })); + server.setTimeout(50, common.mustCall(function(socket) { socket.destroy(); server.close(); cb(); - }); + })); server.listen(0, function() { var options = { port: this.address().port, diff --git a/test/parallel/test-https-timeout-server.js b/test/parallel/test-https-timeout-server.js index e084ec556b9c76..92b06f1495ddbf 100644 --- a/test/parallel/test-https-timeout-server.js +++ b/test/parallel/test-https-timeout-server.js @@ -11,12 +11,6 @@ var https = require('https'); var net = require('net'); var fs = require('fs'); -var clientErrors = 0; - -process.on('exit', function() { - assert.equal(clientErrors, 1); -}); - var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), @@ -25,15 +19,14 @@ var options = { var server = https.createServer(options, common.fail); -server.on('clientError', function(err, conn) { +server.on('clientError', common.mustCall(function(err, conn) { // Don't hesitate to update the asserts if the internal structure of // the cleartext object ever changes. We're checking that the https.Server // has closed the client connection. assert.equal(conn._secureEstablished, false); server.close(); - clientErrors++; conn.destroy(); -}); +})); server.listen(0, function() { net.connect({ host: '127.0.0.1', port: this.address().port }); diff --git a/test/parallel/test-listen-fd-ebadf.js b/test/parallel/test-listen-fd-ebadf.js index 452eb7e14046d5..09beda067b5e71 100644 --- a/test/parallel/test-listen-fd-ebadf.js +++ b/test/parallel/test-listen-fd-ebadf.js @@ -3,16 +3,11 @@ var common = require('../common'); var assert = require('assert'); var net = require('net'); -var gotError = 0; - -process.on('exit', function() { - assert.equal(gotError, 2); -}); - -net.createServer(common.fail).listen({fd: 2}).on('error', onError); -net.createServer(common.fail).listen({fd: 42}).on('error', onError); +net.createServer(common.fail).listen({fd: 2}) + .on('error', common.mustCall(onError)); +net.createServer(common.fail).listen({fd: 42}) + .on('error', common.mustCall(onError)); function onError(ex) { assert.equal(ex.code, 'EINVAL'); - gotError++; } diff --git a/test/parallel/test-net-after-close.js b/test/parallel/test-net-after-close.js index 05782477891ec9..a73663e7da86db 100644 --- a/test/parallel/test-net-after-close.js +++ b/test/parallel/test-net-after-close.js @@ -1,20 +1,18 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var closed = false; var server = net.createServer(function(s) { console.error('SERVER: got connection'); s.end(); }); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var c = net.createConnection(this.address().port); - c.on('close', function() { + c.on('close', common.mustCall(function() { console.error('connection closed'); assert.strictEqual(c._handle, null); - closed = true; assert.doesNotThrow(function() { c.setNoDelay(); c.setKeepAlive(); @@ -26,9 +24,5 @@ server.listen(0, function() { c.remotePort; }); server.close(); - }); -}); - -process.on('exit', function() { - assert(closed); -}); + })); +})); diff --git a/test/parallel/test-net-bind-twice.js b/test/parallel/test-net-bind-twice.js index d8ea1b34a5ca36..9b9fc7c5db37dd 100644 --- a/test/parallel/test-net-bind-twice.js +++ b/test/parallel/test-net-bind-twice.js @@ -1,26 +1,15 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var gotError = false; +var server1 = net.createServer(common.fail); +server1.listen(0, '127.0.0.1', common.mustCall(function() { + var server2 = net.createServer(common.fail); + server2.listen(this.address().port, '127.0.0.1', common.fail); -process.on('exit', function() { - assert(gotError); -}); - -function dontCall() { - assert(false); -} - -var server1 = net.createServer(dontCall); -server1.listen(0, '127.0.0.1', function() { - var server2 = net.createServer(dontCall); - server2.listen(this.address().port, '127.0.0.1', dontCall); - - server2.on('error', function(e) { + server2.on('error', common.mustCall(function(e) { assert.equal(e.code, 'EADDRINUSE'); server1.close(); - gotError = true; - }); -}); + })); +})); diff --git a/test/parallel/test-net-can-reset-timeout.js b/test/parallel/test-net-can-reset-timeout.js index a63932e1ad5c1e..7dbd5cad2ae6bb 100644 --- a/test/parallel/test-net-can-reset-timeout.js +++ b/test/parallel/test-net-can-reset-timeout.js @@ -1,29 +1,23 @@ 'use strict'; -require('../common'); +const common = require('../common'); var net = require('net'); -var assert = require('assert'); -var timeoutCount = 0; - -var server = net.createServer(function(stream) { +var server = net.createServer(common.mustCall(function(stream) { stream.setTimeout(100); stream.resume(); - stream.on('timeout', function() { + stream.on('timeout', common.mustCall(function() { console.log('timeout'); // try to reset the timeout. stream.write('WHAT.'); - // don't worry, the socket didn't *really* time out, we're just thinking - // it did. - timeoutCount += 1; - }); + })); stream.on('end', function() { console.log('server side end'); stream.end(); }); -}); +})); server.listen(0, function() { var c = net.createConnection(this.address().port); @@ -37,8 +31,3 @@ server.listen(0, function() { server.close(); }); }); - - -process.on('exit', function() { - assert.equal(1, timeoutCount); -}); diff --git a/test/parallel/test-net-connect-handle-econnrefused.js b/test/parallel/test-net-connect-handle-econnrefused.js index 0a8ce081680f76..bbfb5c1bec1836 100644 --- a/test/parallel/test-net-connect-handle-econnrefused.js +++ b/test/parallel/test-net-connect-handle-econnrefused.js @@ -12,14 +12,7 @@ c.on('connect', function() { assert.ok(false); }); -var gotError = false; -c.on('error', function(e) { +c.on('error', common.mustCall(function(e) { console.error('couldn\'t connect.'); - gotError = true; assert.equal('ECONNREFUSED', e.code); -}); - - -process.on('exit', function() { - assert.ok(gotError); -}); +})); diff --git a/test/parallel/test-net-connect-options.js b/test/parallel/test-net-connect-options.js index 302a8a9bbc0f89..3446790d7b3c4a 100644 --- a/test/parallel/test-net-connect-options.js +++ b/test/parallel/test-net-connect-options.js @@ -1,42 +1,32 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var serverGotEnd = false; -var clientGotEnd = false; - -var server = net.createServer({allowHalfOpen: true}, function(socket) { +var server = net.createServer({ + allowHalfOpen: true +}, common.mustCall(function(socket) { socket.resume(); - socket.on('end', function() { - serverGotEnd = true; - }); + socket.on('end', common.mustCall(function() {})); socket.end(); -}); +})); server.listen(0, function() { var client = net.connect({ host: '127.0.0.1', port: this.address().port, allowHalfOpen: true - }, function() { + }, common.mustCall(function() { console.error('client connect cb'); client.resume(); - client.on('end', function() { - clientGotEnd = true; + client.on('end', common.mustCall(function() { setTimeout(function() { assert(client.writable); client.end(); }, 10); - }); + })); client.on('close', function() { server.close(); }); - }); -}); - -process.on('exit', function() { - console.error('exit', serverGotEnd, clientGotEnd); - assert(serverGotEnd); - assert(clientGotEnd); + })); }); diff --git a/test/parallel/test-net-dns-custom-lookup.js b/test/parallel/test-net-dns-custom-lookup.js index 12dc4d68d2ebe5..8d91bcba6687ea 100644 --- a/test/parallel/test-net-dns-custom-lookup.js +++ b/test/parallel/test-net-dns-custom-lookup.js @@ -2,7 +2,6 @@ var common = require('../common'); var assert = require('assert'); var net = require('net'); -var ok = false; function check(addressType, cb) { var server = net.createServer(function(client) { @@ -12,19 +11,18 @@ function check(addressType, cb) { }); var address = addressType === 4 ? common.localhostIPv4 : '::1'; - server.listen(0, address, function() { + server.listen(0, address, common.mustCall(function() { net.connect({ port: this.address().port, host: 'localhost', family: addressType, lookup: lookup - }).on('lookup', function(err, ip, type) { + }).on('lookup', common.mustCall(function(err, ip, type) { assert.equal(err, null); assert.equal(address, ip); assert.equal(type, addressType); - ok = true; - }); - }); + })); + })); function lookup(host, dnsopts, cb) { dnsopts.family = addressType; @@ -43,7 +41,3 @@ function check(addressType, cb) { check(4, function() { common.hasIPv6 && check(6); }); - -process.on('exit', function() { - assert.ok(ok); -}); diff --git a/test/parallel/test-net-dns-error.js b/test/parallel/test-net-dns-error.js index eed59cddebb851..b36d84d3e9e214 100644 --- a/test/parallel/test-net-dns-error.js +++ b/test/parallel/test-net-dns-error.js @@ -1,12 +1,9 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var expected_bad_connections = 1; -var actual_bad_connections = 0; - var host = '*'.repeat(256); function do_not_call() { @@ -14,17 +11,12 @@ function do_not_call() { } var socket = net.connect(42, host, do_not_call); -socket.on('error', function(err) { +socket.on('error', common.mustCall(function(err) { assert.equal(err.code, 'ENOTFOUND'); - actual_bad_connections++; -}); +})); socket.on('lookup', function(err, ip, type) { assert(err instanceof Error); assert.equal(err.code, 'ENOTFOUND'); assert.equal(ip, undefined); assert.equal(type, undefined); }); - -process.on('exit', function() { - assert.equal(actual_bad_connections, expected_bad_connections); -}); diff --git a/test/parallel/test-net-dns-lookup.js b/test/parallel/test-net-dns-lookup.js index 31576edd2b7503..4f3cd2991cf925 100644 --- a/test/parallel/test-net-dns-lookup.js +++ b/test/parallel/test-net-dns-lookup.js @@ -1,25 +1,19 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var ok = false; var server = net.createServer(function(client) { client.end(); server.close(); }); -server.listen(0, '127.0.0.1', function() { +server.listen(0, '127.0.0.1', common.mustCall(function() { net.connect(this.address().port, 'localhost') - .on('lookup', function(err, ip, type, host) { + .on('lookup', common.mustCall(function(err, ip, type, host) { assert.equal(err, null); assert.equal(ip, '127.0.0.1'); assert.equal(type, '4'); assert.equal(host, 'localhost'); - ok = true; - }); -}); - -process.on('exit', function() { - assert(ok); -}); + })); +})); diff --git a/test/parallel/test-net-during-close.js b/test/parallel/test-net-during-close.js index 24510acac753b7..2649995f89a02f 100644 --- a/test/parallel/test-net-during-close.js +++ b/test/parallel/test-net-during-close.js @@ -1,14 +1,13 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var accessedProperties = false; var server = net.createServer(function(socket) { socket.end(); }); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var client = net.createConnection(this.address().port); server.close(); // server connection event has not yet fired @@ -18,11 +17,6 @@ server.listen(0, function() { client.remoteFamily; client.remotePort; }); - accessedProperties = true; // exit now, do not wait for the client error event process.exit(0); -}); - -process.on('exit', function() { - assert(accessedProperties); -}); +})); diff --git a/test/parallel/test-net-large-string.js b/test/parallel/test-net-large-string.js index 8feb35c067d0d4..b469b0289546a1 100644 --- a/test/parallel/test-net-large-string.js +++ b/test/parallel/test-net-large-string.js @@ -1,22 +1,24 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); var kPoolSize = 40 * 1024; var data = 'あ'.repeat(kPoolSize); -var receivedSize = 0; var encoding = 'UTF-8'; -var server = net.createServer(function(socket) { +var server = net.createServer(common.mustCall(function(socket) { + var receivedSize = 0; + socket.setEncoding(encoding); socket.on('data', function(data) { receivedSize += data.length; }); - socket.on('end', function() { + socket.on('end', common.mustCall(function() { + assert.strictEqual(receivedSize, kPoolSize); socket.end(); - }); -}); + })); +})); server.listen(0, function() { var client = net.createConnection(this.address().port); @@ -26,7 +28,3 @@ server.listen(0, function() { client.write(data, encoding); client.end(); }); - -process.on('exit', function() { - assert.equal(receivedSize, kPoolSize); -}); diff --git a/test/parallel/test-net-listen-close-server-callback-is-not-function.js b/test/parallel/test-net-listen-close-server-callback-is-not-function.js index 6fdb61e85dd4e0..03c08d4f51bf15 100644 --- a/test/parallel/test-net-listen-close-server-callback-is-not-function.js +++ b/test/parallel/test-net-listen-close-server-callback-is-not-function.js @@ -1,19 +1,11 @@ 'use strict'; const common = require('../common'); -var assert = require('assert'); var net = require('net'); var server = net.createServer(common.fail); -var closeEvents = 0; -server.on('close', function() { - ++closeEvents; -}); +server.on('close', common.mustCall(function() {})); server.listen(0, common.fail); server.close('bad argument'); - -process.on('exit', function() { - assert.equal(closeEvents, 1); -}); diff --git a/test/parallel/test-net-listen-close-server.js b/test/parallel/test-net-listen-close-server.js index 47da53de7dae6f..92c7274f328918 100644 --- a/test/parallel/test-net-listen-close-server.js +++ b/test/parallel/test-net-listen-close-server.js @@ -1,15 +1,9 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var net = require('net'); var server = net.createServer(function(socket) { }); -server.listen(0, function() { - assert(false); -}); -server.on('error', function(error) { - console.error(error); - assert(false); -}); +server.listen(0, common.fail); +server.on('error', common.fail); server.close(); diff --git a/test/parallel/test-net-listen-error.js b/test/parallel/test-net-listen-error.js index 4c4d27d703a9a6..9523fcb2e7f456 100644 --- a/test/parallel/test-net-listen-error.js +++ b/test/parallel/test-net-listen-error.js @@ -1,19 +1,8 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var net = require('net'); -var gotError = false; var server = net.createServer(function(socket) { }); -server.listen(1, '1.1.1.1', function() { // EACCESS or EADDRNOTAVAIL - assert(false); -}); -server.on('error', function(error) { - console.error(error); - gotError = true; -}); - -process.on('exit', function() { - assert(gotError); -}); +server.listen(1, '1.1.1.1', common.fail); // EACCESS or EADDRNOTAVAIL +server.on('error', common.mustCall(function(error) {})); diff --git a/test/parallel/test-net-local-address-port.js b/test/parallel/test-net-local-address-port.js index 2f25f53fa82670..5eebdb16be379b 100644 --- a/test/parallel/test-net-local-address-port.js +++ b/test/parallel/test-net-local-address-port.js @@ -3,17 +3,14 @@ var common = require('../common'); var assert = require('assert'); var net = require('net'); -var conns = 0; - -var server = net.createServer(function(socket) { - conns++; +var server = net.createServer(common.mustCall(function(socket) { assert.equal(socket.localAddress, common.localhostIPv4); assert.equal(socket.localPort, this.address().port); socket.on('end', function() { server.close(); }); socket.resume(); -}); +})); server.listen(0, common.localhostIPv4, function() { var client = net.createConnection(this.address().port, common.localhostIPv4); @@ -21,7 +18,3 @@ server.listen(0, common.localhostIPv4, function() { client.end(); }); }); - -process.on('exit', function() { - assert.equal(1, conns); -}); diff --git a/test/parallel/test-net-pause-resume-connecting.js b/test/parallel/test-net-pause-resume-connecting.js index a96a94e22f315c..6f3e78a94a56df 100644 --- a/test/parallel/test-net-pause-resume-connecting.js +++ b/test/parallel/test-net-pause-resume-connecting.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const net = require('net'); @@ -34,7 +34,7 @@ server.listen(0, function() { // Client 3 conn = require('net').createConnection(this.address().port, 'localhost'); conn.pause(); - conn.on('data', onDataError); + conn.on('data', common.fail); scheduleTearDown(conn); @@ -51,15 +51,9 @@ server.listen(0, function() { conn.resume(); conn.resume(); conn.pause(); - conn.on('data', onDataError); + conn.on('data', common.fail); scheduleTearDown(conn); - - // Client helper functions - function onDataError() { - assert(false); - } - function onDataOk() { dataEvents++; } diff --git a/test/parallel/test-net-pipe-connect-errors.js b/test/parallel/test-net-pipe-connect-errors.js index 05216731e8eb2a..1c25c47512020d 100644 --- a/test/parallel/test-net-pipe-connect-errors.js +++ b/test/parallel/test-net-pipe-connect-errors.js @@ -1,12 +1,10 @@ 'use strict'; +var common = require('../common'); var fs = require('fs'); var net = require('net'); var path = require('path'); var assert = require('assert'); -var common = require('../common'); -var notSocketErrorFired = false; -var noEntErrorFired = false; var accessErrorFired = false; // Test if ENOTSOCK is fired when trying to connect to a file which is not @@ -43,11 +41,10 @@ var notSocketClient = net.createConnection(emptyTxt, function() { assert.ok(false); }); -notSocketClient.on('error', function(err) { +notSocketClient.on('error', common.mustCall(function(err) { assert(err.code === 'ENOTSOCK' || err.code === 'ECONNREFUSED', `received ${err.code} instead of ENOTSOCK or ECONNREFUSED`); - notSocketErrorFired = true; -}); +})); // Trying to connect to not-existing socket should result in ENOENT error @@ -55,10 +52,9 @@ var noEntSocketClient = net.createConnection('no-ent-file', function() { assert.ok(false); }); -noEntSocketClient.on('error', function(err) { +noEntSocketClient.on('error', common.mustCall(function(err) { assert.equal(err.code, 'ENOENT'); - noEntErrorFired = true; -}); +})); // On Windows or when running as root, a chmod has no effect on named pipes @@ -85,10 +81,7 @@ if (!common.isWindows && process.getuid() !== 0) { // Assert that all error events were fired process.on('exit', function() { - assert.ok(notSocketErrorFired); - assert.ok(noEntErrorFired); if (!common.isWindows && process.getuid() !== 0) { assert.ok(accessErrorFired); } }); - diff --git a/test/parallel/test-net-remote-address-port.js b/test/parallel/test-net-remote-address-port.js index beb5625ee11858..05c36def3a5e7f 100644 --- a/test/parallel/test-net-remote-address-port.js +++ b/test/parallel/test-net-remote-address-port.js @@ -4,7 +4,7 @@ var assert = require('assert'); var net = require('net'); -var conns = 0, conns_closed = 0; +var conns_closed = 0; var remoteAddrCandidates = [ common.localhostIPv4 ]; if (common.hasIPv6) remoteAddrCandidates.push('::ffff:127.0.0.1'); @@ -12,8 +12,7 @@ if (common.hasIPv6) remoteAddrCandidates.push('::ffff:127.0.0.1'); var remoteFamilyCandidates = ['IPv4']; if (common.hasIPv6) remoteFamilyCandidates.push('IPv6'); -var server = net.createServer(function(socket) { - conns++; +var server = net.createServer(common.mustCall(function(socket) { assert.notEqual(-1, remoteAddrCandidates.indexOf(socket.remoteAddress)); assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); assert.ok(socket.remotePort); @@ -26,7 +25,7 @@ var server = net.createServer(function(socket) { assert.notEqual(-1, remoteFamilyCandidates.indexOf(socket.remoteFamily)); }); socket.resume(); -}); +}, 2)); server.listen(0, 'localhost', function() { var client = net.createConnection(this.address().port, 'localhost'); @@ -52,7 +51,3 @@ server.listen(0, 'localhost', function() { assert.notEqual(-1, remoteFamilyCandidates.indexOf(client2.remoteFamily)); }); }); - -process.on('exit', function() { - assert.equal(2, conns); -}); diff --git a/test/parallel/test-net-server-unref-persistent.js b/test/parallel/test-net-server-unref-persistent.js index 8e8f45f5fd7d20..d68e94cfbda8c8 100644 --- a/test/parallel/test-net-server-unref-persistent.js +++ b/test/parallel/test-net-server-unref-persistent.js @@ -1,8 +1,6 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var net = require('net'); -var closed = false; var server = net.createServer(); // unref before listening @@ -11,11 +9,4 @@ server.listen(); // If the timeout fires, that means the server held the event loop open // and the unref() was not persistent. Close the server and fail the test. -setTimeout(function() { - closed = true; - server.close(); -}, 1000).unref(); - -process.on('exit', function() { - assert.strictEqual(closed, false, 'server should not hold loop open'); -}); +setTimeout(common.fail, 1000).unref(); diff --git a/test/parallel/test-net-server-unref.js b/test/parallel/test-net-server-unref.js index 50c1a5678535f4..91b25887a28d3e 100644 --- a/test/parallel/test-net-server-unref.js +++ b/test/parallel/test-net-server-unref.js @@ -1,19 +1,9 @@ 'use strict'; -require('../common'); -var assert = require('assert'); - +const common = require('../common'); var net = require('net'); -var closed = false; var s = net.createServer(); s.listen(0); s.unref(); -setTimeout(function() { - closed = true; - s.close(); -}, 1000).unref(); - -process.on('exit', function() { - assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); -}); +setTimeout(common.fail, 1000).unref(); diff --git a/test/parallel/test-net-socket-destroy-twice.js b/test/parallel/test-net-socket-destroy-twice.js index f23a70abb2c9a0..917e9849999b05 100644 --- a/test/parallel/test-net-socket-destroy-twice.js +++ b/test/parallel/test-net-socket-destroy-twice.js @@ -1,23 +1,11 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); var net = require('net'); -var nerrors = 0; -var ncloses = 0; - -process.on('exit', function() { - assert.equal(nerrors, 1); - assert.equal(ncloses, 1); -}); - var conn = net.createConnection(common.PORT); -conn.on('error', function() { - nerrors++; +conn.on('error', common.mustCall(function() { conn.destroy(); -}); +})); -conn.on('close', function() { - ncloses++; -}); +conn.on('close', common.mustCall(function() {})); diff --git a/test/parallel/test-net-socket-timeout.js b/test/parallel/test-net-socket-timeout.js index cac562c5abb1ab..54f5ce301cc52e 100644 --- a/test/parallel/test-net-socket-timeout.js +++ b/test/parallel/test-net-socket-timeout.js @@ -28,22 +28,15 @@ for (let i = 0; i < validDelays.length; i++) { }); } -var timedout = false; - var server = net.Server(); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var socket = net.createConnection(this.address().port); - socket.setTimeout(100, function() { - timedout = true; + socket.setTimeout(100, common.mustCall(function() { socket.destroy(); server.close(); clearTimeout(timer); - }); + })); var timer = setTimeout(function() { process.exit(1); }, common.platformTimeout(200)); -}); - -process.on('exit', function() { - assert.ok(timedout); -}); +})); diff --git a/test/parallel/test-net-write-after-close.js b/test/parallel/test-net-write-after-close.js index 243123da033be4..e01aef80f3635b 100644 --- a/test/parallel/test-net-write-after-close.js +++ b/test/parallel/test-net-write-after-close.js @@ -1,32 +1,20 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var net = require('net'); -var gotError = false; -var gotWriteCB = false; - -process.on('exit', function() { - assert(gotError); - assert(gotWriteCB); -}); - -var server = net.createServer(function(socket) { +var server = net.createServer(common.mustCall(function(socket) { socket.resume(); - socket.on('error', function(error) { + socket.on('error', common.mustCall(function(error) { console.error('got error, closing server', error); server.close(); - gotError = true; - }); + })); - setTimeout(function() { + setTimeout(common.mustCall(function() { console.error('about to try to write'); - socket.write('test', function(e) { - gotWriteCB = true; - }); - }, 250); -}); + socket.write('test', common.mustCall(function(e) {})); + }), 250); +})); server.listen(0, function() { var client = net.connect(this.address().port, function() { diff --git a/test/parallel/test-net-write-connect-write.js b/test/parallel/test-net-write-connect-write.js index b8edb0e3b39612..315db6bc02b309 100644 --- a/test/parallel/test-net-write-connect-write.js +++ b/test/parallel/test-net-write-connect-write.js @@ -1,14 +1,14 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var received = ''; - var server = net.createServer(function(socket) { socket.pipe(socket); -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var conn = net.connect(this.address().port); + var received = ''; + conn.setEncoding('utf8'); conn.write('before'); conn.on('connect', function() { @@ -18,11 +18,8 @@ var server = net.createServer(function(socket) { received += buf; conn.end(); }); - conn.on('end', function() { + conn.on('end', common.mustCall(function() { server.close(); - }); -}); - -process.on('exit', function() { - assert.equal(received, 'before' + 'after'); -}); + assert.strictEqual(received, 'before' + 'after'); + })); +})); diff --git a/test/parallel/test-net-write-slow.js b/test/parallel/test-net-write-slow.js index 7abee7d0e7dffb..6054e2b7882ac2 100644 --- a/test/parallel/test-net-write-slow.js +++ b/test/parallel/test-net-write-slow.js @@ -26,7 +26,7 @@ var server = net.createServer(function(socket) { } socket.end(); -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var conn = net.connect(this.address().port); conn.on('data', function(buf) { received += buf.length; @@ -35,11 +35,8 @@ var server = net.createServer(function(socket) { conn.resume(); }, 20); }); - conn.on('end', function() { + conn.on('end', common.mustCall(function() { server.close(); - }); -}); - -process.on('exit', function() { - assert.equal(received, SIZE * N); -}); + assert.strictEqual(received, SIZE * N); + })); +})); diff --git a/test/parallel/test-next-tick.js b/test/parallel/test-next-tick.js index 8b45e8c705fc84..2a98b46da10f17 100644 --- a/test/parallel/test-next-tick.js +++ b/test/parallel/test-next-tick.js @@ -1,28 +1,18 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); -var complete = 0; +process.nextTick(common.mustCall(function() { + process.nextTick(common.mustCall(function() { + process.nextTick(common.mustCall(function() {})); + })); +})); -process.nextTick(function() { - complete++; - process.nextTick(function() { - complete++; - process.nextTick(function() { - complete++; - }); - }); -}); - -setTimeout(function() { - process.nextTick(function() { - complete++; - }); -}, 50); +setTimeout(common.mustCall(function() { + process.nextTick(common.mustCall(function() {})); +}), 50); -process.nextTick(function() { - complete++; -}); +process.nextTick(common.mustCall(function() {})); var obj = {}; @@ -32,8 +22,5 @@ process.nextTick(function(a, b) { }, 42, obj); process.on('exit', function() { - assert.equal(5, complete); - process.nextTick(function() { - throw new Error('this should not occur'); - }); + process.nextTick(common.fail); }); diff --git a/test/parallel/test-pipe-address.js b/test/parallel/test-pipe-address.js index 36488d80f789af..85e3daa3522e78 100644 --- a/test/parallel/test-pipe-address.js +++ b/test/parallel/test-pipe-address.js @@ -2,20 +2,11 @@ var common = require('../common'); var assert = require('assert'); var net = require('net'); - -var address = null; - -var server = net.createServer(function() { - assert(false); // should not be called -}); +var server = net.createServer(common.fail); common.refreshTmpDir(); -server.listen(common.PIPE, function() { - address = server.address(); +server.listen(common.PIPE, common.mustCall(function() { + assert.strictEqual(server.address(), common.PIPE); server.close(); -}); - -process.on('exit', function() { - assert.equal(address, common.PIPE); -}); +})); diff --git a/test/parallel/test-pipe-head.js b/test/parallel/test-pipe-head.js index ac8b16515158eb..dcb4e89137f536 100644 --- a/test/parallel/test-pipe-head.js +++ b/test/parallel/test-pipe-head.js @@ -10,16 +10,8 @@ var script = join(common.fixturesDir, 'print-10-lines.js'); var cmd = '"' + nodePath + '" "' + script + '" | head -2'; -var finished = false; - -exec(cmd, function(err, stdout, stderr) { +exec(cmd, common.mustCall(function(err, stdout, stderr) { if (err) throw err; var lines = stdout.split('\n'); assert.equal(3, lines.length); - finished = true; -}); - - -process.on('exit', function() { - assert.ok(finished); -}); +})); diff --git a/test/parallel/test-pipe-unref.js b/test/parallel/test-pipe-unref.js index ea6f7c95563928..35c25524b4cfc8 100644 --- a/test/parallel/test-pipe-unref.js +++ b/test/parallel/test-pipe-unref.js @@ -1,9 +1,6 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); - var net = require('net'); -var closed = false; common.refreshTmpDir(); @@ -11,11 +8,4 @@ var s = net.Server(); s.listen(common.PIPE); s.unref(); -setTimeout(function() { - closed = true; - s.close(); -}, 1000).unref(); - -process.on('exit', function() { - assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open'); -}); +setTimeout(common.fail, 1000).unref(); diff --git a/test/parallel/test-process-next-tick.js b/test/parallel/test-process-next-tick.js index 6b20cfbe93377b..343511445280d4 100644 --- a/test/parallel/test-process-next-tick.js +++ b/test/parallel/test-process-next-tick.js @@ -1,25 +1,17 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var N = 2; -var tickCount = 0; -var exceptionCount = 0; function cb() { - ++tickCount; throw new Error(); } for (var i = 0; i < N; ++i) { - process.nextTick(cb); + process.nextTick(common.mustCall(cb)); } -process.on('uncaughtException', function() { - ++exceptionCount; -}); +process.on('uncaughtException', common.mustCall(function() {}, N)); process.on('exit', function() { process.removeAllListeners('uncaughtException'); - assert.equal(tickCount, N); - assert.equal(exceptionCount, N); }); diff --git a/test/parallel/test-process-remove-all-signal-listeners.js b/test/parallel/test-process-remove-all-signal-listeners.js index f05e1f9dec79ef..131d57cdfccaa7 100644 --- a/test/parallel/test-process-remove-all-signal-listeners.js +++ b/test/parallel/test-process-remove-all-signal-listeners.js @@ -1,8 +1,8 @@ 'use strict'; +const common = require('../common'); const assert = require('assert'); const spawn = require('child_process').spawn; -const common = require('../common'); if (common.isWindows) { common.skip('Win32 doesn\'t have signals, just a kind of ' + @@ -10,22 +10,15 @@ if (common.isWindows) { return; } -var ok; - if (process.argv[2] !== '--do-test') { // We are the master, fork a child so we can verify it exits with correct // status. process.env.DOTEST = 'y'; var child = spawn(process.execPath, [__filename, '--do-test']); - child.once('exit', function(code, signal) { + child.once('exit', common.mustCall(function(code, signal) { assert.equal(signal, 'SIGINT'); - ok = true; - }); - - process.on('exit', function() { - assert(ok); - }); + })); return; } diff --git a/test/parallel/test-regress-GH-1531.js b/test/parallel/test-regress-GH-1531.js index ae48c907048428..fa0781c2e2fa72 100644 --- a/test/parallel/test-regress-GH-1531.js +++ b/test/parallel/test-regress-GH-1531.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -15,32 +14,24 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var gotCallback = false; - var server = https.createServer(options, function(req, res) { res.writeHead(200); res.end('hello world\n'); }); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { console.error('listening'); https.get({ agent: false, path: '/', port: this.address().port, rejectUnauthorized: false - }, function(res) { + }, common.mustCall(function(res) { console.error(res.statusCode, res.headers); - gotCallback = true; res.resume(); server.close(); - }).on('error', function(e) { + })).on('error', function(e) { console.error(e.stack); process.exit(1); }); -}); - -process.on('exit', function() { - assert.ok(gotCallback); - console.log('ok'); -}); +})); diff --git a/test/parallel/test-regress-GH-3542.js b/test/parallel/test-regress-GH-3542.js index 0d7e89ef9b5b51..8db34e72157371 100644 --- a/test/parallel/test-regress-GH-3542.js +++ b/test/parallel/test-regress-GH-3542.js @@ -3,7 +3,6 @@ const common = require('../common'); const assert = require('assert'); const fs = require('fs'); const path = require('path'); -let succeeded = 0; // This test is only relevant on Windows. if (!common.isWindows) { @@ -15,11 +14,10 @@ function test(p) { var result = fs.realpathSync(p); assert.strictEqual(result.toLowerCase(), path.resolve(p).toLowerCase()); - fs.realpath(p, function(err, result) { + fs.realpath(p, common.mustCall(function(err, result) { assert.ok(!err); assert.strictEqual(result.toLowerCase(), path.resolve(p).toLowerCase()); - succeeded++; - }); + })); } test('//localhost/c$/Windows/System32'); @@ -29,7 +27,3 @@ test('\\\\localhost\\c$\\'); test('C:\\'); test('C:'); test(process.env.windir); - -process.on('exit', function() { - assert.strictEqual(succeeded, 7); -}); diff --git a/test/parallel/test-regress-GH-746.js b/test/parallel/test-regress-GH-746.js index fe827c743302e5..8bfcb0c3e22f12 100644 --- a/test/parallel/test-regress-GH-746.js +++ b/test/parallel/test-regress-GH-746.js @@ -2,19 +2,16 @@ // Just test that destroying stdin doesn't mess up listening on a server. // This is a regression test for GH-746. -require('../common'); -var assert = require('assert'); +const common = require('../common'); var net = require('net'); process.stdin.destroy(); -var accepted = null; -var server = net.createServer(function(socket) { +var server = net.createServer(common.mustCall(function(socket) { console.log('accepted'); - accepted = socket; socket.end(); server.close(); -}); +})); server.listen(0, function() { @@ -22,9 +19,3 @@ server.listen(0, function() { net.createConnection(this.address().port); }); - - -process.on('exit', function() { - assert.ok(accepted); -}); - diff --git a/test/parallel/test-sigint-infinite-loop.js b/test/parallel/test-sigint-infinite-loop.js index 1570f9c59dd5d3..ecd64802acb627 100644 --- a/test/parallel/test-sigint-infinite-loop.js +++ b/test/parallel/test-sigint-infinite-loop.js @@ -2,7 +2,7 @@ // This test is to assert that we can SIGINT a script which loops forever. // Ref(http): // groups.google.com/group/nodejs-dev/browse_thread/thread/e20f2f8df0296d3f -require('../common'); +const common = require('../common'); var assert = require('assert'); var spawn = require('child_process').spawn; @@ -11,7 +11,6 @@ console.log('start'); var c = spawn(process.execPath, ['-e', 'while(true) { console.log("hi"); }']); var sentKill = false; -var gotChildExit = true; c.stdout.on('data', function(s) { // Prevent race condition: @@ -25,14 +24,11 @@ c.stdout.on('data', function(s) { } }); -c.on('exit', function(code) { +c.on('exit', common.mustCall(function(code) { assert.ok(code !== 0); console.log('killed infinite-loop.js'); - gotChildExit = true; -}); +})); process.on('exit', function() { assert.ok(sentKill); - assert.ok(gotChildExit); }); - diff --git a/test/parallel/test-signal-handler.js b/test/parallel/test-signal-handler.js index 43198de726d20e..a058c7ef31007c 100644 --- a/test/parallel/test-signal-handler.js +++ b/test/parallel/test-signal-handler.js @@ -1,7 +1,6 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); if (common.isWindows) { common.skip('SIGUSR1 and SIGHUP signals are not supported'); @@ -10,23 +9,14 @@ if (common.isWindows) { console.log('process.pid: ' + process.pid); -let first = 0; -let second = 0; +process.on('SIGUSR1', common.mustCall(function() {})); -var sighup = false; - -process.on('SIGUSR1', function() { - console.log('Interrupted by SIGUSR1'); - first += 1; -}); - -process.on('SIGUSR1', function() { - second += 1; +process.on('SIGUSR1', common.mustCall(function() { setTimeout(function() { console.log('End.'); process.exit(0); }, 5); -}); +})); var i = 0; setInterval(function() { @@ -41,11 +31,5 @@ setInterval(function() { // has been previously registered, and `process.listeners(SIGNAL).length === 1` process.on('SIGHUP', function() {}); process.removeAllListeners('SIGHUP'); -process.on('SIGHUP', function() { sighup = true; }); +process.on('SIGHUP', common.mustCall(function() {})); process.kill(process.pid, 'SIGHUP'); - -process.on('exit', function() { - assert.equal(1, first); - assert.equal(1, second); - assert.equal(true, sighup); -}); diff --git a/test/parallel/test-socket-write-after-fin.js b/test/parallel/test-socket-write-after-fin.js index f7e3d5fe4e78e8..70f0d9bf843f9b 100644 --- a/test/parallel/test-socket-write-after-fin.js +++ b/test/parallel/test-socket-write-after-fin.js @@ -1,44 +1,39 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var net = require('net'); -var serverData = ''; -var gotServerEnd = false; -var clientData = ''; -var gotClientEnd = false; +const expected = 'hello1hello2hello3\nTHUNDERMUSCLE!'; + +var server = net.createServer({ + allowHalfOpen: true +}, common.mustCall(function(sock) { + var serverData = ''; -var server = net.createServer({ allowHalfOpen: true }, function(sock) { sock.setEncoding('utf8'); sock.on('data', function(c) { serverData += c; }); - sock.on('end', function() { - gotServerEnd = true; + sock.on('end', common.mustCall(function() { + assert.strictEqual(serverData, expected); sock.end(serverData); server.close(); - }); -}); -server.listen(0, function() { + })); +})); +server.listen(0, common.mustCall(function() { var sock = net.connect(this.address().port); + var clientData = ''; + sock.setEncoding('utf8'); sock.on('data', function(c) { clientData += c; }); - sock.on('end', function() { - gotClientEnd = true; - }); - - process.on('exit', function() { - assert.equal(serverData, clientData); - assert.equal(serverData, 'hello1hello2hello3\nTHUNDERMUSCLE!'); - assert(gotClientEnd); - assert(gotServerEnd); - console.log('ok'); - }); + sock.on('end', common.mustCall(function() { + assert.strictEqual(clientData, expected); + })); sock.write('hello1'); sock.write('hello2'); sock.write('hello3\n'); sock.end('THUNDERMUSCLE!'); -}); +})); diff --git a/test/parallel/test-stdout-close-unref.js b/test/parallel/test-stdout-close-unref.js index 67c6141c963088..fcabc1f66af58a 100644 --- a/test/parallel/test-stdout-close-unref.js +++ b/test/parallel/test-stdout-close-unref.js @@ -1,21 +1,12 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const spawn = require('child_process').spawn; if (process.argv[2] === 'child') { - var errs = 0; - process.stdin.resume(); process.stdin._handle.close(); process.stdin._handle.unref(); // Should not segfault. - process.stdin.on('error', function(err) { - errs++; - }); - - process.on('exit', function() { - assert.strictEqual(errs, 1); - }); + process.stdin.on('error', common.mustCall(function(err) {})); return; } diff --git a/test/parallel/test-stdout-stderr-reading.js b/test/parallel/test-stdout-stderr-reading.js index 2cc029c501c162..e154d41b6bb8d1 100644 --- a/test/parallel/test-stdout-stderr-reading.js +++ b/test/parallel/test-stdout-stderr-reading.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); // verify that stdout is never read from. @@ -22,7 +22,6 @@ else function parent() { var spawn = require('child_process').spawn; var node = process.execPath; - var closes = 0; var c1 = spawn(node, [__filename, 'child']); var c1out = ''; @@ -34,13 +33,12 @@ function parent() { c1.stderr.on('data', function(chunk) { console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); }); - c1.on('close', function(code, signal) { - closes++; + c1.on('close', common.mustCall(function(code, signal) { assert(!code); assert(!signal); assert.equal(c1out, 'ok\n'); console.log('ok'); - }); + })); var c2 = spawn(node, ['-e', 'console.log("ok")']); var c2out = ''; @@ -52,17 +50,12 @@ function parent() { c1.stderr.on('data', function(chunk) { console.error('c1err: ' + chunk.split('\n').join('\nc1err: ')); }); - c2.on('close', function(code, signal) { - closes++; + c2.on('close', common.mustCall(function(code, signal) { assert(!code); assert(!signal); assert.equal(c2out, 'ok\n'); console.log('ok'); - }); - - process.on('exit', function() { - assert.equal(closes, 2, 'saw both closes'); - }); + })); } function child() { diff --git a/test/parallel/test-stdout-to-file.js b/test/parallel/test-stdout-to-file.js index bd1d97b3d8d278..5dce369aadb52e 100644 --- a/test/parallel/test-stdout-to-file.js +++ b/test/parallel/test-stdout-to-file.js @@ -42,15 +42,9 @@ function test(size, useBuffer, cb) { }); } -var finished = false; -test(1024 * 1024, false, function() { +test(1024 * 1024, false, common.mustCall(function() { console.log('Done printing with string'); - test(1024 * 1024, true, function() { + test(1024 * 1024, true, common.mustCall(function() { console.log('Done printing with buffer'); - finished = true; - }); -}); - -process.on('exit', function() { - assert.ok(finished); -}); + })); +})); diff --git a/test/parallel/test-stream-end-paused.js b/test/parallel/test-stream-end-paused.js index 9cc32db880ea88..96a9c4ee132513 100644 --- a/test/parallel/test-stream-end-paused.js +++ b/test/parallel/test-stream-end-paused.js @@ -1,7 +1,6 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); -var gotEnd = false; // Make sure we don't miss the end event for paused 0-length streams @@ -19,15 +18,12 @@ stream.on('data', function() { }); stream.pause(); -setTimeout(function() { - stream.on('end', function() { - gotEnd = true; - }); +setTimeout(common.mustCall(function() { + stream.on('end', common.mustCall(function() {})); stream.resume(); -}); +})); process.on('exit', function() { - assert(gotEnd); assert(calledRead); console.log('ok'); }); diff --git a/test/parallel/test-stream-pipe-error-handling.js b/test/parallel/test-stream-pipe-error-handling.js index b2c25cfe8c6e22..3b36768805c9ec 100644 --- a/test/parallel/test-stream-pipe-error-handling.js +++ b/test/parallel/test-stream-pipe-error-handling.js @@ -45,14 +45,14 @@ const Stream = require('stream').Stream; const w = new W(); let removed = false; - r._read = function() { + r._read = common.mustCall(function() { setTimeout(common.mustCall(function() { assert(removed); assert.throws(function() { w.emit('error', new Error('fail')); }); })); - }; + }); w.on('error', myOnError); r.pipe(w); @@ -72,12 +72,12 @@ const Stream = require('stream').Stream; const w = new W(); let removed = false; - r._read = function() { + r._read = common.mustCall(function() { setTimeout(common.mustCall(function() { assert(removed); w.emit('error', new Error('fail')); })); - }; + }); w.on('error', common.mustCall(function(er) {})); w._write = function() {}; diff --git a/test/parallel/test-stream-wrap.js b/test/parallel/test-stream-wrap.js index 5a8b75d4dc1f19..69e4dee89d3b13 100644 --- a/test/parallel/test-stream-wrap.js +++ b/test/parallel/test-stream-wrap.js @@ -1,13 +1,11 @@ 'use strict'; -require('../common'); +const common = require('../common'); const assert = require('assert'); const StreamWrap = require('_stream_wrap'); const Duplex = require('stream').Duplex; const ShutdownWrap = process.binding('stream_wrap').ShutdownWrap; -var done = false; - function testShutdown(callback) { var stream = new Duplex({ read: function() { @@ -30,10 +28,4 @@ function testShutdown(callback) { req.handle.shutdown(req); } -testShutdown(function() { - done = true; -}); - -process.on('exit', function() { - assert(done); -}); +testShutdown(common.mustCall(function() {})); diff --git a/test/parallel/test-stream2-httpclient-response-end.js b/test/parallel/test-stream2-httpclient-response-end.js index d1244be4c7b74e..d674086055e431 100644 --- a/test/parallel/test-stream2-httpclient-response-end.js +++ b/test/parallel/test-stream2-httpclient-response-end.js @@ -1,32 +1,22 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var http = require('http'); var msg = 'Hello'; -var readable_event = false; -var end_event = false; var server = http.createServer(function(req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end(msg); }).listen(0, function() { http.get({port: this.address().port}, function(res) { var data = ''; - res.on('readable', function() { + res.on('readable', common.mustCall(function() { console.log('readable event'); - readable_event = true; data += res.read(); - }); - res.on('end', function() { + })); + res.on('end', common.mustCall(function() { console.log('end event'); - end_event = true; assert.strictEqual(msg, data); server.close(); - }); + })); }); }); - -process.on('exit', function() { - assert(readable_event); - assert(end_event); -}); - diff --git a/test/parallel/test-stream2-large-read-stall.js b/test/parallel/test-stream2-large-read-stall.js index 0f28db508a4cde..823407d396afb6 100644 --- a/test/parallel/test-stream2-large-read-stall.js +++ b/test/parallel/test-stream2-large-read-stall.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); // If everything aligns so that you do a read(n) of exactly the @@ -32,11 +32,7 @@ r.on('readable', function() { rs.length); }); -var endEmitted = false; -r.on('end', function() { - endEmitted = true; - console.error('end'); -}); +r.on('end', common.mustCall(function() {})); var pushes = 0; function push() { @@ -55,5 +51,4 @@ function push() { process.on('exit', function() { assert.equal(pushes, PUSHCOUNT + 1); - assert(endEmitted); }); diff --git a/test/parallel/test-stream2-read-sync-stack.js b/test/parallel/test-stream2-read-sync-stack.js index 6ed645948c2814..b2cfd05f872e30 100644 --- a/test/parallel/test-stream2-read-sync-stack.js +++ b/test/parallel/test-stream2-read-sync-stack.js @@ -1,6 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var Readable = require('stream').Readable; var r = new Readable(); var N = 256 * 1024; @@ -21,14 +20,6 @@ r.on('readable', function onReadable() { r.read(N * 2); }); -var ended = false; -r.on('end', function onEnd() { - ended = true; -}); +r.on('end', common.mustCall(function() {})); r.read(0); - -process.on('exit', function() { - assert(ended); - console.log('ok'); -}); diff --git a/test/parallel/test-stream2-readable-legacy-drain.js b/test/parallel/test-stream2-readable-legacy-drain.js index b41de6a38ef702..8a0687a6ebd90c 100644 --- a/test/parallel/test-stream2-readable-legacy-drain.js +++ b/test/parallel/test-stream2-readable-legacy-drain.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var Stream = require('stream'); @@ -12,10 +12,7 @@ r._read = function(n) { return r.push(++reads === N ? null : Buffer.allocUnsafe(1)); }; -var rended = false; -r.on('end', function() { - rended = true; -}); +r.on('end', common.mustCall(function() {})); var w = new Stream(); w.writable = true; @@ -32,11 +29,7 @@ function drain() { w.emit('drain'); } - -var wended = false; -w.end = function() { - wended = true; -}; +w.end = common.mustCall(function() {}); // Just for kicks, let's mess with the drain count. // This verifies that even if it gets negative in the @@ -46,8 +39,3 @@ r.on('readable', function() { }); r.pipe(w); -process.on('exit', function() { - assert(rended); - assert(wended); - console.error('ok'); -}); diff --git a/test/parallel/test-stream2-readable-non-empty-end.js b/test/parallel/test-stream2-readable-non-empty-end.js index e337485b63f21e..c08cc287ce1cbf 100644 --- a/test/parallel/test-stream2-readable-non-empty-end.js +++ b/test/parallel/test-stream2-readable-non-empty-end.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var Readable = require('_stream_readable'); @@ -40,14 +40,7 @@ test.read(0); function next() { // now let's make 'end' happen test.removeListener('end', thrower); - - var endEmitted = false; - process.on('exit', function() { - assert(endEmitted, 'end should be emitted by now'); - }); - test.on('end', function() { - endEmitted = true; - }); + test.on('end', common.mustCall(function() {})); // one to get the last byte var r = test.read(); diff --git a/test/parallel/test-stream2-readable-wrap-empty.js b/test/parallel/test-stream2-readable-wrap-empty.js index d2bf8f3f306f6d..02de3cf5b4cb23 100644 --- a/test/parallel/test-stream2-readable-wrap-empty.js +++ b/test/parallel/test-stream2-readable-wrap-empty.js @@ -1,6 +1,5 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var Readable = require('_stream_readable'); var EE = require('events').EventEmitter; @@ -11,13 +10,8 @@ oldStream.resume = function() {}; var newStream = new Readable().wrap(oldStream); -var ended = false; newStream .on('readable', function() {}) - .on('end', function() { ended = true; }); + .on('end', common.mustCall(function() {})); oldStream.emit('end'); - -process.on('exit', function() { - assert.ok(ended); -}); diff --git a/test/parallel/test-tls-0-dns-altname.js b/test/parallel/test-tls-0-dns-altname.js index 019304a4ba8e4d..4ae9f2c91b00ad 100644 --- a/test/parallel/test-tls-0-dns-altname.js +++ b/test/parallel/test-tls-0-dns-altname.js @@ -10,8 +10,6 @@ var tls = require('tls'); var fs = require('fs'); -var requests = 0; - var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/0-dns-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/0-dns-cert.pem') @@ -20,11 +18,10 @@ var server = tls.createServer({ c.destroy(); server.close(); }); -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var c = tls.connect(this.address().port, { rejectUnauthorized: false - }, function() { - requests++; + }, common.mustCall(function() { var cert = c.getPeerCertificate(); assert.equal(cert.subjectaltname, 'DNS:google.com\0.evil.com, ' + @@ -33,9 +30,5 @@ var server = tls.createServer({ 'IP Address:8.8.4.4, ' + 'DNS:last.com'); c.write('ok'); - }); -}); - -process.on('exit', function() { - assert.equal(requests, 1); -}); + })); +})); diff --git a/test/parallel/test-tls-cert-regression.js b/test/parallel/test-tls-cert-regression.js index b3f76aa37967da..a26bab7c46e107 100644 --- a/test/parallel/test-tls-cert-regression.js +++ b/test/parallel/test-tls-cert-regression.js @@ -1,5 +1,4 @@ 'use strict'; -var assert = require('assert'); var common = require('../common'); if (!common.hasCrypto) { @@ -42,13 +41,6 @@ function test(cert, key, cb) { }); } -var completed = false; -test(cert, key, function() { - test(Buffer.from(cert), Buffer.from(key), function() { - completed = true; - }); -}); - -process.on('exit', function() { - assert(completed); -}); +test(cert, key, common.mustCall(function() { + test(Buffer.from(cert), Buffer.from(key), common.mustCall(function() {})); +})); diff --git a/test/parallel/test-tls-client-abort2.js b/test/parallel/test-tls-client-abort2.js index 4bb8f00cf5fc30..f3295f6d854a72 100644 --- a/test/parallel/test-tls-client-abort2.js +++ b/test/parallel/test-tls-client-abort2.js @@ -8,18 +8,9 @@ if (!common.hasCrypto) { } var tls = require('tls'); -var errors = 0; - -var conn = tls.connect(common.PORT, function() { - assert(false); // callback should never be executed -}); -conn.on('error', function() { - ++errors; +var conn = tls.connect(common.PORT, common.fail); +conn.on('error', common.mustCall(function() { assert.doesNotThrow(function() { conn.destroy(); }); -}); - -process.on('exit', function() { - assert.equal(errors, 1); -}); +})); diff --git a/test/parallel/test-tls-client-destroy-soon.js b/test/parallel/test-tls-client-destroy-soon.js index 7535519bcfff47..171aa328142e13 100644 --- a/test/parallel/test-tls-client-destroy-soon.js +++ b/test/parallel/test-tls-client-destroy-soon.js @@ -20,35 +20,30 @@ var options = { }; var big = Buffer.alloc(2 * 1024 * 1024, 'Y'); -var connections = 0; -var bytesRead = 0; // create server -var server = tls.createServer(options, function(socket) { +var server = tls.createServer(options, common.mustCall(function(socket) { socket.end(big); socket.destroySoon(); - connections++; -}); +})); // start listening -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var client = tls.connect({ port: this.address().port, rejectUnauthorized: false - }, function() { + }, common.mustCall(function() { + var bytesRead = 0; + client.on('readable', function() { var d = client.read(); if (d) bytesRead += d.length; }); - client.on('end', function() { + client.on('end', common.mustCall(function() { server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(1, connections); - assert.equal(big.length, bytesRead); -}); + assert.strictEqual(big.length, bytesRead); + })); + })); +})); diff --git a/test/parallel/test-tls-client-reject.js b/test/parallel/test-tls-client-reject.js index ddfcafd2085b53..1b33f5525dc478 100644 --- a/test/parallel/test-tls-client-reject.js +++ b/test/parallel/test-tls-client-reject.js @@ -16,15 +16,12 @@ var options = { cert: fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')) }; -var connectCount = 0; - -var server = tls.createServer(options, function(socket) { - ++connectCount; +var server = tls.createServer(options, common.mustCall(function(socket) { socket.on('data', function(data) { console.error(data.toString()); assert.equal(data, 'ok'); }); -}).listen(0, function() { +}, 3)).listen(0, function() { unauthorized(); }); @@ -38,18 +35,14 @@ function unauthorized() { socket.end(); rejectUnauthorized(); }); - socket.on('error', function(err) { - assert(false); - }); + socket.on('error', common.fail); socket.write('ok'); } function rejectUnauthorized() { var socket = tls.connect(server.address().port, { servername: 'localhost' - }, function() { - assert(false); - }); + }, common.fail); socket.on('error', function(err) { console.error(err); authorized(); @@ -66,12 +59,6 @@ function authorized() { socket.end(); server.close(); }); - socket.on('error', function(err) { - assert(false); - }); + socket.on('error', common.fail); socket.write('ok'); } - -process.on('exit', function() { - assert.equal(connectCount, 3); -}); diff --git a/test/parallel/test-tls-client-resume.js b/test/parallel/test-tls-client-resume.js index 141e0348a7955b..75524a3a189b3e 100644 --- a/test/parallel/test-tls-client-resume.js +++ b/test/parallel/test-tls-client-resume.js @@ -19,13 +19,10 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; -var connections = 0; - // create server -var server = tls.Server(options, function(socket) { +var server = tls.Server(options, common.mustCall(function(socket) { socket.end('Goodbye'); - connections++; -}); +}, 2)); // start listening server.listen(0, function() { @@ -60,7 +57,3 @@ server.listen(0, function() { }); }); }); - -process.on('exit', function() { - assert.equal(2, connections); -}); diff --git a/test/parallel/test-tls-close-error.js b/test/parallel/test-tls-close-error.js index 407d2caa9ed7d0..d1964858c5ae45 100644 --- a/test/parallel/test-tls-close-error.js +++ b/test/parallel/test-tls-close-error.js @@ -11,31 +11,19 @@ var tls = require('tls'); var fs = require('fs'); -var errorCount = 0; -var closeCount = 0; - var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }, function(c) { -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var c = tls.connect(this.address().port, function() { assert(false, 'should not be called'); }); - c.on('error', function(err) { - errorCount++; - }); - - c.on('close', function(err) { - if (err) - closeCount++; + c.on('error', common.mustCall(function(err) {})); + c.on('close', common.mustCall(function(err) { + assert.ok(err); server.close(); - }); -}); - -process.on('exit', function() { - assert.equal(errorCount, 1); - assert.equal(closeCount, 1); -}); + })); +})); diff --git a/test/parallel/test-tls-close-notify.js b/test/parallel/test-tls-close-notify.js index 2d747afd4057a6..51b16746e30533 100644 --- a/test/parallel/test-tls-close-notify.js +++ b/test/parallel/test-tls-close-notify.js @@ -1,5 +1,4 @@ 'use strict'; -var assert = require('assert'); var common = require('../common'); if (!common.hasCrypto) { @@ -10,8 +9,6 @@ var tls = require('tls'); var fs = require('fs'); -var ended = 0; - var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') @@ -19,19 +16,14 @@ var server = tls.createServer({ // Send close-notify without shutting down TCP socket if (c._handle.shutdownSSL() !== 1) c._handle.shutdownSSL(); -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var c = tls.connect(this.address().port, { rejectUnauthorized: false - }, function() { + }, common.mustCall(function() { // Ensure that we receive 'end' event anyway - c.on('end', function() { - ended++; + c.on('end', common.mustCall(function() { c.destroy(); server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(ended, 1); -}); + })); + })); +})); diff --git a/test/parallel/test-tls-connect-pipe.js b/test/parallel/test-tls-connect-pipe.js index acf64f9af7cef3..6ec218e00366f6 100644 --- a/test/parallel/test-tls-connect-pipe.js +++ b/test/parallel/test-tls-connect-pipe.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -10,9 +9,6 @@ var tls = require('tls'); var fs = require('fs'); -var clientConnected = 0; -var serverConnected = 0; - var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') @@ -20,19 +16,12 @@ var options = { common.refreshTmpDir(); -var server = tls.Server(options, function(socket) { - ++serverConnected; +var server = tls.Server(options, common.mustCall(function(socket) { server.close(); -}); -server.listen(common.PIPE, function() { +})); +server.listen(common.PIPE, common.mustCall(function() { var options = { rejectUnauthorized: false }; - var client = tls.connect(common.PIPE, options, function() { - ++clientConnected; + var client = tls.connect(common.PIPE, options, common.mustCall(function() { client.end(); - }); -}); - -process.on('exit', function() { - assert.equal(clientConnected, 1); - assert.equal(serverConnected, 1); -}); + })); +})); diff --git a/test/parallel/test-tls-connect.js b/test/parallel/test-tls-connect.js index 96de1b0ad6fe42..cd4edd89f7b483 100644 --- a/test/parallel/test-tls-connect.js +++ b/test/parallel/test-tls-connect.js @@ -17,20 +17,10 @@ var path = require('path'); const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - let errorEmitted = false; - - process.on('exit', function() { - assert.ok(errorEmitted); - }); - const options = {cert: cert, key: key, port: common.PORT}; - const conn = tls.connect(options, function() { - assert.ok(false); // callback should never be executed - }); + const conn = tls.connect(options, common.fail); - conn.on('error', function() { - errorEmitted = true; - }); + conn.on('error', common.mustCall(function() {})); } // SSL_accept/SSL_connect error handling @@ -38,12 +28,6 @@ var path = require('path'); const cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); const key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); - let errorEmitted = false; - - process.on('exit', function() { - assert.ok(errorEmitted); - }); - const conn = tls.connect({ cert: cert, key: key, @@ -53,7 +37,5 @@ var path = require('path'); assert.ok(false); // callback should never be executed }); - conn.on('error', function() { - errorEmitted = true; - }); + conn.on('error', common.mustCall(function() {})); } diff --git a/test/parallel/test-tls-delayed-attach-error.js b/test/parallel/test-tls-delayed-attach-error.js index b3fbd326415bc1..a5fa91383d7d75 100644 --- a/test/parallel/test-tls-delayed-attach-error.js +++ b/test/parallel/test-tls-delayed-attach-error.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -12,34 +11,27 @@ var net = require('net'); var bonkers = Buffer.alloc(1024, 42); -var receivedError = false; var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = net.createServer(function(c) { - setTimeout(function() { +var server = net.createServer(common.mustCall(function(c) { + setTimeout(common.mustCall(function() { var s = new tls.TLSSocket(c, { isServer: true, secureContext: tls.createSecureContext(options) }); - s.on('_tlsError', function() { - receivedError = true; - }); + s.on('_tlsError', common.mustCall(function() {})); s.on('close', function() { server.close(); s.destroy(); }); - }, 200); -}).listen(0, function() { + }), 200); +})).listen(0, function() { var c = net.connect({port: this.address().port}, function() { c.write(bonkers); }); }); - -process.on('exit', function() { - assert.ok(receivedError); -}); diff --git a/test/parallel/test-tls-ecdh-disable.js b/test/parallel/test-tls-ecdh-disable.js index b6e060f35aed23..a6ddb15cc1478e 100644 --- a/test/parallel/test-tls-ecdh-disable.js +++ b/test/parallel/test-tls-ecdh-disable.js @@ -18,16 +18,7 @@ var options = { ecdhCurve: false }; -var nconns = 0; - -process.on('exit', function() { - assert.equal(nconns, 0); -}); - -var server = tls.createServer(options, function(conn) { - conn.end(); - nconns++; -}); +var server = tls.createServer(options, common.fail); server.listen(0, '127.0.0.1', function() { var cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + diff --git a/test/parallel/test-tls-ecdh.js b/test/parallel/test-tls-ecdh.js index 54a5a382601ee7..e37552247ebd8c 100644 --- a/test/parallel/test-tls-ecdh.js +++ b/test/parallel/test-tls-ecdh.js @@ -19,20 +19,12 @@ var options = { }; var reply = 'I AM THE WALRUS'; // something recognizable -var nconns = 0; -var response = ''; -process.on('exit', function() { - assert.equal(nconns, 1); - assert.notEqual(response.indexOf(reply), -1); -}); - -var server = tls.createServer(options, function(conn) { +var server = tls.createServer(options, common.mustCall(function(conn) { conn.end(reply); - nconns++; -}); +})); -server.listen(0, '127.0.0.1', function() { +server.listen(0, '127.0.0.1', common.mustCall(function() { var cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + ` -connect 127.0.0.1:${this.address().port}`; @@ -40,9 +32,9 @@ server.listen(0, '127.0.0.1', function() { if (common.isWindows) cmd += ' -no_rand_screen'; - exec(cmd, function(err, stdout, stderr) { + exec(cmd, common.mustCall(function(err, stdout, stderr) { if (err) throw err; - response = stdout; + assert.notEqual(stdout.indexOf(reply), -1); server.close(); - }); -}); + })); +})); diff --git a/test/parallel/test-tls-getcipher.js b/test/parallel/test-tls-getcipher.js index 100c4143c09c6d..4ecacb1e9f2fbb 100644 --- a/test/parallel/test-tls-getcipher.js +++ b/test/parallel/test-tls-getcipher.js @@ -18,15 +18,8 @@ var options = { honorCipherOrder: true }; -var nconns = 0; - -process.on('exit', function() { - assert.equal(nconns, 1); -}); - -var server = tls.createServer(options, function(cleartextStream) { - nconns++; -}); +var server = tls.createServer(options, + common.mustCall(function(cleartextStream) {})); server.listen(0, '127.0.0.1', function() { var client = tls.connect({ diff --git a/test/parallel/test-tls-handshake-error.js b/test/parallel/test-tls-handshake-error.js index 1b191d13a3d35b..efe458ebfbf1a8 100644 --- a/test/parallel/test-tls-handshake-error.js +++ b/test/parallel/test-tls-handshake-error.js @@ -11,15 +11,12 @@ var tls = require('tls'); var fs = require('fs'); -var errorCount = 0; -var closeCount = 0; - var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), rejectUnauthorized: true }, function(c) { -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var c = tls.connect({ port: this.address().port, ciphers: 'RC4' @@ -27,19 +24,12 @@ var server = tls.createServer({ assert(false, 'should not be called'); }); - c.on('error', function(err) { - errorCount++; + c.on('error', common.mustCall(function(err) { assert.notEqual(err.code, 'ECONNRESET'); - }); + })); - c.on('close', function(err) { - if (err) - closeCount++; + c.on('close', common.mustCall(function(err) { + assert.ok(err); server.close(); - }); -}); - -process.on('exit', function() { - assert.equal(errorCount, 1); - assert.equal(closeCount, 1); -}); + })); +})); diff --git a/test/parallel/test-tls-invoke-queued.js b/test/parallel/test-tls-invoke-queued.js index 0e7d9a9a2c3ffe..4008e5f099e4bc 100644 --- a/test/parallel/test-tls-invoke-queued.js +++ b/test/parallel/test-tls-invoke-queued.js @@ -12,7 +12,6 @@ var fs = require('fs'); var received = ''; -var ended = 0; var server = tls.createServer({ key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), @@ -26,20 +25,15 @@ var server = tls.createServer({ }); server.close(); -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var c = tls.connect(this.address().port, { rejectUnauthorized: false - }, function() { + }, common.mustCall(function() { c.on('data', function(chunk) { received += chunk; }); - c.on('end', function() { - ended++; - }); - }); -}); - -process.on('exit', function() { - assert.equal(ended, 1); - assert.equal(received, 'hello world! gosh'); -}); + c.on('end', common.mustCall(function() { + assert.strictEqual(received, 'hello world! gosh'); + })); + })); +})); diff --git a/test/parallel/test-tls-legacy-onselect.js b/test/parallel/test-tls-legacy-onselect.js index 6c4b03297c0631..72c748248e448d 100644 --- a/test/parallel/test-tls-legacy-onselect.js +++ b/test/parallel/test-tls-legacy-onselect.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -9,18 +8,15 @@ if (!common.hasCrypto) { var tls = require('tls'); var net = require('net'); -var success = false; - -var server = net.Server(function(raw) { +var server = net.Server(common.mustCall(function(raw) { var pair = tls.createSecurePair(null, true, false, false); pair.on('error', function() {}); - pair.ssl.setSNICallback(function() { + pair.ssl.setSNICallback(common.mustCall(function() { raw.destroy(); server.close(); - success = true; - }); + })); require('_tls_legacy').pipe(pair, raw); -}).listen(0, function() { +})).listen(0, function() { tls.connect({ port: this.address().port, rejectUnauthorized: false, @@ -30,6 +26,3 @@ var server = net.Server(function(raw) { // Just ignore }); }); -process.on('exit', function() { - assert(success); -}); diff --git a/test/parallel/test-tls-max-send-fragment.js b/test/parallel/test-tls-max-send-fragment.js index 6cb8e5f6cf9e8a..64dd14698916c8 100644 --- a/test/parallel/test-tls-max-send-fragment.js +++ b/test/parallel/test-tls-max-send-fragment.js @@ -12,7 +12,6 @@ var fs = require('fs'); var buf = Buffer.allocUnsafe(10000); var received = 0; -var ended = 0; var maxChunk = 768; var server = tls.createServer({ @@ -27,25 +26,20 @@ var server = tls.createServer({ assert(c.setMaxSendFragment(maxChunk)); c.end(buf); -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var c = tls.connect(this.address().port, { rejectUnauthorized: false - }, function() { + }, common.mustCall(function() { c.on('data', function(chunk) { assert(chunk.length <= maxChunk); received += chunk.length; }); // Ensure that we receive 'end' event anyway - c.on('end', function() { - ended++; + c.on('end', common.mustCall(function() { c.destroy(); server.close(); - }); - }); -}); - -process.on('exit', function() { - assert.equal(ended, 1); - assert.equal(received, buf.length); -}); + assert.strictEqual(received, buf.length); + })); + })); +})); diff --git a/test/parallel/test-tls-no-rsa-key.js b/test/parallel/test-tls-no-rsa-key.js index cd1e15c1cd932b..cc04534bf91973 100644 --- a/test/parallel/test-tls-no-rsa-key.js +++ b/test/parallel/test-tls-no-rsa-key.js @@ -15,14 +15,12 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/ec-cert.pem') }; -var cert = null; - var server = tls.createServer(options, function(conn) { conn.end('ok'); -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var c = tls.connect(this.address().port, { rejectUnauthorized: false - }, function() { + }, common.mustCall(function() { c.on('end', common.mustCall(function() { c.end(); server.close(); @@ -32,11 +30,7 @@ var server = tls.createServer(options, function(conn) { assert.equal(data, 'ok'); }); - cert = c.getPeerCertificate(); - }); -}); - -process.on('exit', function() { - assert(cert); - assert.equal(cert.subject.C, 'US'); -}); + const cert = c.getPeerCertificate(); + assert.strictEqual(cert.subject.C, 'US'); + })); +})); diff --git a/test/parallel/test-tls-passphrase.js b/test/parallel/test-tls-passphrase.js index e877363642be32..8999f470187f78 100644 --- a/test/parallel/test-tls-passphrase.js +++ b/test/parallel/test-tls-passphrase.js @@ -25,21 +25,18 @@ var server = tls.Server({ s.end(); }); -var connectCount = 0; -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var c = tls.connect({ port: this.address().port, key: key, passphrase: 'passphrase', cert: cert, rejectUnauthorized: false - }, function() { - ++connectCount; - }); + }, common.mustCall(function() {})); c.on('end', function() { server.close(); }); -}); +})); assert.throws(function() { tls.connect({ @@ -50,7 +47,3 @@ assert.throws(function() { rejectUnauthorized: false }); }); - -process.on('exit', function() { - assert.equal(connectCount, 1); -}); diff --git a/test/parallel/test-tls-peer-certificate-encoding.js b/test/parallel/test-tls-peer-certificate-encoding.js index b7e8c5ba45626c..b59d10faa78bc1 100644 --- a/test/parallel/test-tls-peer-certificate-encoding.js +++ b/test/parallel/test-tls-peer-certificate-encoding.js @@ -17,26 +17,20 @@ var options = { cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent5-cert.pem')), ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca2-cert.pem')) ] }; -var verified = false; var server = tls.createServer(options, function(cleartext) { cleartext.end('World'); }); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var socket = tls.connect({ port: this.address().port, rejectUnauthorized: false - }, function() { + }, common.mustCall(function() { var peerCert = socket.getPeerCertificate(); console.error(util.inspect(peerCert)); assert.equal(peerCert.subject.CN, 'Ádám Lippai'); - verified = true; server.close(); - }); + })); socket.end('Hello'); -}); - -process.on('exit', function() { - assert.ok(verified); -}); +})); diff --git a/test/parallel/test-tls-peer-certificate-multi-keys.js b/test/parallel/test-tls-peer-certificate-multi-keys.js index a466810c8be85a..55bc9f40d3a240 100644 --- a/test/parallel/test-tls-peer-certificate-multi-keys.js +++ b/test/parallel/test-tls-peer-certificate-multi-keys.js @@ -16,28 +16,22 @@ var options = { key: fs.readFileSync(join(common.fixturesDir, 'agent.key')), cert: fs.readFileSync(join(common.fixturesDir, 'multi-alice.crt')) }; -var verified = false; var server = tls.createServer(options, function(cleartext) { cleartext.end('World'); }); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var socket = tls.connect({ port: this.address().port, rejectUnauthorized: false - }, function() { + }, common.mustCall(function() { var peerCert = socket.getPeerCertificate(); console.error(util.inspect(peerCert)); assert.deepStrictEqual( peerCert.subject.OU, ['Information Technology', 'Engineering', 'Marketing'] ); - verified = true; server.close(); - }); + })); socket.end('Hello'); -}); - -process.on('exit', function() { - assert.ok(verified); -}); +})); diff --git a/test/parallel/test-tls-peer-certificate.js b/test/parallel/test-tls-peer-certificate.js index 3e983941b2bd0d..59d1a4fdbccc9e 100644 --- a/test/parallel/test-tls-peer-certificate.js +++ b/test/parallel/test-tls-peer-certificate.js @@ -17,16 +17,15 @@ var options = { cert: fs.readFileSync(join(common.fixturesDir, 'keys', 'agent1-cert.pem')), ca: [ fs.readFileSync(join(common.fixturesDir, 'keys', 'ca1-cert.pem')) ] }; -var verified = false; var server = tls.createServer(options, function(cleartext) { cleartext.end('World'); }); -server.listen(0, function() { +server.listen(0, common.mustCall(function() { var socket = tls.connect({ port: this.address().port, rejectUnauthorized: false - }, function() { + }, common.mustCall(function() { var peerCert = socket.getPeerCertificate(); assert.ok(!peerCert.issuerCertificate); @@ -46,12 +45,7 @@ server.listen(0, function() { var issuer = peerCert.issuerCertificate; assert.ok(issuer.issuerCertificate === issuer); assert.equal(issuer.serialNumber, '8DF21C01468AF393'); - verified = true; server.close(); - }); + })); socket.end('Hello'); -}); - -process.on('exit', function() { - assert.ok(verified); -}); +})); diff --git a/test/parallel/test-tls-request-timeout.js b/test/parallel/test-tls-request-timeout.js index 22ba6904b496a5..fc793def177f3a 100644 --- a/test/parallel/test-tls-request-timeout.js +++ b/test/parallel/test-tls-request-timeout.js @@ -10,23 +10,20 @@ var tls = require('tls'); var fs = require('fs'); -var hadTimeout = false; - var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var server = tls.Server(options, function(socket) { +var server = tls.Server(options, common.mustCall(function(socket) { var s = socket.setTimeout(100); assert.ok(s instanceof tls.TLSSocket); - socket.on('timeout', function(err) { - hadTimeout = true; + socket.on('timeout', common.mustCall(function(err) { socket.end(); server.close(); - }); -}); + })); +})); server.listen(0, function() { tls.connect({ @@ -34,7 +31,3 @@ server.listen(0, function() { rejectUnauthorized: false }); }); - -process.on('exit', function() { - assert.ok(hadTimeout); -}); diff --git a/test/parallel/test-tls-securepair-server.js b/test/parallel/test-tls-securepair-server.js index e6d01b7048a382..24ac2177c54536 100644 --- a/test/parallel/test-tls-securepair-server.js +++ b/test/parallel/test-tls-securepair-server.js @@ -13,7 +13,6 @@ var net = require('net'); var fs = require('fs'); var spawn = require('child_process').spawn; -var connections = 0; var key = fs.readFileSync(join(common.fixturesDir, 'agent.key')).toString(); var cert = fs.readFileSync(join(common.fixturesDir, 'agent.crt')).toString(); @@ -21,8 +20,7 @@ function log(a) { console.error('***server*** ' + a); } -var server = net.createServer(function(socket) { - connections++; +var server = net.createServer(common.mustCall(function(socket) { log('connection fd=' + socket.fd); var sslcontext = tls.createSecureContext({key: key, cert: cert}); sslcontext.context.setCiphers('RC4-SHA:AES128-SHA:AES256-SHA'); @@ -84,14 +82,13 @@ var server = net.createServer(function(socket) { log(err.stack); socket.destroy(); }); -}); +})); var gotHello = false; var sentWorld = false; var gotWorld = false; -var opensslExitCode = -1; -server.listen(0, function() { +server.listen(0, common.mustCall(function() { // To test use: openssl s_client -connect localhost:8000 var args = ['s_client', '-connect', `127.0.0.1:${this.address().port}`]; @@ -123,16 +120,14 @@ server.listen(0, function() { client.stdout.pipe(process.stdout, { end: false }); - client.on('exit', function(code) { - opensslExitCode = code; + client.on('exit', common.mustCall(function(code) { + assert.strictEqual(0, code); server.close(); - }); -}); + })); +})); process.on('exit', function() { - assert.equal(1, connections); assert.ok(gotHello); assert.ok(sentWorld); assert.ok(gotWorld); - assert.equal(0, opensslExitCode); }); diff --git a/test/parallel/test-tls-set-ciphers.js b/test/parallel/test-tls-set-ciphers.js index c72a65980af937..4d9274b184232d 100644 --- a/test/parallel/test-tls-set-ciphers.js +++ b/test/parallel/test-tls-set-ciphers.js @@ -23,18 +23,15 @@ var options = { }; var reply = 'I AM THE WALRUS'; // something recognizable -var nconns = 0; var response = ''; process.on('exit', function() { - assert.equal(nconns, 1); assert.notEqual(response.indexOf(reply), -1); }); -var server = tls.createServer(options, function(conn) { +var server = tls.createServer(options, common.mustCall(function(conn) { conn.end(reply); - nconns++; -}); +})); server.listen(0, '127.0.0.1', function() { var cmd = '"' + common.opensslCli + '" s_client -cipher ' + options.ciphers + diff --git a/test/parallel/test-tls-set-encoding.js b/test/parallel/test-tls-set-encoding.js index 103593d6ed7e02..013a5799fa1a3e 100644 --- a/test/parallel/test-tls-set-encoding.js +++ b/test/parallel/test-tls-set-encoding.js @@ -16,14 +16,12 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; -var connections = 0; var message = 'hello world\n'; -var server = tls.Server(options, function(socket) { +var server = tls.Server(options, common.mustCall(function(socket) { socket.end(message); - connections++; -}); +})); server.listen(0, function() { @@ -53,8 +51,3 @@ server.listen(0, function() { server.close(); }); }); - - -process.on('exit', function() { - assert.equal(1, connections); -}); diff --git a/test/parallel/test-tls-timeout-server.js b/test/parallel/test-tls-timeout-server.js index dfd215086f5071..f72f39b392e297 100644 --- a/test/parallel/test-tls-timeout-server.js +++ b/test/parallel/test-tls-timeout-server.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -11,12 +10,6 @@ var tls = require('tls'); var net = require('net'); var fs = require('fs'); -var clientErrors = 0; - -process.on('exit', function() { - assert.equal(clientErrors, 1); -}); - var options = { key: fs.readFileSync(common.fixturesDir + '/keys/agent1-key.pem'), cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem'), @@ -25,11 +18,10 @@ var options = { var server = tls.createServer(options, common.fail); -server.on('tlsClientError', function(err, conn) { +server.on('tlsClientError', common.mustCall(function(err, conn) { conn.destroy(); server.close(); - clientErrors++; -}); +})); server.listen(0, function() { net.connect({ host: '127.0.0.1', port: this.address().port }); diff --git a/test/parallel/test-tls-zero-clear-in.js b/test/parallel/test-tls-zero-clear-in.js index 3437746162c332..97dd27de11ef91 100644 --- a/test/parallel/test-tls-zero-clear-in.js +++ b/test/parallel/test-tls-zero-clear-in.js @@ -1,6 +1,5 @@ 'use strict'; var common = require('../common'); -var assert = require('assert'); if (!common.hasCrypto) { common.skip('missing crypto'); @@ -14,8 +13,6 @@ var path = require('path'); var cert = fs.readFileSync(path.join(common.fixturesDir, 'test_cert.pem')); var key = fs.readFileSync(path.join(common.fixturesDir, 'test_key.pem')); -var errorEmitted = false; - var server = tls.createServer({ cert: cert, key: key @@ -25,7 +22,7 @@ var server = tls.createServer({ c.end(); server.close(); }, 20); -}).listen(0, function() { +}).listen(0, common.mustCall(function() { var conn = tls.connect({ cert: cert, key: key, @@ -41,12 +38,5 @@ var server = tls.createServer({ // treated as error. conn.end(''); - conn.on('error', function(err) { - console.log(err); - errorEmitted = true; - }); -}); - -process.on('exit', function() { - assert.ok(!errorEmitted); -}); + conn.on('error', common.fail); +})); diff --git a/test/parallel/test-zerolengthbufferbug.js b/test/parallel/test-zerolengthbufferbug.js index d9a9d63ee7d12a..9e2cde6b2fadae 100644 --- a/test/parallel/test-zerolengthbufferbug.js +++ b/test/parallel/test-zerolengthbufferbug.js @@ -1,8 +1,7 @@ 'use strict'; // Serving up a zero-length buffer should work. -require('../common'); -var assert = require('assert'); +const common = require('../common'); var http = require('http'); var server = http.createServer(function(req, res) { @@ -13,25 +12,13 @@ var server = http.createServer(function(req, res) { res.end(buffer); }); -var gotResponse = false; -var resBodySize = 0; +server.listen(0, common.mustCall(function() { + http.get({ port: this.address().port }, common.mustCall(function(res) { -server.listen(0, function() { - http.get({ port: this.address().port }, function(res) { - gotResponse = true; - - res.on('data', function(d) { - resBodySize += d.length; - }); + res.on('data', common.fail); res.on('end', function(d) { server.close(); }); - }); -}); - -process.on('exit', function() { - assert.ok(gotResponse); - assert.equal(0, resBodySize); -}); - + })); +})); diff --git a/test/parallel/test-zlib-close-after-write.js b/test/parallel/test-zlib-close-after-write.js index b47deddd8889e9..4e99ad07760ad4 100644 --- a/test/parallel/test-zlib-close-after-write.js +++ b/test/parallel/test-zlib-close-after-write.js @@ -1,18 +1,9 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); var zlib = require('zlib'); -var closed = false; - -zlib.gzip('hello', function(err, out) { +zlib.gzip('hello', common.mustCall(function(err, out) { var unzip = zlib.createGunzip(); unzip.write(out); - unzip.close(function() { - closed = true; - }); -}); - -process.on('exit', function() { - assert(closed); -}); + unzip.close(common.mustCall(function() {})); +})); diff --git a/test/parallel/test-zlib-random-byte-pipes.js b/test/parallel/test-zlib-random-byte-pipes.js index f9804460c13ba7..006bf14b8c2d80 100644 --- a/test/parallel/test-zlib-random-byte-pipes.js +++ b/test/parallel/test-zlib-random-byte-pipes.js @@ -152,13 +152,7 @@ out.on('data', function(c) { console.error('out data', c.length); }); -var didSomething = false; -out.on('data', function(c) { - didSomething = true; +out.on('data', common.mustCall(function(c) { console.error('hash=%s', c); assert.equal(c, inp._hash, 'hashes should match'); -}); - -process.on('exit', function() { - assert(didSomething, 'should have done something'); -}); +})); diff --git a/test/parallel/test-zlib-write-after-close.js b/test/parallel/test-zlib-write-after-close.js index b1d35935e8ab19..b346d2069a5e96 100644 --- a/test/parallel/test-zlib-write-after-close.js +++ b/test/parallel/test-zlib-write-after-close.js @@ -1,20 +1,12 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); -var closed = false; - -zlib.gzip('hello', function(err, out) { +zlib.gzip('hello', common.mustCall(function(err, out) { var unzip = zlib.createGunzip(); - unzip.close(function() { - closed = true; - }); + unzip.close(common.mustCall(function() {})); assert.throws(function() { unzip.write(out); }); -}); - -process.on('exit', function() { - assert(closed); -}); +})); diff --git a/test/parallel/test-zlib-zero-byte.js b/test/parallel/test-zlib-zero-byte.js index 677df17294a38e..97586040541046 100644 --- a/test/parallel/test-zlib-zero-byte.js +++ b/test/parallel/test-zlib-zero-byte.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var zlib = require('zlib'); @@ -9,20 +9,10 @@ var received = 0; gz.on('data', function(c) { received += c.length; }); -var ended = false; -gz.on('end', function() { - ended = true; -}); -var finished = false; -gz.on('finish', function() { - finished = true; -}); + +gz.on('end', common.mustCall(function() { + assert.strictEqual(received, 20); +})); +gz.on('finish', common.mustCall(function() {})); gz.write(emptyBuffer); gz.end(); - -process.on('exit', function() { - assert.equal(received, 20); - assert(ended); - assert(finished); - console.log('ok'); -}); diff --git a/test/pummel/test-http-client-reconnect-bug.js b/test/pummel/test-http-client-reconnect-bug.js index 7b9b8b0da1bcb0..395a538178fe79 100644 --- a/test/pummel/test-http-client-reconnect-bug.js +++ b/test/pummel/test-http-client-reconnect-bug.js @@ -1,47 +1,27 @@ 'use strict'; const common = require('../common'); -const assert = require('assert'); const net = require('net'); const http = require('http'); -var errorCount = 0; -var eofCount = 0; - var server = net.createServer(function(socket) { socket.end(); }); -server.on('listening', function() { +server.on('listening', common.mustCall(function() { var client = http.createClient(common.PORT); - client.on('error', function(err) { - // We should receive one error - console.log('ERROR! ' + err.message); - errorCount++; - }); - - client.on('end', function() { - // When we remove the old Client interface this will most likely have to be - // changed. - console.log('EOF!'); - eofCount++; - }); + client.on('error', common.mustCall(function(err) {})); + client.on('end', common.mustCall(function() {})); var request = client.request('GET', '/', {'host': 'localhost'}); request.end(); request.on('response', function(response) { console.log('STATUS: ' + response.statusCode); }); -}); +})); server.listen(common.PORT); setTimeout(function() { server.close(); }, 500); - - -process.on('exit', function() { - assert.equal(1, errorCount); - assert.equal(1, eofCount); -}); diff --git a/test/pummel/test-https-large-response.js b/test/pummel/test-https-large-response.js index 36d8e368709770..a122e47bc57a57 100644 --- a/test/pummel/test-https-large-response.js +++ b/test/pummel/test-https-large-response.js @@ -15,29 +15,25 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent1-cert.pem') }; -var reqCount = 0; - process.stdout.write('build body...'); var body = 'hello world\n'.repeat(1024 * 1024); process.stdout.write('done\n'); -var server = https.createServer(options, function(req, res) { - reqCount++; +var server = https.createServer(options, common.mustCall(function(req, res) { console.log('got request'); res.writeHead(200, { 'content-type': 'text/plain' }); res.end(body); -}); - -var count = 0; -var gotResEnd = false; +})); -server.listen(common.PORT, function() { +server.listen(common.PORT, common.mustCall(function() { https.get({ port: common.PORT, rejectUnauthorized: false - }, function(res) { + }, common.mustCall(function(res) { console.log('response!'); + var count = 0; + res.on('data', function(d) { process.stdout.write('.'); count += d.length; @@ -47,19 +43,12 @@ server.listen(common.PORT, function() { }); }); - res.on('end', function(d) { + res.on('end', common.mustCall(function(d) { process.stdout.write('\n'); console.log('expected: ', body.length); console.log(' got: ', count); server.close(); - gotResEnd = true; - }); - }); -}); - - -process.on('exit', function() { - assert.equal(1, reqCount); - assert.equal(body.length, count); - assert.ok(gotResEnd); -}); + assert.strictEqual(count, body.length); + })); + })); +})); diff --git a/test/pummel/test-net-pingpong-delay.js b/test/pummel/test-net-pingpong-delay.js index 1a25ed3fe2b7ed..c9cac778d59f4e 100644 --- a/test/pummel/test-net-pingpong-delay.js +++ b/test/pummel/test-net-pingpong-delay.js @@ -3,9 +3,6 @@ var common = require('../common'); var assert = require('assert'); var net = require('net'); - -var tests_run = 0; - function pingPongTest(port, host, on_complete) { var N = 100; var DELAY = 1; @@ -45,7 +42,7 @@ function pingPongTest(port, host, on_complete) { }); }); - server.listen(port, host, function() { + server.listen(port, host, common.mustCall(function() { var client = net.createConnection(port, host); client.setEncoding('utf8'); @@ -77,18 +74,13 @@ function pingPongTest(port, host, on_complete) { assert.equal(false, true); }); - client.on('close', function() { + client.on('close', common.mustCall(function() { console.log('client.end'); assert.equal(N + 1, count); assert.ok(client_ended); if (on_complete) on_complete(); - tests_run += 1; - }); - }); + })); + })); } pingPongTest(common.PORT); - -process.on('exit', function() { - assert.equal(1, tests_run); -}); diff --git a/test/pummel/test-net-timeout2.js b/test/pummel/test-net-timeout2.js index c7b445f96c4e38..7352fb18a15d52 100644 --- a/test/pummel/test-net-timeout2.js +++ b/test/pummel/test-net-timeout2.js @@ -3,20 +3,13 @@ // https://github.com/joyent/node/issues/2002 var common = require('../common'); -var assert = require('assert'); var net = require('net'); var seconds = 5; -var gotTimeout = false; var counter = 0; var server = net.createServer(function(socket) { - socket.setTimeout((seconds / 2) * 1000, function() { - gotTimeout = true; - console.log('timeout!!'); - socket.destroy(); - process.exit(1); - }); + socket.setTimeout((seconds / 2) * 1000, common.fail); var interval = setInterval(function() { counter++; @@ -38,8 +31,3 @@ server.listen(common.PORT, function() { var s = net.connect(common.PORT); s.pipe(process.stdout); }); - - -process.on('exit', function() { - assert.equal(false, gotTimeout); -}); diff --git a/test/pummel/test-timer-wrap.js b/test/pummel/test-timer-wrap.js index d2e96e066d2fb1..b71a72f42568e7 100644 --- a/test/pummel/test-timer-wrap.js +++ b/test/pummel/test-timer-wrap.js @@ -1,8 +1,6 @@ 'use strict'; -require('../common'); -var assert = require('assert'); +const common = require('../common'); -var timeouts = 0; var Timer = process.binding('timer_wrap').Timer; var kOnTimeout = Timer.kOnTimeout; @@ -10,12 +8,7 @@ var t = new Timer(); t.start(1000, 0); -t[kOnTimeout] = function() { - timeouts++; +t[kOnTimeout] = common.mustCall(function() { console.log('timeout'); t.close(); -}; - -process.on('exit', function() { - assert.equal(1, timeouts); }); diff --git a/test/pummel/test-timers.js b/test/pummel/test-timers.js index 3525c827a9e6b7..f7d85bf0cf27b2 100644 --- a/test/pummel/test-timers.js +++ b/test/pummel/test-timers.js @@ -1,11 +1,10 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); var WINDOW = 200; // why is does this need to be so big? var interval_count = 0; -var setTimeout_called = false; // check that these don't blow up. clearTimeout(null); @@ -13,7 +12,7 @@ clearInterval(null); assert.equal(true, setTimeout instanceof Function); var starttime = new Date(); -setTimeout(function() { +setTimeout(common.mustCall(function() { var endtime = new Date(); var diff = endtime - starttime; @@ -21,8 +20,7 @@ setTimeout(function() { console.error('diff: ' + diff); assert.equal(true, 1000 - WINDOW < diff && diff < 1000 + WINDOW); - setTimeout_called = true; -}, 1000); +}), 1000); // this timer shouldn't execute var id = setTimeout(function() { assert.equal(true, false); }, 500); @@ -101,7 +99,6 @@ clearTimeout(y); process.on('exit', function() { - assert.equal(true, setTimeout_called); assert.equal(3, interval_count); assert.equal(11, count4); assert.equal(0, expectedTimeouts, 'clearTimeout cleared too many timeouts'); diff --git a/test/pummel/test-tls-server-large-request.js b/test/pummel/test-tls-server-large-request.js index db31c28a9d508e..c4d7a6095ae8cb 100644 --- a/test/pummel/test-tls-server-large-request.js +++ b/test/pummel/test-tls-server-large-request.js @@ -12,8 +12,6 @@ var fs = require('fs'); var stream = require('stream'); var util = require('util'); -var clientConnected = 0; -var serverConnected = 0; var request = Buffer.from(new Array(1024 * 256).join('ABCD')); // 1mb var options = { @@ -39,22 +37,15 @@ Mediator.prototype._write = function write(data, enc, cb) { var mediator = new Mediator(); -var server = tls.Server(options, function(socket) { +var server = tls.Server(options, common.mustCall(function(socket) { socket.pipe(mediator); - serverConnected++; -}); +})); -server.listen(common.PORT, function() { +server.listen(common.PORT, common.mustCall(function() { var client1 = tls.connect({ port: common.PORT, rejectUnauthorized: false - }, function() { - ++clientConnected; + }, common.mustCall(function() { client1.end(request); - }); -}); - -process.on('exit', function() { - assert.equal(clientConnected, 1); - assert.equal(serverConnected, 1); -}); + })); +})); diff --git a/test/pummel/test-tls-throttle.js b/test/pummel/test-tls-throttle.js index d80544eae610e7..a93793989f0b2b 100644 --- a/test/pummel/test-tls-throttle.js +++ b/test/pummel/test-tls-throttle.js @@ -21,13 +21,9 @@ var options = { cert: fs.readFileSync(common.fixturesDir + '/keys/agent2-cert.pem') }; -var connections = 0; - - -var server = tls.Server(options, function(socket) { +var server = tls.Server(options, common.mustCall(function(socket) { socket.end(body); - connections++; -}); +})); var recvCount = 0; @@ -67,6 +63,5 @@ var timeout = setTimeout(displayCounts, 10 * 1000); process.on('exit', function() { displayCounts(); - assert.equal(1, connections); assert.equal(body.length, recvCount); }); diff --git a/test/sequential/test-net-GH-5504.js b/test/sequential/test-net-GH-5504.js index e760c26c2944e0..c6e4e8e3d6a2b7 100644 --- a/test/sequential/test-net-GH-5504.js +++ b/test/sequential/test-net-GH-5504.js @@ -47,17 +47,6 @@ function client() { function parent() { var spawn = require('child_process').spawn; var node = process.execPath; - var assert = require('assert'); - var serverExited = false; - var clientExited = false; - var serverListened = false; - - process.on('exit', function() { - assert(serverExited); - assert(clientExited); - assert(serverListened); - console.log('ok'); - }); setTimeout(function() { if (s) s.kill(); @@ -76,21 +65,14 @@ function parent() { wrap(s.stderr, process.stderr, 'SERVER 2>'); wrap(s.stdout, process.stdout, 'SERVER 1>'); - s.on('exit', function(c) { - console.error('server exited', c); - serverExited = true; - }); + s.on('exit', common.mustCall(function(c) {})); - s.stdout.once('data', function() { - serverListened = true; + s.stdout.once('data', common.mustCall(function() { c = spawn(node, [__filename, 'client']); wrap(c.stderr, process.stderr, 'CLIENT 2>'); wrap(c.stdout, process.stdout, 'CLIENT 1>'); - c.on('exit', function(c) { - console.error('client exited', c); - clientExited = true; - }); - }); + c.on('exit', common.mustCall(function(c) {})); + })); function wrap(inp, out, w) { inp.setEncoding('utf8'); diff --git a/test/sequential/test-regress-GH-4027.js b/test/sequential/test-regress-GH-4027.js index 80780fd6a2cf95..aa1ec12c30f609 100644 --- a/test/sequential/test-regress-GH-4027.js +++ b/test/sequential/test-regress-GH-4027.js @@ -10,14 +10,8 @@ var filename = path.join(common.tmpDir, 'watched'); fs.writeFileSync(filename, 'quis custodiet ipsos custodes'); setTimeout(fs.unlinkSync, 100, filename); -var seenEvent = 0; -process.on('exit', function() { - assert.equal(seenEvent, 1); -}); - -fs.watchFile(filename, { interval: 50 }, function(curr, prev) { +fs.watchFile(filename, { interval: 50 }, common.mustCall(function(curr, prev) { assert.equal(prev.nlink, 1); assert.equal(curr.nlink, 0); fs.unwatchFile(filename); - seenEvent++; -}); +})); diff --git a/test/sequential/test-util-debug.js b/test/sequential/test-util-debug.js index 5f0306e5e01645..1159278efa475d 100644 --- a/test/sequential/test-util-debug.js +++ b/test/sequential/test-util-debug.js @@ -1,5 +1,5 @@ 'use strict'; -require('../common'); +const common = require('../common'); var assert = require('assert'); if (process.argv[2] === 'child') @@ -23,7 +23,6 @@ function test(environ, shouldWrite) { 'TUD %PID%: number=1234 string=asdf obj={"foo":"bar"}\n'; } var expectOut = 'ok\n'; - var didTest = false; var spawn = require('child_process').spawn; var child = spawn(process.execPath, [__filename, 'child'], { @@ -44,17 +43,12 @@ function test(environ, shouldWrite) { out += c; }); - child.on('close', function(c) { + child.on('close', common.mustCall(function(c) { assert(!c); assert.equal(err, expectErr); assert.equal(out, expectOut); - didTest = true; console.log('ok %j %j', environ, shouldWrite); - }); - - process.on('exit', function() { - assert(didTest); - }); + })); }