Browse Source

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 <wpreul@gmail.com>
Reviewed-By: Minwoo Jung <jmwsoft@gmail.com>
Reviewed-By: Ben Noordhuis <info@bnoordhuis.nl>
v7.x
cjihrig 9 years ago
parent
commit
04b4d15b39
  1. 15
      test/addons/async-hello-world/test.js
  2. 8
      test/internet/test-http-dns-fail.js
  3. 19
      test/internet/test-http-https-default-ports.js
  4. 23
      test/internet/test-net-connect-timeout.js
  5. 19
      test/internet/test-net-connect-unref.js
  6. 21
      test/parallel/test-child-process-buffering.js
  7. 14
      test/parallel/test-child-process-disconnect.js
  8. 21
      test/parallel/test-child-process-exec-buffer.js
  9. 25
      test/parallel/test-child-process-exec-cwd.js
  10. 11
      test/parallel/test-child-process-exec-error.js
  11. 19
      test/parallel/test-child-process-exit-code.js
  12. 16
      test/parallel/test-child-process-fork-and-spawn.js
  13. 18
      test/parallel/test-child-process-fork-close.js
  14. 13
      test/parallel/test-child-process-fork.js
  15. 21
      test/parallel/test-child-process-internal.js
  16. 37
      test/parallel/test-child-process-kill.js
  17. 12
      test/parallel/test-child-process-set-blocking.js
  18. 11
      test/parallel/test-child-process-spawn-error.js
  19. 13
      test/parallel/test-child-process-stdin-ipc.js
  20. 29
      test/parallel/test-child-process-stdin.js
  21. 9
      test/parallel/test-cluster-http-pipe.js
  22. 11
      test/parallel/test-cluster-listening-port.js
  23. 9
      test/parallel/test-cluster-net-listen.js
  24. 29
      test/parallel/test-cluster-setup-master-emit.js
  25. 14
      test/parallel/test-cluster-uncaught-exception.js
  26. 18
      test/parallel/test-cluster-worker-death.js
  27. 33
      test/parallel/test-cluster-worker-destroy.js
  28. 20
      test/parallel/test-cluster-worker-forced-exit.js
  29. 10
      test/parallel/test-crypto-domains.js
  30. 11
      test/parallel/test-crypto-hash-stream-pipe.js
  31. 16
      test/parallel/test-delayed-require.js
  32. 11
      test/parallel/test-dgram-close-is-not-callback.js
  33. 19
      test/parallel/test-dgram-close.js
  34. 11
      test/parallel/test-dgram-implicit-bind.js
  35. 14
      test/parallel/test-dgram-unref.js
  36. 16
      test/parallel/test-domain-implicit-fs.js
  37. 24
      test/parallel/test-domain-timers.js
  38. 37
      test/parallel/test-error-reporting.js
  39. 22
      test/parallel/test-eval.js
  40. 13
      test/parallel/test-event-emitter-max-listeners.js
  41. 14
      test/parallel/test-event-emitter-no-error-provided-to-error-event.js
  42. 25
      test/parallel/test-event-emitter-once.js
  43. 8
      test/parallel/test-event-emitter-subclass.js
  44. 18
      test/parallel/test-exception-handler.js
  45. 18
      test/parallel/test-file-read-noexist.js
  46. 21
      test/parallel/test-fs-exists.js
  47. 14
      test/parallel/test-fs-long-path.js
  48. 20
      test/parallel/test-fs-open.js
  49. 20
      test/parallel/test-fs-read-buffer.js
  50. 21
      test/parallel/test-fs-read.js
  51. 16
      test/parallel/test-fs-readfile-error.js
  52. 13
      test/parallel/test-fs-readfile-zero-byte-liar.js
  53. 11
      test/parallel/test-fs-realpath.js
  54. 107
      test/parallel/test-fs-stat.js
  55. 19
      test/parallel/test-fs-stream-double-close.js
  56. 12
      test/parallel/test-fs-symlink-dir-junction-relative.js
  57. 27
      test/parallel/test-fs-symlink-dir-junction.js
  58. 8
      test/parallel/test-fs-truncate-fd.js
  59. 16
      test/parallel/test-fs-truncate.js
  60. 35
      test/parallel/test-fs-write-buffer.js
  61. 62
      test/parallel/test-fs-write-file.js
  62. 17
      test/parallel/test-fs-write-string-coerce.js
  63. 31
      test/parallel/test-fs-write.js
  64. 6
      test/parallel/test-http-abort-before-end.js
  65. 23
      test/parallel/test-http-abort-client.js
  66. 22
      test/parallel/test-http-agent-no-protocol.js
  67. 22
      test/parallel/test-http-agent-null.js
  68. 27
      test/parallel/test-http-bind-twice.js
  69. 14
      test/parallel/test-http-blank-header.js
  70. 18
      test/parallel/test-http-buffer-sanity.js
  71. 17
      test/parallel/test-http-byteswritten.js
  72. 23
      test/parallel/test-http-client-abort-event.js
  73. 13
      test/parallel/test-http-client-get-url.js
  74. 12
      test/parallel/test-http-client-readable.js
  75. 12
      test/parallel/test-http-client-response-domain.js
  76. 36
      test/parallel/test-http-client-upload-buf.js
  77. 37
      test/parallel/test-http-client-upload.js
  78. 16
      test/parallel/test-http-conn-reset.js
  79. 8
      test/parallel/test-http-connect-req-res.js
  80. 10
      test/parallel/test-http-connect.js
  81. 10
      test/parallel/test-http-end-throw-socket-handling.js
  82. 24
      test/parallel/test-http-extra-response.js
  83. 25
      test/parallel/test-http-full-response.js
  84. 22
      test/parallel/test-http-head-request.js
  85. 23
      test/parallel/test-http-head-response-has-no-body-end.js
  86. 23
      test/parallel/test-http-head-response-has-no-body.js
  87. 35
      test/parallel/test-http-hex-write.js
  88. 24
      test/parallel/test-http-legacy.js
  89. 15
      test/parallel/test-http-localaddress-bind-error.js
  90. 20
      test/parallel/test-http-multi-line-headers.js
  91. 23
      test/parallel/test-http-no-content-length.js
  92. 29
      test/parallel/test-http-pause-resume-one-end.js
  93. 11
      test/parallel/test-http-pipe-fs.js
  94. 10
      test/parallel/test-http-pipeline-flood.js
  95. 8
      test/parallel/test-http-request-end.js
  96. 28
      test/parallel/test-http-request-methods.js
  97. 19
      test/parallel/test-http-res-write-after-end.js
  98. 25
      test/parallel/test-http-response-close.js
  99. 21
      test/parallel/test-http-response-no-headers.js
  100. 26
      test/parallel/test-http-unix-socket.js

15
test/addons/async-hello-world/test.js

@ -1,17 +1,10 @@
'use strict'; 'use strict';
require('../../common'); const common = require('../../common');
var assert = require('assert'); var assert = require('assert');
var binding = require('./build/Release/binding'); var binding = require('./build/Release/binding');
var called = false;
process.on('exit', function() { binding(5, common.mustCall(function(err, val) {
assert(called);
});
binding(5, function(err, val) {
assert.equal(null, err); assert.equal(null, err);
assert.equal(10, val); assert.equal(10, val);
process.nextTick(function() { process.nextTick(common.mustCall(function() {}));
called = true; }));
});
});

8
test/internet/test-http-dns-fail.js

@ -4,11 +4,10 @@
* should trigger the error event after each attempt. * should trigger the error event after each attempt.
*/ */
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var resDespiteError = false;
var hadError = 0; var hadError = 0;
function httpreq(count) { function httpreq(count) {
@ -19,9 +18,7 @@ function httpreq(count) {
port: 80, port: 80,
path: '/', path: '/',
method: 'GET' method: 'GET'
}, function(res) { }, common.fail);
resDespiteError = true;
});
req.on('error', function(e) { req.on('error', function(e) {
console.log(e.message); console.log(e.message);
@ -37,6 +34,5 @@ httpreq(0);
process.on('exit', function() { process.on('exit', function() {
assert.equal(false, resDespiteError);
assert.equal(2, hadError); assert.equal(2, hadError);
}); });

19
test/internet/test-http-https-default-ports.js

@ -1,6 +1,5 @@
'use strict'; 'use strict';
var common = require('../common'); var common = require('../common');
var assert = require('assert');
if (!common.hasCrypto) { if (!common.hasCrypto) {
common.skip('missing crypto'); common.skip('missing crypto');
@ -9,21 +8,11 @@ if (!common.hasCrypto) {
var https = require('https'); var https = require('https');
var http = require('http'); var http = require('http');
var gotHttpsResp = false;
var gotHttpResp = false;
process.on('exit', function() { https.get('https://www.google.com/', common.mustCall(function(res) {
assert(gotHttpsResp);
assert(gotHttpResp);
console.log('ok');
});
https.get('https://www.google.com/', function(res) {
gotHttpsResp = true;
res.resume(); res.resume();
}); }));
http.get('http://www.google.com/', function(res) { http.get('http://www.google.com/', common.mustCall(function(res) {
gotHttpResp = true;
res.resume(); res.resume();
}); }));

23
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/UE0ZbfLt6t8
// https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw // https://groups.google.com/forum/#!topic/nodejs-dev/jR7-5UDqXkw
require('../common'); const common = require('../common');
var net = require('net'); var net = require('net');
var assert = require('assert'); var assert = require('assert');
var start = new Date(); var start = new Date();
var gotTimeout = false;
var gotConnect = false;
var T = 100; var T = 100;
// 192.0.2.1 is part of subnet assigned as "TEST-NET" in RFC 5737. // 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.setTimeout(T);
socket.on('timeout', function() { socket.on('timeout', common.mustCall(function() {
console.error('timeout'); console.error('timeout');
gotTimeout = true;
var now = new Date(); var now = new Date();
assert.ok(now - start < T + 500); assert.ok(now - start < T + 500);
socket.destroy(); socket.destroy();
}); }));
socket.on('connect', function() {
console.error('connect');
gotConnect = true;
socket.destroy();
});
process.on('exit', function() { socket.on('connect', common.fail);
assert.ok(gotTimeout);
assert.ok(!gotConnect);
});

19
test/internet/test-net-connect-unref.js

@ -1,25 +1,14 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var net = require('net'); var net = require('net');
var client, killed = false, ended = false; var client;
var TIMEOUT = 10 * 1000; var TIMEOUT = 10 * 1000;
client = net.createConnection(53, '8.8.8.8', function() { client = net.createConnection(53, '8.8.8.8', function() {
client.unref(); client.unref();
}); });
client.on('close', function() { client.on('close', common.fail);
ended = true;
});
setTimeout(function() {
killed = true;
client.end();
}, TIMEOUT).unref();
process.on('exit', function() { setTimeout(common.fail, TIMEOUT).unref();
assert.strictEqual(killed, false, 'A client should have connected');
assert.strictEqual(ended, false, 'A client should stay connected');
});

21
test/parallel/test-child-process-buffering.js

@ -2,10 +2,6 @@
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var pwd_called = false;
var childClosed = false;
var childExited = false;
function pwd(callback) { function pwd(callback) {
var output = ''; var output = '';
var child = common.spawnPwd(); var child = common.spawnPwd();
@ -16,17 +12,14 @@ function pwd(callback) {
output += s; output += s;
}); });
child.on('exit', function(c) { child.on('exit', common.mustCall(function(c) {
console.log('exit: ' + c); console.log('exit: ' + c);
assert.equal(0, c); assert.equal(0, c);
childExited = true; }));
});
child.on('close', function() { child.on('close', common.mustCall(function() {
callback(output); callback(output);
pwd_called = true; }));
childClosed = true;
});
} }
@ -35,9 +28,3 @@ pwd(function(result) {
assert.equal(true, result.length > 1); assert.equal(true, result.length > 1);
assert.equal('\n', result[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);
});

14
test/parallel/test-child-process-disconnect.js

@ -48,21 +48,16 @@ if (process.argv[2] === 'child') {
var child = fork(process.argv[1], ['child']); var child = fork(process.argv[1], ['child']);
var childFlag = false; var childFlag = false;
var childSelfTerminate = false;
var parentEmit = false;
var parentFlag = false; var parentFlag = false;
// when calling .disconnect the event should emit // when calling .disconnect the event should emit
// and the disconnected flag should be true. // and the disconnected flag should be true.
child.on('disconnect', function() { child.on('disconnect', common.mustCall(function() {
parentEmit = true;
parentFlag = child.connected; parentFlag = child.connected;
}); }));
// the process should also self terminate without using signals // the process should also self terminate without using signals
child.on('exit', function() { child.on('exit', common.mustCall(function() {}));
childSelfTerminate = true;
});
// when child is listening // when child is listening
child.on('message', function(obj) { child.on('message', function(obj) {
@ -91,8 +86,5 @@ if (process.argv[2] === 'child') {
process.on('exit', function() { process.on('exit', function() {
assert.equal(childFlag, false); assert.equal(childFlag, false);
assert.equal(parentFlag, false); assert.equal(parentFlag, false);
assert.ok(childSelfTerminate);
assert.ok(parentEmit);
}); });
} }

21
test/parallel/test-child-process-exec-buffer.js

@ -1,33 +1,22 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var exec = require('child_process').exec; var exec = require('child_process').exec;
var os = require('os'); var os = require('os');
var success_count = 0;
var str = 'hello'; var str = 'hello';
// default encoding // 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 stdout, 'Expected stdout to be a string');
assert.ok('string', typeof stderr, 'Expected stderr to be a string'); assert.ok('string', typeof stderr, 'Expected stderr to be a string');
assert.equal(str + os.EOL, stdout); assert.equal(str + os.EOL, stdout);
}));
success_count++;
});
// no encoding (Buffers expected) // no encoding (Buffers expected)
exec('echo ' + str, { exec('echo ' + str, {
encoding: null 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(stdout instanceof Buffer, 'Expected stdout to be a Buffer');
assert.ok(stderr instanceof Buffer, 'Expected stderr to be a Buffer'); assert.ok(stderr instanceof Buffer, 'Expected stderr to be a Buffer');
assert.equal(str + os.EOL, stdout.toString()); assert.equal(str + os.EOL, stdout.toString());
}));
success_count++;
});
process.on('exit', function() {
assert.equal(2, success_count);
});

25
test/parallel/test-child-process-exec-cwd.js

@ -3,9 +3,6 @@ const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var exec = require('child_process').exec; var exec = require('child_process').exec;
var success_count = 0;
var error_count = 0;
var pwdcommand, dir; var pwdcommand, dir;
if (common.isWindows) { if (common.isWindows) {
@ -16,21 +13,7 @@ if (common.isWindows) {
dir = '/dev'; dir = '/dev';
} }
exec(pwdcommand, {cwd: dir}, function(err, stdout, stderr) { exec(pwdcommand, {cwd: dir}, common.mustCall(function(err, stdout, stderr) {
if (err) { assert.ifError(err);
error_count++; assert.ok(stdout.indexOf(dir) == 0);
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);
});

11
test/parallel/test-child-process-exec-error.js

@ -4,17 +4,10 @@ var assert = require('assert');
var child_process = require('child_process'); var child_process = require('child_process');
function test(fun, code) { function test(fun, code) {
var errors = 0; fun('does-not-exist', common.mustCall(function(err) {
fun('does-not-exist', function(err) {
assert.equal(err.code, code); assert.equal(err.code, code);
assert(/does\-not\-exist/.test(err.cmd)); assert(/does\-not\-exist/.test(err.cmd));
errors++; }));
});
process.on('exit', function() {
assert.equal(errors, 1);
});
} }
if (common.isWindows) { if (common.isWindows) {

19
test/parallel/test-child-process-exit-code.js

@ -4,29 +4,18 @@ var assert = require('assert');
var spawn = require('child_process').spawn; var spawn = require('child_process').spawn;
var path = require('path'); var path = require('path');
var exits = 0;
var exitScript = path.join(common.fixturesDir, 'exit.js'); var exitScript = path.join(common.fixturesDir, 'exit.js');
var exitChild = spawn(process.argv[0], [exitScript, 23]); 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(code, 23);
assert.strictEqual(signal, null); assert.strictEqual(signal, null);
}));
exits++;
});
var errorScript = path.join(common.fixturesDir, var errorScript = path.join(common.fixturesDir,
'child_process_should_emit_error.js'); 'child_process_should_emit_error.js');
var errorChild = spawn(process.argv[0], [errorScript]); 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.ok(code !== 0);
assert.strictEqual(signal, null); assert.strictEqual(signal, null);
}));
exits++;
});
process.on('exit', function() {
assert.equal(2, exits);
});

16
test/parallel/test-child-process-fork-and-spawn.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var spawn = require('child_process').spawn; var spawn = require('child_process').spawn;
var fork = require('child_process').fork; 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. // Fork, then spawn. The spawned process should not hang.
switch (process.argv[2] || '') { switch (process.argv[2] || '') {
case '': case '':
fork(__filename, ['fork']).on('exit', checkExit); fork(__filename, ['fork']).on('exit', common.mustCall(checkExit));
process.on('exit', haveExit);
break; break;
case 'fork': case 'fork':
spawn(process.execPath, [__filename, 'spawn']).on('exit', checkExit); spawn(process.execPath, [__filename, 'spawn'])
process.on('exit', haveExit); .on('exit', common.mustCall(checkExit));
break; break;
case 'spawn': case 'spawn':
break; break;
@ -20,14 +19,7 @@ switch (process.argv[2] || '') {
assert(0); assert(0);
} }
var seenExit = false;
function checkExit(statusCode) { function checkExit(statusCode) {
seenExit = true;
assert.equal(statusCode, 0); assert.equal(statusCode, 0);
process.nextTick(process.exit); process.nextTick(process.exit);
} }
function haveExit() {
assert.equal(seenExit, true);
}

18
test/parallel/test-child-process-fork-close.js

@ -9,28 +9,22 @@ let gotMessage = false;
let gotExit = false; let gotExit = false;
let gotClose = false; let gotClose = false;
cp.on('message', function(message) { cp.on('message', common.mustCall(function(message) {
assert(!gotMessage); assert(!gotMessage);
assert(!gotClose); assert(!gotClose);
assert.strictEqual(message, 'hello'); assert.strictEqual(message, 'hello');
gotMessage = true; gotMessage = true;
}); }));
cp.on('exit', function() { cp.on('exit', common.mustCall(function() {
assert(!gotExit); assert(!gotExit);
assert(!gotClose); assert(!gotClose);
gotExit = true; gotExit = true;
}); }));
cp.on('close', function() { cp.on('close', common.mustCall(function() {
assert(gotMessage); assert(gotMessage);
assert(gotExit); assert(gotExit);
assert(!gotClose); assert(!gotClose);
gotClose = true; gotClose = true;
}); }));
process.on('exit', function() {
assert(gotMessage);
assert(gotExit);
assert(gotClose);
});

13
test/parallel/test-child-process-fork.js

@ -1,6 +1,6 @@
'use strict'; 'use strict';
const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var common = require('../common');
var fork = require('child_process').fork; var fork = require('child_process').fork;
var args = ['foo', 'bar']; var args = ['foo', 'bar'];
@ -19,11 +19,6 @@ assert.throws(function() { n.send(); }, TypeError);
n.send({ hello: 'world' }); n.send({ hello: 'world' });
var childExitCode = -1; n.on('exit', common.mustCall(function(c) {
n.on('exit', function(c) { assert.strictEqual(c, 0);
childExitCode = c; }));
});
process.on('exit', function() {
assert.ok(childExitCode == 0);
});

21
test/parallel/test-child-process-internal.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
//messages //messages
@ -21,18 +21,11 @@ if (process.argv[2] === 'child') {
var fork = require('child_process').fork; var fork = require('child_process').fork;
var child = fork(process.argv[1], ['child']); var child = fork(process.argv[1], ['child']);
var gotNormal; child.once('message', common.mustCall(function(data) {
child.once('message', function(data) { assert.deepStrictEqual(data, normal);
gotNormal = data; }));
});
var gotInternal; child.once('internalMessage', common.mustCall(function(data) {
child.once('internalMessage', function(data) { assert.deepStrictEqual(data, internal);
gotInternal = data; }));
});
process.on('exit', function() {
assert.deepStrictEqual(gotNormal, normal);
assert.deepStrictEqual(gotInternal, internal);
});
} }

37
test/parallel/test-child-process-kill.js

@ -1,41 +1,18 @@
'use strict'; 'use strict';
var common = require('../common'); var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var spawn = require('child_process').spawn; var spawn = require('child_process').spawn;
var exitCode;
var termSignal;
var gotStdoutEOF = false;
var gotStderrEOF = false;
var cat = spawn(common.isWindows ? 'cmd' : 'cat'); 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() { cat.on('exit', common.mustCall(function(code, signal) {
gotStdoutEOF = true; assert.strictEqual(code, null);
}); assert.strictEqual(signal, 'SIGTERM');
}));
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;
});
assert.equal(cat.killed, false); assert.equal(cat.killed, false);
cat.kill(); cat.kill();
assert.equal(cat.killed, true); assert.equal(cat.killed, true);
process.on('exit', function() {
assert.strictEqual(exitCode, null);
assert.strictEqual(termSignal, 'SIGTERM');
assert.ok(gotStdoutEOF);
assert.ok(gotStderrEOF);
});

12
test/parallel/test-child-process-set-blocking.js

@ -1,20 +1,14 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var ch = require('child_process'); var ch = require('child_process');
var SIZE = 100000; var SIZE = 100000;
var childGone = false;
var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], { var cp = ch.spawn('python', ['-c', 'print ' + SIZE + ' * "C"'], {
stdio: 'inherit' stdio: 'inherit'
}); });
cp.on('exit', function(code) { cp.on('exit', common.mustCall(function(code) {
childGone = true;
assert.equal(0, code); assert.equal(0, code);
}); }));
process.on('exit', function() {
assert.ok(childGone);
});

11
test/parallel/test-child-process-spawn-error.js

@ -3,22 +3,15 @@ var common = require('../common');
var spawn = require('child_process').spawn; var spawn = require('child_process').spawn;
var assert = require('assert'); var assert = require('assert');
var errors = 0;
var enoentPath = 'foo123'; var enoentPath = 'foo123';
var spawnargs = ['bar']; var spawnargs = ['bar'];
assert.equal(common.fileExists(enoentPath), false); assert.equal(common.fileExists(enoentPath), false);
var enoentChild = spawn(enoentPath, spawnargs); 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.code, 'ENOENT');
assert.equal(err.errno, 'ENOENT'); assert.equal(err.errno, 'ENOENT');
assert.equal(err.syscall, 'spawn ' + enoentPath); assert.equal(err.syscall, 'spawn ' + enoentPath);
assert.equal(err.path, enoentPath); assert.equal(err.path, enoentPath);
assert.deepStrictEqual(err.spawnargs, spawnargs); assert.deepStrictEqual(err.spawnargs, spawnargs);
errors++; }));
});
process.on('exit', function() {
assert.equal(1, errors);
});

13
test/parallel/test-child-process-stdin-ipc.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var spawn = require('child_process').spawn; var spawn = require('child_process').spawn;
@ -14,11 +14,6 @@ var proc = spawn(process.execPath, [__filename, 'child'], {
stdio: ['ipc', 'inherit', 'inherit'] stdio: ['ipc', 'inherit', 'inherit']
}); });
var childCode = -1; proc.on('exit', common.mustCall(function(code) {
proc.on('exit', function(code) { assert.strictEqual(code, 0);
childCode = code; }));
});
process.on('exit', function() {
assert.equal(childCode, 0);
});

29
test/parallel/test-child-process-stdin.js

@ -15,8 +15,6 @@ assert.ok(!cat.stdin.readable);
cat.stdin.end(); cat.stdin.end();
var response = ''; var response = '';
var exitStatus = -1;
var closed = false;
cat.stdout.setEncoding('utf8'); cat.stdout.setEncoding('utf8');
cat.stdout.on('data', function(chunk) { cat.stdout.on('data', function(chunk) {
@ -26,33 +24,18 @@ cat.stdout.on('data', function(chunk) {
cat.stdout.on('end', common.mustCall(function() {})); cat.stdout.on('end', common.mustCall(function() {}));
cat.stderr.on('data', function(chunk) { cat.stderr.on('data', common.fail);
// shouldn't get any stderr output
assert.ok(false);
});
cat.stderr.on('end', common.mustCall(function() {})); cat.stderr.on('end', common.mustCall(function() {}));
cat.on('exit', function(status) { cat.on('exit', common.mustCall(function(status) {
console.log('exit event'); assert.strictEqual(0, status);
exitStatus = status; }));
});
cat.on('close', function() {
closed = true;
if (common.isWindows) {
assert.equal('hello world\r\n', response);
} else {
assert.equal('hello world', response);
}
});
process.on('exit', function() { cat.on('close', common.mustCall(function() {
assert.equal(0, exitStatus);
assert(closed);
if (common.isWindows) { if (common.isWindows) {
assert.equal('hello world\r\n', response); assert.equal('hello world\r\n', response);
} else { } else {
assert.equal('hello world', response); assert.equal('hello world', response);
} }
}); }));

9
test/parallel/test-cluster-http-pipe.js

@ -13,18 +13,13 @@ if (common.isWindows) {
if (cluster.isMaster) { if (cluster.isMaster) {
common.refreshTmpDir(); common.refreshTmpDir();
var ok = false;
var worker = cluster.fork(); var worker = cluster.fork();
worker.on('message', function(msg) { worker.on('message', common.mustCall(function(msg) {
assert.equal(msg, 'DONE'); assert.equal(msg, 'DONE');
ok = true; }));
});
worker.on('exit', function() { worker.on('exit', function() {
process.exit(); process.exit();
}); });
process.on('exit', function() {
assert(ok);
});
return; return;
} }

11
test/parallel/test-cluster-listening-port.js

@ -5,20 +5,15 @@ var cluster = require('cluster');
var net = require('net'); var net = require('net');
if (cluster.isMaster) { if (cluster.isMaster) {
var port = null;
cluster.fork(); cluster.fork();
cluster.on('listening', function(worker, address) { cluster.on('listening', common.mustCall(function(worker, address) {
port = address.port; const port = address.port;
// ensure that the port is not 0 or null // ensure that the port is not 0 or null
assert(port); assert(port);
// ensure that the port is numerical // ensure that the port is numerical
assert.strictEqual(typeof port, 'number'); assert.strictEqual(typeof port, 'number');
worker.kill(); worker.kill();
}); }));
process.on('exit', function() {
// ensure that the 'listening' handler has been called
assert(port);
});
} else { } else {
net.createServer(common.fail).listen(0); net.createServer(common.fail).listen(0);
} }

9
test/parallel/test-cluster-net-listen.js

@ -6,14 +6,9 @@ var net = require('net');
if (cluster.isMaster) { if (cluster.isMaster) {
// ensure that the worker exits peacefully // ensure that the worker exits peacefully
var worker = cluster.fork(); cluster.fork().on('exit', common.mustCall(function(statusCode) {
worker.on('exit', function(statusCode) {
assert.equal(statusCode, 0); assert.equal(statusCode, 0);
worker = null; }));
});
process.on('exit', function() {
assert.equal(worker, null);
});
} else { } else {
// listen() without port should not trigger a libuv assert // listen() without port should not trigger a libuv assert
net.createServer(common.fail).listen(process.exit); net.createServer(common.fail).listen(process.exit);

29
test/parallel/test-cluster-setup-master-emit.js

@ -1,39 +1,26 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var cluster = require('cluster'); var cluster = require('cluster');
assert(cluster.isMaster); assert(cluster.isMaster);
var assertsRun = 0;
function emitAndCatch(next) { function emitAndCatch(next) {
cluster.once('setup', function(settings) { cluster.once('setup', common.mustCall(function(settings) {
assert.strictEqual(settings.exec, 'new-exec'); assert.strictEqual(settings.exec, 'new-exec');
console.log('ok "setup" emitted with options set');
assertsRun += 1;
setImmediate(next); setImmediate(next);
}); }));
cluster.setupMaster({ exec: 'new-exec' }); cluster.setupMaster({ exec: 'new-exec' });
} }
function emitAndCatch2(next) { function emitAndCatch2(next) {
cluster.once('setup', function(settings) { cluster.once('setup', common.mustCall(function(settings) {
assert('exec' in settings); assert('exec' in settings);
console.log('ok "setup" emitted without options set');
assertsRun += 1;
setImmediate(next); setImmediate(next);
}); }));
cluster.setupMaster(); cluster.setupMaster();
} }
process.on('exit', function() { emitAndCatch(common.mustCall(function() {
assert.strictEqual(assertsRun, 2); emitAndCatch2(common.mustCall(function() {}));
console.log('ok correct number of assertions'); }));
});
emitAndCatch(function() {
emitAndCatch2(function() {
console.log('ok emitted and caught');
});
});

14
test/parallel/test-cluster-uncaught-exception.js

@ -3,7 +3,7 @@
// one that the cluster module installs. // one that the cluster module installs.
// https://github.com/joyent/node/issues/2556 // https://github.com/joyent/node/issues/2556
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var cluster = require('cluster'); var cluster = require('cluster');
var fork = require('child_process').fork; var fork = require('child_process').fork;
@ -13,16 +13,10 @@ var MAGIC_EXIT_CODE = 42;
var isTestRunner = process.argv[2] != 'child'; var isTestRunner = process.argv[2] != 'child';
if (isTestRunner) { if (isTestRunner) {
var exitCode = -1;
process.on('exit', function() {
assert.equal(exitCode, MAGIC_EXIT_CODE);
});
var master = fork(__filename, ['child']); var master = fork(__filename, ['child']);
master.on('exit', function(code) { master.on('exit', common.mustCall(function(code) {
exitCode = code; assert.strictEqual(code, MAGIC_EXIT_CODE);
}); }));
} else if (cluster.isMaster) { } else if (cluster.isMaster) {
process.on('uncaughtException', function() { process.on('uncaughtException', function() {
process.nextTick(function() { process.nextTick(function() {

18
test/parallel/test-cluster-worker-death.js

@ -1,25 +1,17 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var cluster = require('cluster'); var cluster = require('cluster');
if (!cluster.isMaster) { if (!cluster.isMaster) {
process.exit(42); process.exit(42);
} else { } else {
var seenExit = 0;
var seenDeath = 0;
var worker = cluster.fork(); var worker = cluster.fork();
worker.on('exit', function(exitCode, signalCode) { worker.on('exit', common.mustCall(function(exitCode, signalCode) {
assert.equal(exitCode, 42); assert.equal(exitCode, 42);
assert.equal(signalCode, null); assert.equal(signalCode, null);
seenExit++; }));
}); cluster.on('exit', common.mustCall(function(worker_) {
cluster.on('exit', function(worker_) {
assert.equal(worker_, worker); assert.equal(worker_, worker);
seenDeath++; }));
});
process.on('exit', function() {
assert.equal(seenExit, 1);
assert.equal(seenDeath, 1);
});
} }

33
test/parallel/test-cluster-worker-destroy.js

@ -7,26 +7,18 @@
* both code paths. * both code paths.
*/ */
require('../common'); const common = require('../common');
var cluster = require('cluster'); var cluster = require('cluster');
var assert = require('assert'); var worker1, worker2;
var worker1, worker2, workerExited, workerDisconnected;
if (cluster.isMaster) { if (cluster.isMaster) {
worker1 = cluster.fork(); worker1 = cluster.fork();
worker2 = cluster.fork(); worker2 = cluster.fork();
workerExited = 0;
workerDisconnected = 0;
[worker1, worker2].forEach(function(worker) { [worker1, worker2].forEach(function(worker) {
worker.on('disconnect', ondisconnect); worker.on('disconnect', common.mustCall(function() {}));
worker.on('exit', onexit); worker.on('exit', common.mustCall(function() {}));
}); });
process.on('exit', onProcessExit);
} else { } else {
if (cluster.worker.id === 1) { if (cluster.worker.id === 1) {
// Call destroy when worker is disconnected // Call destroy when worker is disconnected
@ -40,20 +32,3 @@ if (cluster.isMaster) {
cluster.worker.destroy(); 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;
}

20
test/parallel/test-cluster-worker-forced-exit.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var cluster = require('cluster'); var cluster = require('cluster');
@ -24,14 +24,6 @@ if (cluster.isWorker) {
return; return;
} }
var unforcedOk;
var forcedOk;
process.on('exit', function() {
assert(forcedOk);
assert(unforcedOk);
});
checkUnforced(); checkUnforced();
checkForced(); checkForced();
@ -40,10 +32,9 @@ function checkUnforced() {
.on('online', function() { .on('online', function() {
this.disconnect(); this.disconnect();
}) })
.on('exit', function(status) { .on('exit', common.mustCall(function(status) {
assert.equal(status, SENTINEL); assert.equal(status, SENTINEL);
unforcedOk = true; }));
});
} }
function checkForced() { function checkForced() {
@ -51,8 +42,7 @@ function checkForced() {
.on('online', function() { .on('online', function() {
this.process.disconnect(); this.process.disconnect();
}) })
.on('exit', function(status) { .on('exit', common.mustCall(function(status) {
assert.equal(status, 0); assert.equal(status, 0);
forcedOk = true; }));
});
} }

10
test/parallel/test-crypto-domains.js

@ -4,7 +4,6 @@ var domain = require('domain');
var assert = require('assert'); var assert = require('assert');
var d = domain.create(); var d = domain.create();
var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes']; var expect = ['pbkdf2', 'randomBytes', 'pseudoRandomBytes'];
var errors = 0;
if (!common.hasCrypto) { if (!common.hasCrypto) {
common.skip('missing crypto'); common.skip('missing crypto');
@ -12,14 +11,9 @@ if (!common.hasCrypto) {
} }
var crypto = require('crypto'); var crypto = require('crypto');
process.on('exit', function() { d.on('error', common.mustCall(function(e) {
assert.equal(errors, 3);
});
d.on('error', function(e) {
assert.equal(e.message, expect.shift()); assert.equal(e.message, expect.shift());
errors += 1; }, 3));
});
d.run(function() { d.run(function() {
one(); one();

11
test/parallel/test-crypto-hash-stream-pipe.js

@ -12,16 +12,9 @@ var stream = require('stream');
var s = new stream.PassThrough(); var s = new stream.PassThrough();
var h = crypto.createHash('sha1'); var h = crypto.createHash('sha1');
var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e'; var expect = '15987e60950cf22655b9323bc1e281f9c4aff47e';
var gotData = false;
process.on('exit', function() { s.pipe(h).on('data', common.mustCall(function(c) {
assert(gotData);
console.log('ok');
});
s.pipe(h).on('data', function(c) {
assert.equal(c, expect); assert.equal(c, expect);
gotData = true; })).setEncoding('hex');
}).setEncoding('hex');
s.end('aoeu'); s.end('aoeu');

16
test/parallel/test-delayed-require.js

@ -3,13 +3,9 @@ var common = require('../common');
var path = require('path'); var path = require('path');
var assert = require('assert'); var assert = require('assert');
var a; setTimeout(common.mustCall(function() {
setTimeout(function() { const a = require(path.join(common.fixturesDir, 'a'));
a = require(path.join(common.fixturesDir, 'a')); assert.strictEqual(true, 'A' in a);
}, 50); assert.strictEqual('A', a.A());
assert.strictEqual('D', a.D());
process.on('exit', function() { }), 50);
assert.equal(true, 'A' in a);
assert.equal('A', a.A());
assert.equal('D', a.D());
});

11
test/parallel/test-dgram-close-is-not-callback.js

@ -1,21 +1,14 @@
'use strict'; 'use strict';
var assert = require('assert');
var common = require('../common'); var common = require('../common');
var dgram = require('dgram'); var dgram = require('dgram');
var buf = Buffer.alloc(1024, 42); var buf = Buffer.alloc(1024, 42);
var socket = dgram.createSocket('udp4'); var socket = dgram.createSocket('udp4');
var closeEvents = 0;
socket.send(buf, 0, buf.length, common.PORT, 'localhost'); socket.send(buf, 0, buf.length, common.PORT, 'localhost');
// if close callback is not function, ignore the argument. // if close callback is not function, ignore the argument.
socket.close('bad argument'); socket.close('bad argument');
socket.on('close', function() { socket.on('close', common.mustCall(function() {}));
++closeEvents;
});
process.on('exit', function() {
assert.equal(closeEvents, 1);
});

19
test/parallel/test-dgram-close.js

@ -2,24 +2,18 @@
// Ensure that if a dgram socket is closed before the DNS lookup completes, it // Ensure that if a dgram socket is closed before the DNS lookup completes, it
// won't crash. // won't crash.
const assert = require('assert');
const common = require('../common'); const common = require('../common');
const assert = require('assert');
const dgram = require('dgram'); const dgram = require('dgram');
var buf = Buffer.alloc(1024, 42); var buf = Buffer.alloc(1024, 42);
var socket = dgram.createSocket('udp4'); var socket = dgram.createSocket('udp4');
var handle = socket._handle; var handle = socket._handle;
var closeEvents = 0;
var closeCallbacks = 0;
socket.send(buf, 0, buf.length, common.PORT, 'localhost'); socket.send(buf, 0, buf.length, common.PORT, 'localhost');
assert.strictEqual(socket.close(function() { assert.strictEqual(socket.close(common.mustCall(function() {})), socket);
++closeCallbacks; socket.on('close', common.mustCall(function() {}));
}), socket);
socket.on('close', function() {
assert.equal(closeCallbacks, 1);
++closeEvents;
});
socket = null; socket = null;
// Verify that accessing handle after closure doesn't throw // Verify that accessing handle after closure doesn't throw
@ -28,8 +22,3 @@ setImmediate(function() {
console.log('Handle fd is: ', handle.fd); console.log('Handle fd is: ', handle.fd);
}); });
}); });
process.on('exit', function() {
assert.equal(closeEvents, 1);
assert.equal(closeCallbacks, 1);
});

11
test/parallel/test-dgram-implicit-bind.js

@ -1,24 +1,19 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var dgram = require('dgram'); var dgram = require('dgram');
var source = dgram.createSocket('udp4'); var source = dgram.createSocket('udp4');
var target = dgram.createSocket('udp4'); var target = dgram.createSocket('udp4');
var messages = 0; var messages = 0;
process.on('exit', function() { target.on('message', common.mustCall(function(buf) {
assert.equal(messages, 2);
});
target.on('message', function(buf) {
if (buf.toString() === 'abc') ++messages; if (buf.toString() === 'abc') ++messages;
if (buf.toString() === 'def') ++messages; if (buf.toString() === 'def') ++messages;
if (messages === 2) { if (messages === 2) {
source.close(); source.close();
target.close(); target.close();
} }
}); }, 2));
target.on('listening', function() { target.on('listening', function() {
// Second .send() call should not throw a bind error. // Second .send() call should not throw a bind error.

14
test/parallel/test-dgram-unref.js

@ -1,19 +1,9 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var dgram = require('dgram'); var dgram = require('dgram');
var closed = false;
var s = dgram.createSocket('udp4'); var s = dgram.createSocket('udp4');
s.bind(); s.bind();
s.unref(); s.unref();
setTimeout(function() { setTimeout(common.fail, 1000).unref();
closed = true;
s.close();
}, 1000).unref();
process.on('exit', function() {
assert.strictEqual(closed, false, 'Unrefd socket should not hold loop open');
});

16
test/parallel/test-domain-implicit-fs.js

@ -1,15 +1,13 @@
'use strict'; 'use strict';
// Simple tests of most basic domain functionality. // Simple tests of most basic domain functionality.
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var domain = require('domain'); var domain = require('domain');
var caught = 0;
var expectCaught = 1;
var d = new domain.Domain(); var d = new domain.Domain();
d.on('error', function(er) { d.on('error', common.mustCall(function(er) {
console.error('caught', er); console.error('caught', er);
assert.strictEqual(er.domain, d); assert.strictEqual(er.domain, d);
@ -18,15 +16,7 @@ d.on('error', function(er) {
assert.strictEqual(er.code, 'ENOENT'); assert.strictEqual(er.code, 'ENOENT');
assert.ok(/\bthis file does not exist\b/i.test(er.path)); assert.ok(/\bthis file does not exist\b/i.test(er.path));
assert.strictEqual(typeof er.errno, 'number'); 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 // implicit handling of thrown errors while in a domain, via the

24
test/parallel/test-domain-timers.js

@ -1,16 +1,16 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var domain = require('domain'); var domain = require('domain');
var assert = require('assert'); var assert = require('assert');
var timeout_err, timeout, immediate_err; var timeout;
var timeoutd = domain.create(); var timeoutd = domain.create();
timeoutd.on('error', function(e) { timeoutd.on('error', common.mustCall(function(e) {
timeout_err = e; assert.equal(e.message, 'Timeout UNREFd', 'Domain should catch timer error');
clearTimeout(timeout); clearTimeout(timeout);
}); }));
timeoutd.run(function() { timeoutd.run(function() {
setTimeout(function() { setTimeout(function() {
@ -20,9 +20,10 @@ timeoutd.run(function() {
var immediated = domain.create(); var immediated = domain.create();
immediated.on('error', function(e) { immediated.on('error', common.mustCall(function(e) {
immediate_err = e; assert.equal(e.message, 'Immediate Error',
}); 'Domain should catch immediate error');
}));
immediated.run(function() { immediated.run(function() {
setImmediate(function() { setImmediate(function() {
@ -31,10 +32,3 @@ immediated.run(function() {
}); });
timeout = setTimeout(function() {}, 10 * 1000); 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');
});

37
test/parallel/test-error-reporting.js

@ -4,8 +4,6 @@ var assert = require('assert');
var exec = require('child_process').exec; var exec = require('child_process').exec;
var path = require('path'); var path = require('path');
var exits = 0;
function errExec(script, callback) { function errExec(script, callback) {
var cmd = '"' + process.argv[0] + '" "' + var cmd = '"' + process.argv[0] + '" "' +
path.join(common.fixturesDir, script) + '"'; path.join(common.fixturesDir, script) + '"';
@ -21,52 +19,45 @@ function errExec(script, callback) {
// Proxy the args for more tests. // Proxy the args for more tests.
callback(err, stdout, stderr); callback(err, stdout, stderr);
// Count the tests
exits++;
}); });
} }
// Simple throw error // 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)); assert.ok(/blah/.test(stderr));
}); }));
// Trying to JSON.parse(undefined) // 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)); assert.ok(/SyntaxError/.test(stderr));
}); }));
// Trying to JSON.parse(undefined) in nextTick // 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)); assert.ok(/SyntaxError/.test(stderr));
}); }));
// throw ILLEGAL error // 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(/\/\*\*/.test(stderr));
assert.ok(/SyntaxError/.test(stderr)); assert.ok(/SyntaxError/.test(stderr));
}); }));
// Specific long exception line doesn't result in stack overflow // 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)); assert.ok(/SyntaxError/.test(stderr));
}); }));
// Long exception line with length > errorBuffer doesn't result in assertion // 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)); assert.ok(/SyntaxError/.test(stderr));
}); }));
// Object that throws in toString() doesn't print garbage // 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(/<toString\(\) threw exception/.test(stderr)); assert.ok(/<toString\(\) threw exception/.test(stderr));
}); }));
process.on('exit', function() {
assert.equal(7, exits);
});

22
test/parallel/test-eval.js

@ -1,27 +1,13 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var util = require('util'); var util = require('util');
var assert = require('assert'); var assert = require('assert');
var exec = require('child_process').exec; var exec = require('child_process').exec;
var success_count = 0;
var error_count = 0;
var cmd = ['"' + process.execPath + '"', '-e', '"console.error(process.argv)"', var cmd = ['"' + process.execPath + '"', '-e', '"console.error(process.argv)"',
'foo', 'bar'].join(' '); 'foo', 'bar'].join(' ');
var expected = util.format([process.execPath, 'foo', 'bar']) + '\n'; var expected = util.format([process.execPath, 'foo', 'bar']) + '\n';
exec(cmd, function(err, stdout, stderr) { exec(cmd, common.mustCall(function(err, stdout, stderr) {
if (err) { assert.ifError(err);
console.log(err.toString());
++error_count;
return;
}
assert.equal(stderr, expected); assert.equal(stderr, expected);
++success_count; }));
});
process.on('exit', function() {
assert.equal(1, success_count);
assert.equal(0, error_count);
});

13
test/parallel/test-event-emitter-max-listeners.js

@ -1,19 +1,10 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var events = require('events'); var events = require('events');
var gotEvent = false;
process.on('exit', function() {
assert(gotEvent);
});
var e = new events.EventEmitter(); var e = new events.EventEmitter();
e.on('maxListeners', function() { e.on('maxListeners', common.mustCall(function() {}));
gotEvent = true;
});
// Should not corrupt the 'maxListeners' queue. // Should not corrupt the 'maxListeners' queue.
e.setMaxListeners(42); e.setMaxListeners(42);

14
test/parallel/test-event-emitter-no-error-provided-to-error-event.js

@ -1,22 +1,14 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var events = require('events'); var events = require('events');
var domain = require('domain'); var domain = require('domain');
var errorCatched = false;
var e = new events.EventEmitter(); var e = new events.EventEmitter();
var d = domain.create(); var d = domain.create();
d.add(e); d.add(e);
d.on('error', function(er) { d.on('error', common.mustCall(function(er) {
assert(er instanceof Error, 'error created'); assert(er instanceof Error, 'error created');
errorCatched = true; }));
});
e.emit('error'); e.emit('error');
process.on('exit', function() {
assert(errorCatched, 'error got caught');
});

25
test/parallel/test-event-emitter-once.js

@ -1,14 +1,10 @@
'use strict'; 'use strict';
const common = require('../common'); const common = require('../common');
var assert = require('assert');
var events = require('events'); var events = require('events');
var e = new events.EventEmitter(); var e = new events.EventEmitter();
var times_hello_emited = 0;
e.once('hello', function(a, b) { e.once('hello', common.mustCall(function(a, b) {}));
times_hello_emited++;
});
e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b');
e.emit('hello', 'a', 'b'); e.emit('hello', 'a', 'b');
@ -23,23 +19,10 @@ e.once('foo', remove);
e.removeListener('foo', remove); e.removeListener('foo', remove);
e.emit('foo'); e.emit('foo');
process.on('exit', function() { e.once('e', common.mustCall(function() {
assert.equal(1, times_hello_emited);
});
var times_recurse_emitted = 0;
e.once('e', function() {
e.emit('e'); e.emit('e');
times_recurse_emitted++; }));
});
e.once('e', function() { e.once('e', common.mustCall(function() {}));
times_recurse_emitted++;
});
e.emit('e'); e.emit('e');
process.on('exit', function() {
assert.equal(2, times_recurse_emitted);
});

8
test/parallel/test-event-emitter-subclass.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var EventEmitter = require('events').EventEmitter; var EventEmitter = require('events').EventEmitter;
var util = require('util'); var util = require('util');
@ -13,10 +13,7 @@ function MyEE(cb) {
EventEmitter.call(this); EventEmitter.call(this);
} }
var called = false; var myee = new MyEE(common.mustCall(function() {}));
var myee = new MyEE(function() {
called = true;
});
util.inherits(ErrorEE, EventEmitter); util.inherits(ErrorEE, EventEmitter);
@ -29,7 +26,6 @@ assert.throws(function() {
}, /blerg/); }, /blerg/);
process.on('exit', function() { process.on('exit', function() {
assert(called);
assert(!(myee._events instanceof Object)); assert(!(myee._events instanceof Object));
assert.deepStrictEqual(Object.keys(myee._events), []); assert.deepStrictEqual(Object.keys(myee._events), []);
console.log('ok'); console.log('ok');

18
test/parallel/test-exception-handler.js

@ -1,27 +1,19 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var MESSAGE = 'catch me if you can'; var MESSAGE = 'catch me if you can';
var caughtException = false;
process.on('uncaughtException', function(e) { process.on('uncaughtException', common.mustCall(function(e) {
console.log('uncaught exception! 1'); console.log('uncaught exception! 1');
assert.equal(MESSAGE, e.message); assert.equal(MESSAGE, e.message);
caughtException = true; }));
});
process.on('uncaughtException', function(e) { process.on('uncaughtException', common.mustCall(function(e) {
console.log('uncaught exception! 2'); console.log('uncaught exception! 2');
assert.equal(MESSAGE, e.message); assert.equal(MESSAGE, e.message);
caughtException = true; }));
});
setTimeout(function() { setTimeout(function() {
throw new Error(MESSAGE); throw new Error(MESSAGE);
}, 10); }, 10);
process.on('exit', function() {
console.log('exit');
assert.equal(true, caughtException);
});

18
test/parallel/test-file-read-noexist.js

@ -3,20 +3,8 @@ var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var path = require('path'); var path = require('path');
var fs = require('fs'); var fs = require('fs');
var got_error = false;
var filename = path.join(common.fixturesDir, 'does_not_exist.txt'); var filename = path.join(common.fixturesDir, 'does_not_exist.txt');
fs.readFile(filename, 'latin1', function(err, content) { fs.readFile(filename, 'latin1', common.mustCall(function(err, content) {
if (err) { assert.ok(err);
got_error = true; }));
} else {
console.error('cat returned some content: ' + content);
console.error('this shouldn\'t happen as the file doesn\'t exist...');
assert.equal(true, false);
}
});
process.on('exit', function() {
console.log('done');
assert.equal(true, got_error);
});

21
test/parallel/test-fs-exists.js

@ -1,23 +1,16 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var fs = require('fs'); var fs = require('fs');
var f = __filename; var f = __filename;
var exists;
var doesNotExist;
fs.exists(f, function(y) { fs.exists(f, common.mustCall(function(y) {
exists = y; assert.strictEqual(y, true);
}); }));
fs.exists(f + '-NO', function(y) { fs.exists(f + '-NO', common.mustCall(function(y) {
doesNotExist = y; assert.strictEqual(y, false);
}); }));
assert(fs.existsSync(f)); assert(fs.existsSync(f));
assert(!fs.existsSync(f + '-NO')); assert(!fs.existsSync(f + '-NO'));
process.on('exit', function() {
assert.strictEqual(exists, true);
assert.strictEqual(doesNotExist, false);
});

14
test/parallel/test-fs-long-path.js

@ -2,15 +2,12 @@
var common = require('../common'); var common = require('../common');
var fs = require('fs'); var fs = require('fs');
var path = require('path'); var path = require('path');
var assert = require('assert');
if (!common.isWindows) { if (!common.isWindows) {
common.skip('this test is Windows-specific.'); common.skip('this test is Windows-specific.');
return; return;
} }
var successes = 0;
// make a path that will be at least 260 chars long. // make a path that will be at least 260 chars long.
var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1); var fileNameLen = Math.max(260 - common.tmpDir.length - 1, 1);
var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x')); var fileName = path.join(common.tmpDir, new Array(fileNameLen + 1).join('x'));
@ -23,17 +20,14 @@ console.log({
fullPathLength: fullPath.length fullPathLength: fullPath.length
}); });
fs.writeFile(fullPath, 'ok', function(err) { fs.writeFile(fullPath, 'ok', common.mustCall(function(err) {
if (err) throw err; if (err) throw err;
successes++;
fs.stat(fullPath, function(err, stats) { fs.stat(fullPath, common.mustCall(function(err, stats) {
if (err) throw err; if (err) throw err;
successes++; }));
}); }));
});
process.on('exit', function() { process.on('exit', function() {
fs.unlinkSync(fullPath); fs.unlinkSync(fullPath);
assert.equal(2, successes);
}); });

20
test/parallel/test-fs-open.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var fs = require('fs'); var fs = require('fs');
@ -14,24 +14,14 @@ try {
} }
assert.ok(caughtException); assert.ok(caughtException);
var openFd; fs.open(__filename, 'r', common.mustCall(function(err, fd) {
fs.open(__filename, 'r', function(err, fd) {
if (err) { if (err) {
throw err; throw err;
} }
openFd = fd; }));
});
var openFd2; fs.open(__filename, 'rs', common.mustCall(function(err, fd) {
fs.open(__filename, 'rs', function(err, fd) {
if (err) { if (err) {
throw err; throw err;
} }
openFd2 = fd; }));
});
process.on('exit', function() {
assert.ok(openFd);
assert.ok(openFd2);
});

20
test/parallel/test-fs-read-buffer.js

@ -9,19 +9,17 @@ const fd = fs.openSync(filepath, 'r');
const expected = 'xyz\n'; const expected = 'xyz\n';
const bufferAsync = Buffer.allocUnsafe(expected.length); const bufferAsync = Buffer.allocUnsafe(expected.length);
const bufferSync = Buffer.allocUnsafe(expected.length); const bufferSync = Buffer.allocUnsafe(expected.length);
let readCalled = 0;
fs.read(fd, bufferAsync, 0, expected.length, 0, function(err, bytesRead) { fs.read(fd,
readCalled++; bufferAsync,
0,
assert.equal(bytesRead, expected.length); expected.length,
assert.deepStrictEqual(bufferAsync, Buffer.from(expected)); 0,
}); common.mustCall(function(err, bytesRead) {
assert.equal(bytesRead, expected.length);
assert.deepStrictEqual(bufferAsync, Buffer.from(expected));
}));
var r = fs.readSync(fd, bufferSync, 0, expected.length, 0); var r = fs.readSync(fd, bufferSync, 0, expected.length, 0);
assert.deepStrictEqual(bufferSync, Buffer.from(expected)); assert.deepStrictEqual(bufferSync, Buffer.from(expected));
assert.equal(r, expected.length); assert.equal(r, expected.length);
process.on('exit', function() {
assert.equal(readCalled, 1);
});

21
test/parallel/test-fs-read.js

@ -6,20 +6,17 @@ const fs = require('fs');
const filepath = path.join(common.fixturesDir, 'x.txt'); const filepath = path.join(common.fixturesDir, 'x.txt');
const fd = fs.openSync(filepath, 'r'); const fd = fs.openSync(filepath, 'r');
const expected = 'xyz\n'; const expected = 'xyz\n';
let readCalled = 0;
fs.read(fd, expected.length, 0, 'utf-8', function(err, str, bytesRead) { fs.read(fd,
readCalled++; expected.length,
0,
assert.ok(!err); 'utf-8',
assert.equal(str, expected); common.mustCall(function(err, str, bytesRead) {
assert.equal(bytesRead, expected.length); assert.ok(!err);
}); assert.equal(str, expected);
assert.equal(bytesRead, expected.length);
}));
var r = fs.readSync(fd, expected.length, 0, 'utf-8'); var r = fs.readSync(fd, expected.length, 0, 'utf-8');
assert.equal(r[0], expected); assert.equal(r[0], expected);
assert.equal(r[1], expected.length); assert.equal(r[1], expected.length);
process.on('exit', function() {
assert.equal(readCalled, 1);
});

16
test/parallel/test-fs-readfile-error.js

@ -11,8 +11,6 @@ if (process.platform === 'freebsd') {
return; return;
} }
var callbacks = 0;
function test(env, cb) { function test(env, cb) {
var filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js'); var filename = path.join(common.fixturesDir, 'test-fs-readfile-error.js');
var execPath = '"' + process.execPath + '" "' + filename + '"'; var execPath = '"' + process.execPath + '" "' + filename + '"';
@ -25,18 +23,12 @@ function test(env, cb) {
}); });
} }
test({ NODE_DEBUG: '' }, function(data) { test({ NODE_DEBUG: '' }, common.mustCall(function(data) {
assert(/EISDIR/.test(data)); assert(/EISDIR/.test(data));
assert(!/test-fs-readfile-error/.test(data)); assert(!/test-fs-readfile-error/.test(data));
callbacks++; }));
});
test({ NODE_DEBUG: 'fs' }, function(data) { test({ NODE_DEBUG: 'fs' }, common.mustCall(function(data) {
assert(/EISDIR/.test(data)); assert(/EISDIR/.test(data));
assert(/test-fs-readfile-error/.test(data)); assert(/test-fs-readfile-error/.test(data));
callbacks++; }));
});
process.on('exit', function() {
assert.equal(callbacks, 2);
});

13
test/parallel/test-fs-readfile-zero-byte-liar.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var fs = require('fs'); var fs = require('fs');
@ -26,13 +26,6 @@ fs.fstatSync = function(fd) {
var d = fs.readFileSync(__filename, 'utf8'); var d = fs.readFileSync(__filename, 'utf8');
assert.equal(d, dataExpected); assert.equal(d, dataExpected);
var called = false; fs.readFile(__filename, 'utf8', common.mustCall(function(er, d) {
fs.readFile(__filename, 'utf8', function(er, d) {
assert.equal(d, dataExpected); assert.equal(d, dataExpected);
called = true; }));
});
process.on('exit', function() {
assert(called);
console.log('ok');
});

11
test/parallel/test-fs-realpath.js

@ -68,18 +68,11 @@ function asynctest(testBlock, args, callback, assertBlock) {
// sub-tests: // sub-tests:
function test_simple_error_callback(cb) { function test_simple_error_callback(cb) {
var ncalls = 0; fs.realpath('/this/path/does/not/exist', common.mustCall(function(err, s) {
fs.realpath('/this/path/does/not/exist', function(err, s) {
assert(err); assert(err);
assert(!s); assert(!s);
ncalls++;
cb(); cb();
}); }));
process.on('exit', function() {
assert.equal(ncalls, 1);
});
} }
function test_simple_relative_symlink(callback) { function test_simple_relative_symlink(callback) {

107
test/parallel/test-fs-stat.js

@ -1,108 +1,81 @@
/* eslint-disable strict */ /* eslint-disable strict */
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var fs = require('fs'); var fs = require('fs');
var got_error = false;
var success_count = 0;
fs.stat('.', function(err, stats) { fs.stat('.', common.mustCall(function(err, stats) {
if (err) { assert.ifError(err);
got_error = true; assert.ok(stats.mtime instanceof Date);
} else {
console.dir(stats);
assert.ok(stats.mtime instanceof Date);
success_count++;
}
assert(this === global); assert(this === global);
}); }));
fs.stat('.', function(err, stats) { fs.stat('.', common.mustCall(function(err, stats) {
assert.ok(stats.hasOwnProperty('blksize')); assert.ok(stats.hasOwnProperty('blksize'));
assert.ok(stats.hasOwnProperty('blocks')); assert.ok(stats.hasOwnProperty('blocks'));
}); }));
fs.lstat('.', function(err, stats) { fs.lstat('.', common.mustCall(function(err, stats) {
if (err) { assert.ifError(err);
got_error = true; assert.ok(stats.mtime instanceof Date);
} else {
console.dir(stats);
assert.ok(stats.mtime instanceof Date);
success_count++;
}
assert(this === global); assert(this === global);
}); }));
// fstat // fstat
fs.open('.', 'r', undefined, function(err, fd) { fs.open('.', 'r', undefined, common.mustCall(function(err, fd) {
assert.ok(!err); assert.ok(!err);
assert.ok(fd); assert.ok(fd);
fs.fstat(fd, function(err, stats) { fs.fstat(fd, common.mustCall(function(err, stats) {
if (err) { assert.ifError(err);
got_error = true; assert.ok(stats.mtime instanceof Date);
} else { fs.close(fd);
console.dir(stats);
assert.ok(stats.mtime instanceof Date);
success_count++;
fs.close(fd);
}
assert(this === global); assert(this === global);
}); }));
assert(this === global); assert(this === global);
}); }));
// fstatSync // fstatSync
fs.open('.', 'r', undefined, function(err, fd) { fs.open('.', 'r', undefined, common.mustCall(function(err, fd) {
var stats; var stats;
try { try {
stats = fs.fstatSync(fd); stats = fs.fstatSync(fd);
} catch (err) { } catch (err) {
got_error = true; common.fail(err);
} }
if (stats) { if (stats) {
console.dir(stats); console.dir(stats);
assert.ok(stats.mtime instanceof Date); assert.ok(stats.mtime instanceof Date);
success_count++;
} }
fs.close(fd); fs.close(fd);
}); }));
console.log(`stating: ${__filename}`); console.log(`stating: ${__filename}`);
fs.stat(__filename, function(err, s) { fs.stat(__filename, common.mustCall(function(err, s) {
if (err) { assert.ifError(err);
got_error = true;
} else {
console.dir(s);
success_count++;
console.log('isDirectory: ' + JSON.stringify(s.isDirectory())); console.dir(s);
assert.equal(false, s.isDirectory());
console.log('isFile: ' + JSON.stringify(s.isFile())); console.log('isDirectory: ' + JSON.stringify(s.isDirectory()));
assert.equal(true, s.isFile()); assert.equal(false, s.isDirectory());
console.log('isSocket: ' + JSON.stringify(s.isSocket())); console.log('isFile: ' + JSON.stringify(s.isFile()));
assert.equal(false, s.isSocket()); assert.equal(true, s.isFile());
console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice())); console.log('isSocket: ' + JSON.stringify(s.isSocket()));
assert.equal(false, s.isBlockDevice()); assert.equal(false, s.isSocket());
console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice())); console.log('isBlockDevice: ' + JSON.stringify(s.isBlockDevice()));
assert.equal(false, s.isCharacterDevice()); assert.equal(false, s.isBlockDevice());
console.log('isFIFO: ' + JSON.stringify(s.isFIFO())); console.log('isCharacterDevice: ' + JSON.stringify(s.isCharacterDevice()));
assert.equal(false, s.isFIFO()); assert.equal(false, s.isCharacterDevice());
console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink())); console.log('isFIFO: ' + JSON.stringify(s.isFIFO()));
assert.equal(false, s.isSymbolicLink()); assert.equal(false, s.isFIFO());
assert.ok(s.mtime instanceof Date);
}
});
process.on('exit', function() { console.log('isSymbolicLink: ' + JSON.stringify(s.isSymbolicLink()));
assert.equal(5, success_count); assert.equal(false, s.isSymbolicLink());
assert.equal(false, got_error);
});
assert.ok(s.mtime instanceof Date);
}));

19
test/parallel/test-fs-stream-double-close.js

@ -1,6 +1,5 @@
'use strict'; 'use strict';
var common = require('../common'); var common = require('../common');
var assert = require('assert');
var fs = require('fs'); var fs = require('fs');
common.refreshTmpDir(); common.refreshTmpDir();
@ -20,24 +19,14 @@ function test1(stream) {
function test2(stream) { function test2(stream) {
stream.destroy(); stream.destroy();
stream.on('open', function(fd) { stream.on('open', common.mustCall(function(fd) {
stream.destroy(); stream.destroy();
open_cb_called++; }));
});
process.on('exit', function() {
assert.equal(open_cb_called, 1);
});
var open_cb_called = 0;
} }
function test3(stream) { function test3(stream) {
stream.on('open', function(fd) { stream.on('open', common.mustCall(function(fd) {
stream.destroy(); stream.destroy();
stream.destroy(); stream.destroy();
open_cb_called++; }));
});
process.on('exit', function() {
assert.equal(open_cb_called, 1);
});
var open_cb_called = 0;
} }

12
test/parallel/test-fs-symlink-dir-junction-relative.js

@ -5,8 +5,6 @@ var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var path = require('path'); var path = require('path');
var fs = require('fs'); var fs = require('fs');
var completed = 0;
var expected_tests = 2;
var linkPath1 = path.join(common.tmpDir, 'junction1'); var linkPath1 = path.join(common.tmpDir, 'junction1');
var linkPath2 = path.join(common.tmpDir, 'junction2'); var linkPath2 = path.join(common.tmpDir, 'junction2');
@ -16,10 +14,10 @@ var linkData = path.join(common.fixturesDir);
common.refreshTmpDir(); common.refreshTmpDir();
// Test fs.symlink() // Test fs.symlink()
fs.symlink(linkData, linkPath1, 'junction', function(err) { fs.symlink(linkData, linkPath1, 'junction', common.mustCall(function(err) {
if (err) throw err; if (err) throw err;
verifyLink(linkPath1); verifyLink(linkPath1);
}); }));
// Test fs.symlinkSync() // Test fs.symlinkSync()
fs.symlinkSync(linkData, linkPath2, 'junction'); fs.symlinkSync(linkData, linkPath2, 'junction');
@ -35,10 +33,4 @@ function verifyLink(linkPath) {
// Clean up. // Clean up.
fs.unlinkSync(linkPath); fs.unlinkSync(linkPath);
completed++;
} }
process.on('exit', function() {
assert.equal(completed, expected_tests);
});

27
test/parallel/test-fs-symlink-dir-junction.js

@ -3,8 +3,6 @@ var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var path = require('path'); var path = require('path');
var fs = require('fs'); var fs = require('fs');
var completed = 0;
var expected_tests = 4;
// test creating and reading symbolic link // test creating and reading symbolic link
var linkData = path.join(common.fixturesDir, 'cycles/'); var linkData = path.join(common.fixturesDir, 'cycles/');
@ -15,31 +13,22 @@ common.refreshTmpDir();
console.log('linkData: ' + linkData); console.log('linkData: ' + linkData);
console.log('linkPath: ' + linkPath); console.log('linkPath: ' + linkPath);
fs.symlink(linkData, linkPath, 'junction', function(err) { fs.symlink(linkData, linkPath, 'junction', common.mustCall(function(err) {
if (err) throw err; if (err) throw err;
completed++;
fs.lstat(linkPath, function(err, stats) { fs.lstat(linkPath, common.mustCall(function(err, stats) {
if (err) throw err; if (err) throw err;
assert.ok(stats.isSymbolicLink()); assert.ok(stats.isSymbolicLink());
completed++;
fs.readlink(linkPath, function(err, destination) { fs.readlink(linkPath, common.mustCall(function(err, destination) {
if (err) throw err; if (err) throw err;
assert.equal(destination, linkData); assert.equal(destination, linkData);
completed++;
fs.unlink(linkPath, function(err) { fs.unlink(linkPath, common.mustCall(function(err) {
if (err) throw err; if (err) throw err;
assert(!common.fileExists(linkPath)); assert(!common.fileExists(linkPath));
assert(common.fileExists(linkData)); assert(common.fileExists(linkData));
completed++; }));
}); }));
}); }));
}); }));
});
process.on('exit', function() {
assert.equal(completed, expected_tests);
});

8
test/parallel/test-fs-truncate-fd.js

@ -7,19 +7,15 @@ var tmp = common.tmpDir;
common.refreshTmpDir(); common.refreshTmpDir();
var filename = path.resolve(tmp, 'truncate-file.txt'); var filename = path.resolve(tmp, 'truncate-file.txt');
var success = 0;
fs.writeFileSync(filename, 'hello world', 'utf8'); fs.writeFileSync(filename, 'hello world', 'utf8');
var fd = fs.openSync(filename, 'r+'); var fd = fs.openSync(filename, 'r+');
fs.truncate(fd, 5, function(err) { fs.truncate(fd, 5, common.mustCall(function(err) {
assert.ok(!err); assert.ok(!err);
assert.equal(fs.readFileSync(filename, 'utf8'), 'hello'); assert.equal(fs.readFileSync(filename, 'utf8'), 'hello');
success++; }));
});
process.on('exit', function() { process.on('exit', function() {
fs.closeSync(fd); fs.closeSync(fd);
fs.unlinkSync(filename); fs.unlinkSync(filename);
assert.equal(success, 1);
console.log('ok'); console.log('ok');
}); });

16
test/parallel/test-fs-truncate.js

@ -42,20 +42,12 @@ assert.equal(stat.size, 0);
fs.closeSync(fd); fs.closeSync(fd);
// async tests // async tests
var success = 0; testTruncate(common.mustCall(function(er) {
testTruncate(function(er) {
if (er) throw er; if (er) throw er;
success++; testFtruncate(common.mustCall(function(er) {
testFtruncate(function(er) {
if (er) throw er; if (er) throw er;
success++; }));
}); }));
});
process.on('exit', function() {
assert.equal(success, 2);
console.log('ok');
});
function testTruncate(cb) { function testTruncate(cb) {
fs.writeFile(filename, data, function(er) { fs.writeFile(filename, data, function(er) {

35
test/parallel/test-fs-write-buffer.js

@ -6,30 +6,25 @@ const Buffer = require('buffer').Buffer;
const fs = require('fs'); const fs = require('fs');
const filename = path.join(common.tmpDir, 'write.txt'); const filename = path.join(common.tmpDir, 'write.txt');
const expected = Buffer.from('hello'); const expected = Buffer.from('hello');
let openCalled = 0;
let writeCalled = 0;
common.refreshTmpDir(); common.refreshTmpDir();
fs.open(filename, 'w', 0o644, function(err, fd) { fs.open(filename, 'w', 0o644, common.mustCall(function(err, fd) {
openCalled++;
if (err) throw err; if (err) throw err;
fs.write(fd, expected, 0, expected.length, null, function(err, written) { fs.write(fd,
writeCalled++; expected,
if (err) throw err; 0,
expected.length,
assert.equal(expected.length, written); null,
fs.closeSync(fd); common.mustCall(function(err, written) {
if (err) throw err;
var found = fs.readFileSync(filename, 'utf8'); assert.equal(expected.length, written);
assert.deepStrictEqual(expected.toString(), found); fs.closeSync(fd);
fs.unlinkSync(filename);
});
});
process.on('exit', function() { var found = fs.readFileSync(filename, 'utf8');
assert.equal(1, openCalled); assert.deepStrictEqual(expected.toString(), found);
assert.equal(1, writeCalled); fs.unlinkSync(filename);
}); }));
}));

62
test/parallel/test-fs-write-file.js

@ -17,41 +17,34 @@ var s = '南越国是前203年至前111年存在于岭南地区的一个国家
'历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' + '历经五代君主。南越国是岭南地区的第一个有记载的政权国家,采用封建制和郡县制并存的制度,' +
'它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n'; '它的建立保证了秦末乱世岭南地区社会秩序的稳定,有效的改善了岭南地区落后的政治、##济现状。\n';
var ncallbacks = 0; fs.writeFile(filename, s, common.mustCall(function(e) {
fs.writeFile(filename, s, function(e) {
if (e) throw e; if (e) throw e;
ncallbacks++; fs.readFile(filename, common.mustCall(function(e, buffer) {
fs.readFile(filename, function(e, buffer) {
if (e) throw e; if (e) throw e;
ncallbacks++;
assert.equal(Buffer.byteLength(s), buffer.length); assert.equal(Buffer.byteLength(s), buffer.length);
}); }));
}); }));
// test that writeFile accepts buffers // test that writeFile accepts buffers
var filename2 = join(common.tmpDir, 'test2.txt'); var filename2 = join(common.tmpDir, 'test2.txt');
var buf = Buffer.from(s, 'utf8'); var buf = Buffer.from(s, 'utf8');
fs.writeFile(filename2, buf, function(e) { fs.writeFile(filename2, buf, common.mustCall(function(e) {
if (e) throw e; if (e) throw e;
ncallbacks++; fs.readFile(filename2, common.mustCall(function(e, buffer) {
fs.readFile(filename2, function(e, buffer) {
if (e) throw e; if (e) throw e;
ncallbacks++;
assert.equal(buf.length, buffer.length); assert.equal(buf.length, buffer.length);
}); }));
}); }));
// test that writeFile accepts numbers. // test that writeFile accepts numbers.
var filename3 = join(common.tmpDir, 'test3.txt'); var filename3 = join(common.tmpDir, 'test3.txt');
var m = 0o600; var m = 0o600;
fs.writeFile(filename3, n, { mode: m }, function(e) { fs.writeFile(filename3, n, { mode: m }, common.mustCall(function(e) {
if (e) throw e; if (e) throw e;
// windows permissions aren't unix // windows permissions aren't unix
@ -60,46 +53,35 @@ fs.writeFile(filename3, n, { mode: m }, function(e) {
assert.equal(st.mode & 0o700, m); assert.equal(st.mode & 0o700, m);
} }
ncallbacks++; fs.readFile(filename3, common.mustCall(function(e, buffer) {
fs.readFile(filename3, function(e, buffer) {
if (e) throw e; if (e) throw e;
ncallbacks++;
assert.equal(Buffer.byteLength('' + n), buffer.length); assert.equal(Buffer.byteLength('' + n), buffer.length);
}); }));
}); }));
// test that writeFile accepts file descriptors // test that writeFile accepts file descriptors
var filename4 = join(common.tmpDir, 'test4.txt'); var filename4 = join(common.tmpDir, 'test4.txt');
fs.open(filename4, 'w+', function(e, fd) { fs.open(filename4, 'w+', common.mustCall(function(e, fd) {
if (e) throw e; if (e) throw e;
ncallbacks++; fs.writeFile(fd, s, common.mustCall(function(e) {
fs.writeFile(fd, s, function(e) {
if (e) throw e; if (e) throw e;
ncallbacks++; fs.close(fd, common.mustCall(function(e) {
fs.close(fd, function(e) {
if (e) throw e; if (e) throw e;
ncallbacks++; fs.readFile(filename4, common.mustCall(function(e, buffer) {
fs.readFile(filename4, function(e, buffer) {
if (e) throw e; if (e) throw e;
ncallbacks++;
assert.equal(Buffer.byteLength(s), buffer.length); assert.equal(Buffer.byteLength(s), buffer.length);
}); }));
}); }));
}); }));
}); }));
process.on('exit', function() { process.on('exit', function() {
assert.equal(10, ncallbacks);
fs.unlinkSync(filename); fs.unlinkSync(filename);
fs.unlinkSync(filename2); fs.unlinkSync(filename2);
fs.unlinkSync(filename3); fs.unlinkSync(filename3);

17
test/parallel/test-fs-write-string-coerce.js

@ -10,24 +10,19 @@ common.refreshTmpDir();
var fn = path.join(common.tmpDir, 'write-string-coerce.txt'); var fn = path.join(common.tmpDir, 'write-string-coerce.txt');
var data = true; var data = true;
var expected = data + ''; var expected = data + '';
var found;
fs.open(fn, 'w', 0o644, function(err, fd) { fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) {
if (err) throw err; if (err) throw err;
console.log('open done'); console.log('open done');
fs.write(fd, data, 0, 'utf8', function(err, written) { fs.write(fd, data, 0, 'utf8', common.mustCall(function(err, written) {
console.log('write done'); console.log('write done');
if (err) throw err; if (err) throw err;
assert.equal(Buffer.byteLength(expected), written); assert.equal(Buffer.byteLength(expected), written);
fs.closeSync(fd); fs.closeSync(fd);
found = fs.readFileSync(fn, 'utf8'); const found = fs.readFileSync(fn, 'utf8');
console.log('expected: "%s"', expected); console.log('expected: "%s"', expected);
console.log('found: "%s"', found); console.log('found: "%s"', found);
fs.unlinkSync(fn); fs.unlinkSync(fn);
}); assert.strictEqual(expected, found);
}); }));
}));
process.on('exit', function() {
assert.equal(expected, found);
});

31
test/parallel/test-fs-write.js

@ -8,50 +8,45 @@ var fn = path.join(common.tmpDir, 'write.txt');
var fn2 = path.join(common.tmpDir, 'write2.txt'); var fn2 = path.join(common.tmpDir, 'write2.txt');
var expected = 'ümlaut.'; var expected = 'ümlaut.';
var constants = fs.constants; var constants = fs.constants;
var found, found2;
common.refreshTmpDir(); common.refreshTmpDir();
fs.open(fn, 'w', 0o644, function(err, fd) { fs.open(fn, 'w', 0o644, common.mustCall(function(err, fd) {
if (err) throw err; if (err) throw err;
console.log('open done'); console.log('open done');
fs.write(fd, '', 0, 'utf8', function(err, written) { fs.write(fd, '', 0, 'utf8', function(err, written) {
assert.equal(0, written); assert.equal(0, written);
}); });
fs.write(fd, expected, 0, 'utf8', function(err, written) { fs.write(fd, expected, 0, 'utf8', common.mustCall(function(err, written) {
console.log('write done'); console.log('write done');
if (err) throw err; if (err) throw err;
assert.equal(Buffer.byteLength(expected), written); assert.equal(Buffer.byteLength(expected), written);
fs.closeSync(fd); fs.closeSync(fd);
found = fs.readFileSync(fn, 'utf8'); const found = fs.readFileSync(fn, 'utf8');
console.log('expected: "%s"', expected); console.log('expected: "%s"', expected);
console.log('found: "%s"', found); console.log('found: "%s"', found);
fs.unlinkSync(fn); fs.unlinkSync(fn);
}); assert.strictEqual(expected, found);
}); }));
}));
fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0o644, fs.open(fn2, constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC, 0o644,
function(err, fd) { common.mustCall(function(err, fd) {
if (err) throw err; if (err) throw err;
console.log('open done'); console.log('open done');
fs.write(fd, '', 0, 'utf8', function(err, written) { fs.write(fd, '', 0, 'utf8', function(err, written) {
assert.equal(0, written); assert.equal(0, written);
}); });
fs.write(fd, expected, 0, 'utf8', function(err, written) { fs.write(fd, expected, 0, 'utf8', common.mustCall(function(err, written) {
console.log('write done'); console.log('write done');
if (err) throw err; if (err) throw err;
assert.equal(Buffer.byteLength(expected), written); assert.equal(Buffer.byteLength(expected), written);
fs.closeSync(fd); fs.closeSync(fd);
found2 = fs.readFileSync(fn2, 'utf8'); const found = fs.readFileSync(fn2, 'utf8');
console.log('expected: "%s"', expected); console.log('expected: "%s"', expected);
console.log('found: "%s"', found2); console.log('found: "%s"', found);
fs.unlinkSync(fn2); fs.unlinkSync(fn2);
}); assert.strictEqual(expected, found);
}); }));
}));
process.on('exit', function() {
assert.equal(expected, found);
assert.equal(expected, found2);
});

6
test/parallel/test-http-abort-before-end.js

@ -1,11 +1,9 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var http = require('http'); var http = require('http');
var assert = require('assert'); var assert = require('assert');
var server = http.createServer(function(req, res) { var server = http.createServer(common.fail);
assert(false); // should not be called
});
server.listen(0, function() { server.listen(0, function() {
var req = http.request({ var req = http.request({

23
test/parallel/test-http-abort-client.js

@ -1,7 +1,6 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var http = require('http'); var http = require('http');
var assert = require('assert');
var server = http.Server(function(req, res) { var server = http.Server(function(req, res) {
console.log('Server accepted request.'); console.log('Server accepted request.');
@ -11,13 +10,11 @@ var server = http.Server(function(req, res) {
res.destroy(); res.destroy();
}); });
var responseClose = false; server.listen(0, common.mustCall(function() {
server.listen(0, function() {
http.get({ http.get({
port: this.address().port, port: this.address().port,
headers: { connection: 'keep-alive' } headers: { connection: 'keep-alive' }
}, function(res) { }, common.mustCall(function(res) {
server.close(); server.close();
console.log('Got res: ' + res.statusCode); console.log('Got res: ' + res.statusCode);
@ -41,14 +38,6 @@ server.listen(0, function() {
}); });
// it would be nice if this worked: // it would be nice if this worked:
res.on('close', function() { res.on('close', common.mustCall(function() {}));
console.log('Response aborted'); }));
responseClose = true; }));
});
});
});
process.on('exit', function() {
assert.ok(responseClose);
});

22
test/parallel/test-http-agent-no-protocol.js

@ -1,20 +1,11 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
var url = require('url'); var url = require('url');
var request = 0; var server = http.createServer(common.mustCall(function(req, res) {
var response = 0;
process.on('exit', function() {
assert.equal(1, request, 'http server "request" callback was not called');
assert.equal(1, response, 'http client "response" callback was not called');
});
var server = http.createServer(function(req, res) {
res.end(); res.end();
request++; })).listen(0, '127.0.0.1', common.mustCall(function() {
}).listen(0, '127.0.0.1', function() {
var opts = url.parse(`http://127.0.0.1:${this.address().port}/`); var opts = url.parse(`http://127.0.0.1:${this.address().port}/`);
// remove the `protocol` field… the `http` module should fall back // remove the `protocol` field… the `http` module should fall back
@ -22,9 +13,8 @@ var server = http.createServer(function(req, res) {
opts.agent = new http.Agent(); opts.agent = new http.Agent();
opts.agent.protocol = null; opts.agent.protocol = null;
http.get(opts, function(res) { http.get(opts, common.mustCall(function(res) {
response++;
res.resume(); res.resume();
server.close(); server.close();
}); }));
}); }));

22
test/parallel/test-http-agent-null.js

@ -1,26 +1,16 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
var request = 0; var server = http.createServer(common.mustCall(function(req, res) {
var response = 0;
process.on('exit', function() {
assert.equal(request, 1, 'http server "request" callback was not called');
assert.equal(response, 1, 'http request "response" callback was not called');
});
var server = http.createServer(function(req, res) {
request++;
res.end(); res.end();
}).listen(0, function() { })).listen(0, common.mustCall(function() {
var options = { var options = {
agent: null, agent: null,
port: this.address().port port: this.address().port
}; };
http.get(options, function(res) { http.get(options, common.mustCall(function(res) {
response++;
res.resume(); res.resume();
server.close(); server.close();
}); }));
}); }));

27
test/parallel/test-http-bind-twice.js

@ -1,26 +1,15 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var gotError = false; var server1 = http.createServer(common.fail);
server1.listen(0, '127.0.0.1', common.mustCall(function() {
var server2 = http.createServer(common.fail);
server2.listen(this.address().port, '127.0.0.1', common.fail);
process.on('exit', function() { server2.on('error', common.mustCall(function(e) {
assert(gotError);
});
function dontCall() {
assert(false);
}
var server1 = http.createServer(dontCall);
server1.listen(0, '127.0.0.1', function() {
var server2 = http.createServer(dontCall);
server2.listen(this.address().port, '127.0.0.1', dontCall);
server2.on('error', function(e) {
assert.equal(e.code, 'EADDRINUSE'); assert.equal(e.code, 'EADDRINUSE');
server1.close(); server1.close();
gotError = true; }));
}); }));
});

14
test/parallel/test-http-blank-header.js

@ -1,13 +1,10 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var net = require('net'); var net = require('net');
var gotReq = false; var server = http.createServer(common.mustCall(function(req, res) {
var server = http.createServer(function(req, res) {
gotReq = true;
assert.equal('GET', req.method); assert.equal('GET', req.method);
assert.equal('/blah', req.url); assert.equal('/blah', req.url);
assert.deepStrictEqual({ assert.deepStrictEqual({
@ -15,7 +12,7 @@ var server = http.createServer(function(req, res) {
origin: 'http://mapdevel.trolologames.ru', origin: 'http://mapdevel.trolologames.ru',
cookie: '' cookie: ''
}, req.headers); }, req.headers);
}); }));
server.listen(0, function() { server.listen(0, function() {
@ -38,8 +35,3 @@ server.listen(0, function() {
server.close(); server.close();
}); });
}); });
process.on('exit', function() {
assert.ok(gotReq);
});

18
test/parallel/test-http-buffer-sanity.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
@ -42,9 +42,7 @@ var web = http.Server(function(req, res) {
}); });
}); });
var gotThanks = false; web.listen(0, common.mustCall(function() {
web.listen(0, function() {
console.log('Making request'); console.log('Making request');
var req = http.request({ var req = http.request({
@ -52,19 +50,17 @@ web.listen(0, function() {
method: 'GET', method: 'GET',
path: '/', path: '/',
headers: { 'content-length': buffer.length } headers: { 'content-length': buffer.length }
}, function(res) { }, common.mustCall(function(res) {
console.log('Got response'); console.log('Got response');
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function(string) { res.on('data', common.mustCall(function(string) {
assert.equal('thanks', string); assert.equal('thanks', string);
gotThanks = true; }));
}); }));
});
req.end(buffer); req.end(buffer);
}); }));
process.on('exit', function() { process.on('exit', function() {
assert.equal(bufferSize, measuredSize); assert.equal(bufferSize, measuredSize);
assert.ok(gotThanks);
}); });

17
test/parallel/test-http-byteswritten.js

@ -1,24 +1,17 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var body = 'hello world\n'; var body = 'hello world\n';
var sawFinish = false; var httpServer = http.createServer(common.mustCall(function(req, res) {
process.on('exit', function() {
assert(sawFinish);
console.log('ok');
});
var httpServer = http.createServer(function(req, res) {
httpServer.close(); httpServer.close();
res.on('finish', function() { res.on('finish', common.mustCall(function() {
sawFinish = true;
assert(typeof req.connection.bytesWritten === 'number'); assert(typeof req.connection.bytesWritten === 'number');
assert(req.connection.bytesWritten > 0); assert(req.connection.bytesWritten > 0);
}); }));
res.writeHead(200, { 'Content-Type': 'text/plain' }); res.writeHead(200, { 'Content-Type': 'text/plain' });
// Write 1.5mb to cause some requests to buffer // 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); assert(res.connection.bytesWritten > 0);
res.end(body); res.end(body);
}); }));
httpServer.listen(0, function() { httpServer.listen(0, function() {
http.get({ port: this.address().port }); http.get({ port: this.address().port });

23
test/parallel/test-http-client-abort-event.js

@ -1,29 +1,20 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
var server = http.createServer(function(req, res) { var server = http.createServer(function(req, res) {
res.end(); res.end();
}); });
var count = 0;
server.listen(0, function() { server.listen(0, common.mustCall(function() {
var req = http.request({ var req = http.request({
port: this.address().port port: this.address().port
}, function() { }, common.fail);
assert(false, 'should not receive data');
});
req.on('abort', function() { req.on('abort', common.mustCall(function() {
// should only be emitted once
count++;
server.close(); server.close();
}); }));
req.end(); req.end();
req.abort(); req.abort();
req.abort(); req.abort();
}); }));
process.on('exit', function() {
assert.equal(count, 1);
});

13
test/parallel/test-http-client-get-url.js

@ -1,24 +1,17 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var seen_req = false; var server = http.createServer(common.mustCall(function(req, res) {
var server = http.createServer(function(req, res) {
assert.equal('GET', req.method); assert.equal('GET', req.method);
assert.equal('/foo?bar', req.url); assert.equal('/foo?bar', req.url);
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('hello\n'); res.write('hello\n');
res.end(); res.end();
server.close(); server.close();
seen_req = true; }));
});
server.listen(0, function() { server.listen(0, function() {
http.get(`http://127.0.0.1:${this.address().port}/foo?bar`); http.get(`http://127.0.0.1:${this.address().port}/foo?bar`);
}); });
process.on('exit', function() {
assert(seen_req);
});

12
test/parallel/test-http-client-readable.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var util = require('util'); var util = require('util');
@ -39,22 +39,18 @@ FakeAgent.prototype.createConnection = function createConnection() {
}; };
var received = ''; var received = '';
var ended = 0;
var req = http.request({ var req = http.request({
agent: new FakeAgent() agent: new FakeAgent()
}, function(res) { }, common.mustCall(function(res) {
res.on('data', function(chunk) { res.on('data', function(chunk) {
received += chunk; received += chunk;
}); });
res.on('end', function() { res.on('end', common.mustCall(function() {}));
ended++; }));
});
});
req.end(); req.end();
process.on('exit', function() { process.on('exit', function() {
assert.equal(received, 'hello world'); assert.equal(received, 'hello world');
assert.equal(ended, 1);
}); });

12
test/parallel/test-http-client-response-domain.js

@ -4,13 +4,8 @@ const assert = require('assert');
const http = require('http'); const http = require('http');
const domain = require('domain'); const domain = require('domain');
var gotDomainError = false;
var d; var d;
process.on('exit', function() {
assert(gotDomainError);
});
common.refreshTmpDir(); common.refreshTmpDir();
// first fire up a simple HTTP server // first fire up a simple HTTP server
@ -22,15 +17,14 @@ var server = http.createServer(function(req, res) {
server.listen(common.PIPE, function() { server.listen(common.PIPE, function() {
// create a domain // create a domain
d = domain.create(); d = domain.create();
d.run(test); d.run(common.mustCall(test));
}); });
function test() { function test() {
d.on('error', function(err) { d.on('error', common.mustCall(function(err) {
gotDomainError = true;
assert.equal('should be caught by domain', err.message); assert.equal('should be caught by domain', err.message);
}); }));
var req = http.get({ var req = http.get({
socketPath: common.PIPE, socketPath: common.PIPE,

36
test/parallel/test-http-client-upload-buf.js

@ -1,52 +1,44 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var N = 1024; 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); assert.equal('POST', req.method);
var bytesReceived = 0;
req.on('data', function(chunk) { req.on('data', function(chunk) {
bytesReceived += chunk.length; bytesReceived += chunk.length;
}); });
req.on('end', function() { req.on('end', common.mustCall(function() {
server_req_complete = true; assert.strictEqual(N, bytesReceived);
console.log('request complete from server'); console.log('request complete from server');
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('hello\n'); res.write('hello\n');
res.end(); res.end();
}); }));
}); }));
server.listen(0); server.listen(0);
server.on('listening', function() { server.on('listening', common.mustCall(function() {
var req = http.request({ var req = http.request({
port: this.address().port, port: this.address().port,
method: 'POST', method: 'POST',
path: '/' path: '/'
}, function(res) { }, common.mustCall(function(res) {
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function(chunk) { res.on('data', function(chunk) {
console.log(chunk); console.log(chunk);
}); });
res.on('end', function() { res.on('end', common.mustCall(function() {
client_res_complete = true;
server.close(); server.close();
}); }));
}); }));
req.write(Buffer.allocUnsafe(N)); req.write(Buffer.allocUnsafe(N));
req.end(); req.end();
}); }));
process.on('exit', function() {
assert.equal(N, bytesReceived);
assert.equal(true, server_req_complete);
assert.equal(true, client_res_complete);
});

37
test/parallel/test-http-client-upload.js

@ -1,55 +1,46 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var sent_body = ''; var server = http.createServer(common.mustCall(function(req, res) {
var server_req_complete = false;
var client_res_complete = false;
var server = http.createServer(function(req, res) {
assert.equal('POST', req.method); assert.equal('POST', req.method);
req.setEncoding('utf8'); req.setEncoding('utf8');
var sent_body = '';
req.on('data', function(chunk) { req.on('data', function(chunk) {
console.log('server got: ' + JSON.stringify(chunk)); console.log('server got: ' + JSON.stringify(chunk));
sent_body += chunk; sent_body += chunk;
}); });
req.on('end', function() { req.on('end', common.mustCall(function() {
server_req_complete = true; assert.strictEqual('1\n2\n3\n', sent_body);
console.log('request complete from server'); console.log('request complete from server');
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('hello\n'); res.write('hello\n');
res.end(); res.end();
}); }));
}); }));
server.listen(0); server.listen(0);
server.on('listening', function() { server.on('listening', common.mustCall(function() {
var req = http.request({ var req = http.request({
port: this.address().port, port: this.address().port,
method: 'POST', method: 'POST',
path: '/' path: '/'
}, function(res) { }, common.mustCall(function(res) {
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function(chunk) { res.on('data', function(chunk) {
console.log(chunk); console.log(chunk);
}); });
res.on('end', function() { res.on('end', common.mustCall(function() {
client_res_complete = true;
server.close(); server.close();
}); }));
}); }));
req.write('1\n'); req.write('1\n');
req.write('2\n'); req.write('2\n');
req.write('3\n'); req.write('3\n');
req.end(); 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);
});

16
test/parallel/test-http-conn-reset.js

@ -1,11 +1,9 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var net = require('net'); var net = require('net');
var caughtError = false;
var options = { var options = {
host: '127.0.0.1', host: '127.0.0.1',
port: undefined port: undefined
@ -16,7 +14,7 @@ var server = net.createServer(function(client) {
client.destroy(); client.destroy();
server.close(); server.close();
}); });
server.listen(0, options.host, onListen); server.listen(0, options.host, common.mustCall(onListen));
// do a GET request, expect it to fail // do a GET request, expect it to fail
function onListen() { function onListen() {
@ -24,14 +22,8 @@ function onListen() {
var req = http.request(options, function(res) { var req = http.request(options, function(res) {
assert.ok(false, 'this should never run'); assert.ok(false, 'this should never run');
}); });
req.on('error', function(err) { req.on('error', common.mustCall(function(err) {
assert.equal(err.code, 'ECONNRESET'); assert.equal(err.code, 'ECONNRESET');
caughtError = true; }));
});
req.end(); req.end();
} }
process.on('exit', function() {
assert.equal(caughtError, true);
});

8
test/parallel/test-http-connect-req-res.js

@ -3,9 +3,7 @@ const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const http = require('http'); const http = require('http');
const server = http.createServer(function(req, res) { const server = http.createServer(common.fail);
assert(false);
});
server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) { server.on('connect', common.mustCall(function(req, socket, firstBodyChunk) {
assert.equal(req.method, 'CONNECT'); assert.equal(req.method, 'CONNECT');
assert.equal(req.url, 'example.com:443'); assert.equal(req.url, 'example.com:443');
@ -33,9 +31,7 @@ server.listen(0, common.mustCall(function() {
port: this.address().port, port: this.address().port,
method: 'CONNECT', method: 'CONNECT',
path: 'example.com:443' path: 'example.com:443'
}, function(res) { }, common.fail);
assert(false);
});
req.on('close', common.mustCall(function() { })); req.on('close', common.mustCall(function() { }));

10
test/parallel/test-http-connect.js

@ -1,14 +1,12 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var serverGotConnect = false; var serverGotConnect = false;
var clientGotConnect = false; var clientGotConnect = false;
var server = http.createServer(function(req, res) { var server = http.createServer(common.fail);
assert(false);
});
server.on('connect', function(req, socket, firstBodyChunk) { server.on('connect', function(req, socket, firstBodyChunk) {
assert.equal(req.method, 'CONNECT'); assert.equal(req.method, 'CONNECT');
assert.equal(req.url, 'google.com:443'); assert.equal(req.url, 'google.com:443');
@ -30,9 +28,7 @@ server.listen(0, function() {
port: this.address().port, port: this.address().port,
method: 'CONNECT', method: 'CONNECT',
path: 'google.com:443' path: 'google.com:443'
}, function(res) { }, common.fail);
assert(false);
});
var clientRequestClosed = false; var clientRequestClosed = false;
req.on('close', function() { req.on('close', function() {

10
test/parallel/test-http-end-throw-socket-handling.js

@ -1,6 +1,5 @@
'use strict'; 'use strict';
const common = require('../common'); const common = require('../common');
const assert = require('assert');
// Make sure that throwing in 'end' handler doesn't lock // Make sure that throwing in 'end' handler doesn't lock
// up the socket forever. // up the socket forever.
@ -29,11 +28,4 @@ server.listen(0, common.mustCall(() => {
} }
})); }));
let errors = 0; process.on('uncaughtException', common.mustCall(() => {}, 10));
process.on('uncaughtException', () => {
errors++;
});
process.on('exit', () => {
assert.equal(errors, 10);
});

24
test/parallel/test-http-extra-response.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var net = require('net'); var net = require('net');
@ -20,9 +20,6 @@ var fullResponse =
'\r\n' + '\r\n' +
body; body;
var gotResponse = false;
var server = net.createServer(function(socket) { var server = net.createServer(function(socket) {
var postBody = ''; var postBody = '';
@ -44,8 +41,8 @@ var server = net.createServer(function(socket) {
}); });
server.listen(0, function() { server.listen(0, common.mustCall(function() {
http.get({ port: this.address().port }, function(res) { http.get({ port: this.address().port }, common.mustCall(function(res) {
var buffer = ''; var buffer = '';
console.log('Got res code: ' + res.statusCode); console.log('Got res code: ' + res.statusCode);
@ -54,17 +51,10 @@ server.listen(0, function() {
buffer += chunk; buffer += chunk;
}); });
res.on('end', function() { res.on('end', common.mustCall(function() {
console.log('Response ended, read ' + buffer.length + ' bytes'); console.log('Response ended, read ' + buffer.length + ' bytes');
assert.equal(body, buffer); assert.equal(body, buffer);
server.close(); server.close();
gotResponse = true; }));
}); }));
}); }));
});
process.on('exit', function() {
assert.ok(gotResponse);
});

25
test/parallel/test-http-full-response.js

@ -17,8 +17,6 @@ var server = http.createServer(function(req, res) {
res.end(body); res.end(body);
}); });
var runs = 0;
function runAb(opts, callback) { function runAb(opts, callback) {
var command = `ab ${opts} http://127.0.0.1:${server.address().port}/`; var command = `ab ${opts} http://127.0.0.1:${server.address().port}/`;
exec(command, function(err, stdout, stderr) { exec(command, function(err, stdout, stderr) {
@ -43,28 +41,21 @@ function runAb(opts, callback) {
assert.equal(bodyLength, documentLength); assert.equal(bodyLength, documentLength);
assert.equal(completeRequests * documentLength, htmlTransfered); assert.equal(completeRequests * documentLength, htmlTransfered);
runs++;
if (callback) callback(); if (callback) callback();
}); });
} }
server.listen(0, function() { server.listen(0, common.mustCall(function() {
runAb('-c 1 -n 10', function() { runAb('-c 1 -n 10', common.mustCall(function() {
console.log('-c 1 -n 10 okay'); 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'); 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'); console.log('-c 1 -n 1000 okay');
server.close(); server.close();
}); }));
}); }));
}); }));
}));
});
process.on('exit', function() {
assert.equal(3, runs);
});

22
test/parallel/test-http-head-request.js

@ -1,6 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
var body = 'hello world\n'; var body = 'hello world\n';
@ -13,27 +12,20 @@ function test(headers) {
server.close(); server.close();
}); });
var gotEnd = false; server.listen(0, common.mustCall(function() {
server.listen(0, function() {
var request = http.request({ var request = http.request({
port: this.address().port, port: this.address().port,
method: 'HEAD', method: 'HEAD',
path: '/' path: '/'
}, function(response) { }, common.mustCall(function(response) {
console.error('response start'); console.error('response start');
response.on('end', function() { response.on('end', common.mustCall(function() {
console.error('response end'); console.error('response end');
gotEnd = true; }));
});
response.resume(); response.resume();
}); }));
request.end(); request.end();
}); }));
process.on('exit', function() {
assert.ok(gotEnd);
});
} }
test({ test({

23
test/parallel/test-http-head-response-has-no-body-end.js

@ -1,7 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
// This test is to make sure that when the HTTP server // 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); server.listen(0);
var responseComplete = false; server.on('listening', common.mustCall(function() {
server.on('listening', function() {
var req = http.request({ var req = http.request({
port: this.address().port, port: this.address().port,
method: 'HEAD', method: 'HEAD',
path: '/' path: '/'
}, function(res) { }, common.mustCall(function(res) {
res.on('end', function() { res.on('end', common.mustCall(function() {
server.close(); server.close();
responseComplete = true; }));
});
res.resume(); res.resume();
}); }));
req.end(); req.end();
}); }));
process.on('exit', function() {
assert.ok(responseComplete);
});

23
test/parallel/test-http-head-response-has-no-body.js

@ -1,7 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
// This test is to make sure that when the HTTP server // 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); server.listen(0);
var responseComplete = false; server.on('listening', common.mustCall(function() {
server.on('listening', function() {
var req = http.request({ var req = http.request({
port: this.address().port, port: this.address().port,
method: 'HEAD', method: 'HEAD',
path: '/' path: '/'
}, function(res) { }, common.mustCall(function(res) {
res.on('end', function() { res.on('end', common.mustCall(function() {
server.close(); server.close();
responseComplete = true; }));
});
res.resume(); res.resume();
}); }));
req.end(); req.end();
}); }));
process.on('exit', function() {
assert.ok(responseComplete);
});

35
test/parallel/test-http-hex-write.js

@ -1,18 +1,10 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var expect = 'hex\nutf8\n'; 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) { http.createServer(function(q, s) {
s.setHeader('content-length', expect.length); s.setHeader('content-length', expect.length);
@ -20,14 +12,17 @@ http.createServer(function(q, s) {
s.write('utf8\n'); s.write('utf8\n');
s.end(); s.end();
this.close(); this.close();
}).listen(0, function() { }).listen(0, common.mustCall(function() {
http.request({ port: this.address().port }).on('response', function(res) { http.request({ port: this.address().port })
res.setEncoding('ascii'); .on('response', common.mustCall(function(res) {
res.on('data', function(c) { var data = '';
data += c;
}); res.setEncoding('ascii');
res.on('end', function() { res.on('data', function(c) {
ended = true; data += c;
}); });
}).end(); res.on('end', common.mustCall(function() {
}); assert.strictEqual(data, expect);
}));
})).end();
}));

24
test/parallel/test-http-legacy.js

@ -1,11 +1,10 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var url = require('url'); var url = require('url');
var responses_sent = 0; var responses_sent = 0;
var responses_recvd = 0;
var body0 = ''; var body0 = '';
var body1 = ''; var body1 = '';
@ -37,37 +36,32 @@ var server = http.createServer(function(req, res) {
req.resume(); req.resume();
}); });
server.listen(0, function() { server.listen(0, common.mustCall(function() {
var client = http.createClient(this.address().port); var client = http.createClient(this.address().port);
var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'}); var req = client.request('/hello', {'Accept': '*/*', 'Foo': 'bar'});
setTimeout(function() { setTimeout(function() {
req.end(); req.end();
}, 100); }, 100);
req.on('response', function(res) { req.on('response', common.mustCall(function(res) {
assert.equal(200, res.statusCode); assert.equal(200, res.statusCode);
responses_recvd += 1;
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function(chunk) { body0 += chunk; }); res.on('data', function(chunk) { body0 += chunk; });
console.error('Got /hello response'); console.error('Got /hello response');
}); }));
setTimeout(function() { setTimeout(common.mustCall(function() {
var req = client.request('POST', '/world'); var req = client.request('POST', '/world');
req.end(); req.end();
req.on('response', function(res) { req.on('response', common.mustCall(function(res) {
assert.equal(200, res.statusCode); assert.equal(200, res.statusCode);
responses_recvd += 1;
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function(chunk) { body1 += chunk; }); res.on('data', function(chunk) { body1 += chunk; });
console.error('Got /world response'); console.error('Got /world response');
}); }));
}, 1); }), 1);
}); }));
process.on('exit', function() { process.on('exit', function() {
console.error('responses_recvd: ' + responses_recvd);
assert.equal(2, responses_recvd);
console.error('responses_sent: ' + responses_sent); console.error('responses_sent: ' + responses_sent);
assert.equal(2, responses_sent); assert.equal(2, responses_sent);

15
test/parallel/test-http-localaddress-bind-error.js

@ -1,10 +1,8 @@
'use strict'; 'use strict';
const common = require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
var invalidLocalAddress = '1.2.3.4'; var invalidLocalAddress = '1.2.3.4';
var gotError = false;
var server = http.createServer(function(req, res) { var server = http.createServer(function(req, res) {
console.log('Connect from: ' + req.connection.remoteAddress); console.log('Connect from: ' + req.connection.remoteAddress);
@ -16,7 +14,7 @@ var server = http.createServer(function(req, res) {
req.resume(); req.resume();
}); });
server.listen(0, '127.0.0.1', function() { server.listen(0, '127.0.0.1', common.mustCall(function() {
http.request({ http.request({
host: 'localhost', host: 'localhost',
port: this.address().port, port: this.address().port,
@ -25,13 +23,8 @@ server.listen(0, '127.0.0.1', function() {
localAddress: invalidLocalAddress localAddress: invalidLocalAddress
}, function(res) { }, function(res) {
common.fail('unexpectedly got response from server'); common.fail('unexpectedly got response from server');
}).on('error', function(e) { }).on('error', common.mustCall(function(e) {
console.log('client got error: ' + e.message); console.log('client got error: ' + e.message);
gotError = true;
server.close(); server.close();
}).end(); })).end();
}); }));
process.on('exit', function() {
assert.ok(gotError);
});

20
test/parallel/test-http-multi-line-headers.js

@ -1,12 +1,10 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var net = require('net'); var net = require('net');
var gotResponse = false;
var server = net.createServer(function(conn) { var server = net.createServer(function(conn) {
var body = 'Yet another node.js server.'; var body = 'Yet another node.js server.';
@ -24,15 +22,13 @@ var server = net.createServer(function(conn) {
server.close(); server.close();
}); });
server.listen(0, function() { server.listen(0, common.mustCall(function() {
http.get({host: '127.0.0.1', port: this.address().port}, function(res) { http.get({
host: '127.0.0.1',
port: this.address().port
}, common.mustCall(function(res) {
assert.equal(res.headers['content-type'], assert.equal(res.headers['content-type'],
'text/plain; x-unix-mode=0600; name="hello.txt"'); 'text/plain; x-unix-mode=0600; name="hello.txt"');
gotResponse = true;
res.destroy(); res.destroy();
}); }));
}); }));
process.on('exit', function() {
assert.ok(gotResponse);
});

23
test/parallel/test-http-no-content-length.js

@ -1,26 +1,23 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var net = require('net'); var net = require('net');
var http = require('http'); var http = require('http');
var body = '';
var server = net.createServer(function(socket) { var server = net.createServer(function(socket) {
// Neither Content-Length nor Connection // Neither Content-Length nor Connection
socket.end('HTTP/1.1 200 ok\r\n\r\nHello'); socket.end('HTTP/1.1 200 ok\r\n\r\nHello');
}).listen(0, function() { }).listen(0, common.mustCall(function() {
http.get({port: this.address().port}, function(res) { http.get({port: this.address().port}, common.mustCall(function(res) {
var body = '';
res.setEncoding('utf8'); res.setEncoding('utf8');
res.on('data', function(chunk) { res.on('data', function(chunk) {
body += chunk; body += chunk;
}); });
res.on('end', function() { res.on('end', common.mustCall(function() {
assert.strictEqual(body, 'Hello');
server.close(); server.close();
}); }));
}); }));
}); }));
process.on('exit', function() {
assert.equal(body, 'Hello');
});

29
test/parallel/test-http-pause-resume-one-end.js

@ -1,6 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
var server = http.Server(function(req, res) { var server = http.Server(function(req, res) {
@ -9,32 +8,20 @@ var server = http.Server(function(req, res) {
server.close(); server.close();
}); });
server.listen(0, common.mustCall(function() {
var dataCount = 0, endCount = 0;
server.listen(0, function() {
var opts = { var opts = {
port: this.address().port, port: this.address().port,
headers: { connection: 'close' } headers: { connection: 'close' }
}; };
http.get(opts, function(res) { http.get(opts, common.mustCall(function(res) {
res.on('data', function(chunk) { res.on('data', common.mustCall(function(chunk) {
dataCount++;
res.pause(); res.pause();
setTimeout(function() { setTimeout(function() {
res.resume(); res.resume();
}); });
}); }));
res.on('end', function() {
endCount++;
});
});
});
process.on('exit', function() { res.on('end', common.mustCall(function() {}));
assert.equal(1, dataCount); }));
assert.equal(1, endCount); }));
});

11
test/parallel/test-http-pipe-fs.js

@ -1,6 +1,5 @@
'use strict'; 'use strict';
var common = require('../common'); var common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
var fs = require('fs'); var fs = require('fs');
var path = require('path'); var path = require('path');
@ -8,17 +7,15 @@ var path = require('path');
common.refreshTmpDir(); common.refreshTmpDir();
var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt'); var file = path.join(common.tmpDir, 'http-pipe-fs-test.txt');
var requests = 0;
var server = http.createServer(function(req, res) { var server = http.createServer(common.mustCall(function(req, res) {
++requests;
var stream = fs.createWriteStream(file); var stream = fs.createWriteStream(file);
req.pipe(stream); req.pipe(stream);
stream.on('close', function() { stream.on('close', function() {
res.writeHead(200); res.writeHead(200);
res.end(); res.end();
}); });
}).listen(0, function() { }, 2)).listen(0, function() {
http.globalAgent.maxSockets = 1; http.globalAgent.maxSockets = 1;
for (var i = 0; i < 2; ++i) { for (var i = 0; i < 2; ++i) {
@ -45,7 +42,3 @@ var server = http.createServer(function(req, res) {
}(i + 1)); }(i + 1));
} }
}); });
process.on('exit', function() {
assert.equal(requests, 2);
});

10
test/parallel/test-http-pipeline-flood.js

@ -1,6 +1,5 @@
'use strict'; 'use strict';
const common = require('../common'); const common = require('../common');
const assert = require('assert');
// Here we are testing the HTTP server module's flood prevention mechanism. // Here we are testing the HTTP server module's flood prevention mechanism.
// When writeable.write returns false (ie the underlying send() indicated the // When writeable.write returns false (ie the underlying send() indicated the
@ -27,7 +26,6 @@ switch (process.argv[2]) {
function parent() { function parent() {
const http = require('http'); const http = require('http');
const bigResponse = Buffer.alloc(10240, 'x'); const bigResponse = Buffer.alloc(10240, 'x');
var connections = 0;
var backloggedReqs = 0; var backloggedReqs = 0;
const server = http.createServer(function(req, res) { const server = http.createServer(function(req, res) {
@ -48,9 +46,7 @@ function parent() {
res.end(); res.end();
}); });
server.on('connection', function(conn) { server.on('connection', common.mustCall(function(conn) {}));
connections++;
});
server.listen(0, function() { server.listen(0, function() {
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
@ -64,10 +60,6 @@ function parent() {
child.kill(); child.kill();
})); }));
}); });
process.on('exit', function() {
assert.equal(connections, 1);
});
} }
function child() { function child() {

8
test/parallel/test-http-request-end.js

@ -4,15 +4,17 @@ var assert = require('assert');
var http = require('http'); var http = require('http');
var expected = 'Post Body For Test'; var expected = 'Post Body For Test';
var result = '';
var server = http.Server(function(req, res) { var server = http.Server(function(req, res) {
var result = '';
req.setEncoding('utf8'); req.setEncoding('utf8');
req.on('data', function(chunk) { req.on('data', function(chunk) {
result += chunk; result += chunk;
}); });
req.on('end', function() { req.on('end', function() {
assert.strictEqual(expected, result);
server.close(); server.close();
res.writeHead(200); res.writeHead(200);
res.end('hello world\n'); res.end('hello world\n');
@ -33,7 +35,3 @@ server.listen(0, function() {
process.exit(1); process.exit(1);
}).end(expected); }).end(expected);
}); });
process.on('exit', function() {
assert.equal(expected, result);
});

28
test/parallel/test-http-request-methods.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var net = require('net'); var net = require('net');
var http = require('http'); var http = require('http');
@ -7,20 +7,18 @@ var http = require('http');
// Test that the DELETE, PATCH and PURGE verbs get passed through correctly // Test that the DELETE, PATCH and PURGE verbs get passed through correctly
['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) { ['DELETE', 'PATCH', 'PURGE'].forEach(function(method, index) {
var server_response = ''; var server = http.createServer(common.mustCall(function(req, res) {
var received_method = null; assert.strictEqual(req.method, method);
var server = http.createServer(function(req, res) {
received_method = req.method;
res.writeHead(200, {'Content-Type': 'text/plain'}); res.writeHead(200, {'Content-Type': 'text/plain'});
res.write('hello '); res.write('hello ');
res.write('world\n'); res.write('world\n');
res.end(); res.end();
}); }));
server.listen(0); server.listen(0);
server.on('listening', function() { server.on('listening', common.mustCall(function() {
var c = net.createConnection(this.address().port); var c = net.createConnection(this.address().port);
var server_response = '';
c.setEncoding('utf8'); c.setEncoding('utf8');
@ -33,18 +31,14 @@ var http = require('http');
server_response += chunk; 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.end();
}); }));
c.on('close', function() { c.on('close', function() {
server.close(); 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);
});
}); });

19
test/parallel/test-http-res-write-after-end.js

@ -1,29 +1,22 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var responseError; var server = http.Server(common.mustCall(function(req, res) {
res.on('error', common.mustCall(function onResError(err) {
var server = http.Server(function(req, res) { assert.strictEqual(err.message, 'write after end');
res.on('error', function onResError(err) { }));
responseError = err;
});
res.write('This should write.'); res.write('This should write.');
res.end(); res.end();
var r = res.write('This should raise an error.'); var r = res.write('This should raise an error.');
assert.equal(r, true, 'write after end should return true'); assert.equal(r, true, 'write after end should return true');
}); }));
server.listen(0, function() { server.listen(0, function() {
http.get({port: this.address().port}, function(res) { http.get({port: this.address().port}, function(res) {
server.close(); server.close();
}); });
}); });
process.on('exit', function onProcessExit(code) {
assert(responseError, 'response should have emitted error');
assert.equal(responseError.message, 'write after end');
});

25
test/parallel/test-http-response-close.js

@ -1,24 +1,18 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert');
var http = require('http'); var http = require('http');
var requestGotEnd = false; var server = http.createServer(common.mustCall(function(req, res) {
var responseGotEnd = false;
var server = http.createServer(function(req, res) {
res.writeHead(200); res.writeHead(200);
res.write('a'); res.write('a');
req.on('close', function() { req.on('close', common.mustCall(function() {
console.error('request aborted'); console.error('request aborted');
requestGotEnd = true; }));
}); res.on('close', common.mustCall(function() {
res.on('close', function() {
console.error('response aborted'); console.error('response aborted');
responseGotEnd = true; }));
}); }));
});
server.listen(0); server.listen(0);
server.on('listening', function() { server.on('listening', function() {
@ -34,8 +28,3 @@ server.on('listening', function() {
}); });
}); });
}); });
process.on('exit', function() {
assert.ok(requestGotEnd);
assert.ok(responseGotEnd);
});

21
test/parallel/test-http-response-no-headers.js

@ -1,5 +1,5 @@
'use strict'; 'use strict';
require('../common'); const common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); var http = require('http');
var net = require('net'); var net = require('net');
@ -10,13 +10,7 @@ var expected = {
'1.1': '' '1.1': ''
}; };
var gotExpected = false;
function test(httpVersion, callback) { function test(httpVersion, callback) {
process.on('exit', function() {
assert(gotExpected);
});
var server = net.createServer(function(conn) { var server = net.createServer(function(conn) {
var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' + var reply = 'HTTP/' + httpVersion + ' 200 OK\r\n\r\n' +
expected[httpVersion]; expected[httpVersion];
@ -24,31 +18,30 @@ function test(httpVersion, callback) {
conn.end(reply); conn.end(reply);
}); });
server.listen(0, '127.0.0.1', function() { server.listen(0, '127.0.0.1', common.mustCall(function() {
var options = { var options = {
host: '127.0.0.1', host: '127.0.0.1',
port: this.address().port port: this.address().port
}; };
var req = http.get(options, function(res) { var req = http.get(options, common.mustCall(function(res) {
var body = ''; var body = '';
res.on('data', function(data) { res.on('data', function(data) {
body += data; body += data;
}); });
res.on('end', function() { res.on('end', common.mustCall(function() {
assert.equal(body, expected[httpVersion]); assert.equal(body, expected[httpVersion]);
gotExpected = true;
server.close(); server.close();
if (callback) process.nextTick(callback); if (callback) process.nextTick(callback);
}); }));
}); }));
req.on('error', function(err) { req.on('error', function(err) {
throw err; throw err;
}); });
}); }));
} }
test('0.9', function() { test('0.9', function() {

26
test/parallel/test-http-unix-socket.js

@ -3,10 +3,6 @@ var common = require('../common');
var assert = require('assert'); var assert = require('assert');
var http = require('http'); 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) { var server = http.createServer(function(req, res) {
res.writeHead(200, { res.writeHead(200, {
'Content-Type': 'text/plain', 'Content-Type': 'text/plain',
@ -19,19 +15,16 @@ var server = http.createServer(function(req, res) {
common.refreshTmpDir(); common.refreshTmpDir();
server.listen(common.PIPE, function() { server.listen(common.PIPE, common.mustCall(function() {
var options = { var options = {
socketPath: common.PIPE, socketPath: common.PIPE,
path: '/' path: '/'
}; };
var req = http.get(options, function(res) { var req = http.get(options, common.mustCall(function(res) {
assert.equal(res.statusCode, 200); assert.equal(res.statusCode, 200);
status_ok = true;
assert.equal(res.headers['content-type'], 'text/plain'); assert.equal(res.headers['content-type'], 'text/plain');
headers_ok = true;
res.body = ''; res.body = '';
res.setEncoding('utf8'); res.setEncoding('utf8');
@ -40,17 +33,16 @@ server.listen(common.PIPE, function() {
res.body += chunk; res.body += chunk;
}); });
res.on('end', function() { res.on('end', common.mustCall(function() {
assert.equal(res.body, 'hello world\n'); assert.equal(res.body, 'hello world\n');
body_ok = true;
server.close(function(error) { server.close(function(error) {
assert.equal(error, undefined); assert.equal(error, undefined);
server.close(function(error) { server.close(function(error) {
assert.equal(error && error.message, 'Not running'); assert.equal(error && error.message, 'Not running');
}); });
}); });
}); }));
}); }));
req.on('error', function(e) { req.on('error', function(e) {
console.log(e.stack); console.log(e.stack);
@ -59,10 +51,4 @@ server.listen(common.PIPE, function() {
req.end(); req.end();
}); }));
process.on('exit', function() {
assert.ok(status_ok);
assert.ok(headers_ok);
assert.ok(body_ok);
});

Some files were not shown because too many files changed in this diff

Loading…
Cancel
Save