test: refactoring / cleanup on child-process tests

PR-URL: https://github.com/nodejs/node/pull/32078
Reviewed-By: Gireesh Punathil <gpunathi@in.ibm.com>
This commit is contained in:
James M Snell 2020-03-23 13:06:24 -07:00
parent c78d3f2256
commit d0c0e20bc2
17 changed files with 309 additions and 261 deletions

View File

@ -1,7 +1,8 @@
const assert = require('assert'); const assert = require('assert');
const debug = require('util').debuglog('test');
function onmessage(m) { function onmessage(m) {
console.log('CHILD got message:', m); debug('CHILD got message:', m);
assert.ok(m.hello); assert.ok(m.hello);
process.removeListener('message', onmessage); process.removeListener('message', onmessage);
} }

View File

@ -2,14 +2,15 @@
require('../common'); require('../common');
const assert = require('assert'); const assert = require('assert');
const child_process = require('child_process'); const child_process = require('child_process');
const { inspect } = require('util'); const { debuglog, inspect } = require('util');
const debug = debuglog('test');
const p = child_process.spawnSync( const p = child_process.spawnSync(
process.execPath, [ '--completion-bash' ]); process.execPath, [ '--completion-bash' ]);
assert.ifError(p.error); assert.ifError(p.error);
const output = p.stdout.toString().trim().replace(/\r/g, ''); const output = p.stdout.toString().trim().replace(/\r/g, '');
console.log(output); debug(output);
const prefix = `_node_complete() { const prefix = `_node_complete() {
local cur_word options local cur_word options

View File

@ -20,15 +20,16 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const { isWindows } = require('../common');
const assert = require('assert'); const assert = require('assert');
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
const debug = require('util').debuglog('test');
process.env.HELLO = 'WORLD'; process.env.HELLO = 'WORLD';
let child; let child;
if (common.isWindows) { if (isWindows) {
child = spawn('cmd.exe', ['/c', 'set'], {}); child = spawn('cmd.exe', ['/c', 'set'], {});
} else { } else {
child = spawn('/usr/bin/env', [], {}); child = spawn('/usr/bin/env', [], {});
@ -39,7 +40,7 @@ let response = '';
child.stdout.setEncoding('utf8'); child.stdout.setEncoding('utf8');
child.stdout.on('data', function(chunk) { child.stdout.on('data', function(chunk) {
console.log(`stdout: ${chunk}`); debug(`stdout: ${chunk}`);
response += chunk; response += chunk;
}); });

View File

@ -20,17 +20,22 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const {
isWindows,
mustCall,
mustCallAtLeast,
} = require('../common');
const assert = require('assert'); const assert = require('assert');
const os = require('os'); const os = require('os');
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
const debug = require('util').debuglog('test');
// We're trying to reproduce: // We're trying to reproduce:
// $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/ // $ echo "hello\nnode\nand\nworld" | grep o | sed s/o/a/
let grep, sed, echo; let grep, sed, echo;
if (common.isWindows) { if (isWindows) {
grep = spawn('grep', ['--binary', 'o']); grep = spawn('grep', ['--binary', 'o']);
sed = spawn('sed', ['--binary', 's/o/O/']); sed = spawn('sed', ['--binary', 's/o/O/']);
echo = spawn('cmd.exe', echo = spawn('cmd.exe',
@ -54,62 +59,66 @@ if (common.isWindows) {
// pipe echo | grep // pipe echo | grep
echo.stdout.on('data', function(data) { echo.stdout.on('data', mustCallAtLeast((data) => {
console.error(`grep stdin write ${data.length}`); debug(`grep stdin write ${data.length}`);
if (!grep.stdin.write(data)) { if (!grep.stdin.write(data)) {
echo.stdout.pause(); echo.stdout.pause();
} }
}); }));
grep.stdin.on('drain', function(data) { // TODO(@jasnell): This does not appear to ever be
// emitted. It's not clear if it is necessary.
grep.stdin.on('drain', (data) => {
echo.stdout.resume(); echo.stdout.resume();
}); });
// Propagate end from echo to grep // Propagate end from echo to grep
echo.stdout.on('end', function(code) { echo.stdout.on('end', mustCall((code) => {
grep.stdin.end(); grep.stdin.end();
}); }));
echo.on('exit', function() { echo.on('exit', mustCall(() => {
console.error('echo exit'); debug('echo exit');
}); }));
grep.on('exit', function() { grep.on('exit', mustCall(() => {
console.error('grep exit'); debug('grep exit');
}); }));
sed.on('exit', function() { sed.on('exit', mustCall(() => {
console.error('sed exit'); debug('sed exit');
}); }));
// pipe grep | sed // pipe grep | sed
grep.stdout.on('data', function(data) { grep.stdout.on('data', mustCallAtLeast((data) => {
console.error(`grep stdout ${data.length}`); debug(`grep stdout ${data.length}`);
if (!sed.stdin.write(data)) { if (!sed.stdin.write(data)) {
grep.stdout.pause(); grep.stdout.pause();
} }
}); }));
sed.stdin.on('drain', function(data) { // TODO(@jasnell): This does not appear to ever be
// emitted. It's not clear if it is necessary.
sed.stdin.on('drain', (data) => {
grep.stdout.resume(); grep.stdout.resume();
}); });
// Propagate end from grep to sed // Propagate end from grep to sed
grep.stdout.on('end', function(code) { grep.stdout.on('end', mustCall((code) => {
console.error('grep stdout end'); debug('grep stdout end');
sed.stdin.end(); sed.stdin.end();
}); }));
let result = ''; let result = '';
// print sed's output // print sed's output
sed.stdout.on('data', function(data) { sed.stdout.on('data', mustCallAtLeast((data) => {
result += data.toString('utf8', 0, data.length); result += data.toString('utf8', 0, data.length);
console.log(data); debug(data);
}); }));
sed.stdout.on('end', function(code) { sed.stdout.on('end', mustCall((code) => {
assert.strictEqual(result, `hellO${os.EOL}nOde${os.EOL}wOrld${os.EOL}`); assert.strictEqual(result, `hellO${os.EOL}nOde${os.EOL}wOrld${os.EOL}`);
}); }));

View File

@ -20,9 +20,14 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const {
isWindows,
mustCall,
mustCallAtLeast,
} = require('../common');
const assert = require('assert'); const assert = require('assert');
const os = require('os'); const os = require('os');
const debug = require('util').debuglog('test');
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
@ -38,7 +43,7 @@ Object.setPrototypeOf(env, {
}); });
let child; let child;
if (common.isWindows) { if (isWindows) {
child = spawn('cmd.exe', ['/c', 'set'], { env }); child = spawn('cmd.exe', ['/c', 'set'], { env });
} else { } else {
child = spawn('/usr/bin/env', [], { env }); child = spawn('/usr/bin/env', [], { env });
@ -49,15 +54,15 @@ let response = '';
child.stdout.setEncoding('utf8'); child.stdout.setEncoding('utf8');
child.stdout.on('data', (chunk) => { child.stdout.on('data', mustCallAtLeast((chunk) => {
console.log(`stdout: ${chunk}`); debug(`stdout: ${chunk}`);
response += chunk; response += chunk;
}); }));
process.on('exit', () => { child.stdout.on('end', mustCall(() => {
assert.ok(response.includes('HELLO=WORLD')); assert.ok(response.includes('HELLO=WORLD'));
assert.ok(response.includes('FOO=BAR')); assert.ok(response.includes('FOO=BAR'));
assert.ok(!response.includes('UNDEFINED=undefined')); assert.ok(!response.includes('UNDEFINED=undefined'));
assert.ok(response.includes('NULL=null')); assert.ok(response.includes('NULL=null'));
assert.ok(response.includes(`EMPTY=${os.EOL}`)); assert.ok(response.includes(`EMPTY=${os.EOL}`));
}); }));

View File

@ -20,9 +20,11 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const { isWindows } = require('../common');
const assert = require('assert'); const assert = require('assert');
const exec = require('child_process').exec; const exec = require('child_process').exec;
const debug = require('util').debuglog('test');
let success_count = 0; let success_count = 0;
let error_count = 0; let error_count = 0;
let response = ''; let response = '';
@ -31,9 +33,9 @@ let child;
function after(err, stdout, stderr) { function after(err, stdout, stderr) {
if (err) { if (err) {
error_count++; error_count++;
console.log(`error!: ${err.code}`); debug(`error!: ${err.code}`);
console.log(`stdout: ${JSON.stringify(stdout)}`); debug(`stdout: ${JSON.stringify(stdout)}`);
console.log(`stderr: ${JSON.stringify(stderr)}`); debug(`stderr: ${JSON.stringify(stderr)}`);
assert.strictEqual(err.killed, false); assert.strictEqual(err.killed, false);
} else { } else {
success_count++; success_count++;
@ -41,7 +43,7 @@ function after(err, stdout, stderr) {
} }
} }
if (!common.isWindows) { if (!isWindows) {
child = exec('/usr/bin/env', { env: { 'HELLO': 'WORLD' } }, after); child = exec('/usr/bin/env', { env: { 'HELLO': 'WORLD' } }, after);
} else { } else {
child = exec('set', child = exec('set',
@ -55,7 +57,7 @@ child.stdout.on('data', function(chunk) {
}); });
process.on('exit', function() { process.on('exit', function() {
console.log('response: ', response); debug('response: ', response);
assert.strictEqual(success_count, 1); assert.strictEqual(success_count, 1);
assert.strictEqual(error_count, 0); assert.strictEqual(error_count, 0);
assert.ok(response.includes('HELLO=WORLD')); assert.ok(response.includes('HELLO=WORLD'));

View File

@ -20,7 +20,7 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const fork = require('child_process').fork; const fork = require('child_process').fork;
const net = require('net'); const net = require('net');
@ -29,7 +29,7 @@ const count = 12;
if (process.argv[2] === 'child') { if (process.argv[2] === 'child') {
const sockets = []; const sockets = [];
process.on('message', function(m, socket) { process.on('message', common.mustCall((m, socket) => {
function sendClosed(id) { function sendClosed(id) {
process.send({ id: id, status: 'closed' }); process.send({ id: id, status: 'closed' });
} }
@ -52,41 +52,39 @@ if (process.argv[2] === 'child') {
sockets[m.id].destroy(); sockets[m.id].destroy();
} }
} }
}); }));
} else { } else {
const child = fork(process.argv[1], ['child']); const child = fork(process.argv[1], ['child']);
child.on('exit', function(code, signal) { child.on('exit', common.mustCall((code, signal) => {
if (!subprocessKilled) { if (!subprocessKilled) {
assert.fail('subprocess died unexpectedly! ' + assert.fail('subprocess died unexpectedly! ' +
`code: ${code} signal: ${signal}`); `code: ${code} signal: ${signal}`);
} }
}); }));
const server = net.createServer(); const server = net.createServer();
const sockets = []; const sockets = [];
let sent = 0;
server.on('connection', function(socket) { server.on('connection', common.mustCall((socket) => {
child.send({ cmd: 'new' }, socket); child.send({ cmd: 'new' }, socket);
sockets.push(socket); sockets.push(socket);
if (sockets.length === count) { if (sockets.length === count) {
closeSockets(0); closeSockets(0);
} }
}); }, count));
let disconnected = 0; const onClose = common.mustCall(count);
server.on('listening', function() {
server.on('listening', common.mustCall(() => {
let j = count; let j = count;
while (j--) { while (j--) {
const client = net.connect(server.address().port, '127.0.0.1'); const client = net.connect(server.address().port, '127.0.0.1');
client.on('close', function() { client.on('close', onClose);
disconnected += 1;
});
} }
}); }));
let subprocessKilled = false; let subprocessKilled = false;
function closeSockets(i) { function closeSockets(i) {
@ -97,29 +95,18 @@ if (process.argv[2] === 'child') {
return; return;
} }
child.once('message', function(m) { child.once('message', common.mustCall((m) => {
assert.strictEqual(m.status, 'closed'); assert.strictEqual(m.status, 'closed');
server.getConnections(function(err, num) { server.getConnections(common.mustCall((err, num) => {
assert.ifError(err); assert.ifError(err);
assert.strictEqual(num, count - (i + 1)); assert.strictEqual(num, count - (i + 1));
closeSockets(i + 1); closeSockets(i + 1);
}); }));
}); }));
sent++;
child.send({ id: i, cmd: 'close' }); child.send({ id: i, cmd: 'close' });
} }
let closeEmitted = false; server.on('close', common.mustCall());
server.on('close', function() {
closeEmitted = true;
});
server.listen(0, '127.0.0.1'); server.listen(0, '127.0.0.1');
process.on('exit', function() {
assert.strictEqual(sent, count);
assert.strictEqual(disconnected, count);
assert.ok(closeEmitted);
console.log('ok');
});
} }

View File

@ -24,56 +24,60 @@ const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const fork = require('child_process').fork; const fork = require('child_process').fork;
const net = require('net'); const net = require('net');
const debug = require('util').debuglog('test');
function ProgressTracker(missing, callback) { const Countdown = require('../common/countdown');
this.missing = missing;
this.callback = callback;
}
ProgressTracker.prototype.done = function() {
this.missing -= 1;
this.check();
};
ProgressTracker.prototype.check = function() {
if (this.missing === 0) this.callback();
};
if (process.argv[2] === 'child') { if (process.argv[2] === 'child') {
let serverScope; let serverScope;
process.on('message', function onServer(msg, server) { // TODO(@jasnell): The message event is not called consistently
// across platforms. Need to investigate if it can be made
// more consistent.
const onServer = (msg, server) => {
if (msg.what !== 'server') return; if (msg.what !== 'server') return;
process.removeListener('message', onServer); process.removeListener('message', onServer);
serverScope = server; serverScope = server;
server.on('connection', function(socket) { // TODO(@jasnell): This is apparently not called consistently
console.log('CHILD: got connection'); // across platforms. Need to investigate if it can be made
// more consistent.
server.on('connection', (socket) => {
debug('CHILD: got connection');
process.send({ what: 'connection' }); process.send({ what: 'connection' });
socket.destroy(); socket.destroy();
}); });
// Start making connection from parent. // Start making connection from parent.
console.log('CHILD: server listening'); debug('CHILD: server listening');
process.send({ what: 'listening' }); process.send({ what: 'listening' });
}); };
process.on('message', function onClose(msg) { process.on('message', onServer);
// TODO(@jasnell): The close event is not called consistently
// across platforms. Need to investigate if it can be made
// more consistent.
const onClose = (msg) => {
if (msg.what !== 'close') return; if (msg.what !== 'close') return;
process.removeListener('message', onClose); process.removeListener('message', onClose);
serverScope.on('close', function() { serverScope.on('close', common.mustCall(() => {
process.send({ what: 'close' }); process.send({ what: 'close' });
}); }));
serverScope.close(); serverScope.close();
}); };
process.on('message', onClose);
process.send({ what: 'ready' }); process.send({ what: 'ready' });
} else { } else {
const child = fork(process.argv[1], ['child']); const child = fork(process.argv[1], ['child']);
child.on('exit', common.mustCall(function(code, signal) { child.on('exit', common.mustCall((code, signal) => {
const message = `CHILD: died with ${code}, ${signal}`; const message = `CHILD: died with ${code}, ${signal}`;
assert.strictEqual(code, 0, message); assert.strictEqual(code, 0, message);
})); }));
@ -82,64 +86,74 @@ if (process.argv[2] === 'child') {
function testServer(callback) { function testServer(callback) {
// Destroy server execute callback when done. // Destroy server execute callback when done.
const progress = new ProgressTracker(2, function() { const countdown = new Countdown(2, () => {
server.on('close', function() { server.on('close', common.mustCall(() => {
console.log('PARENT: server closed'); debug('PARENT: server closed');
child.send({ what: 'close' }); child.send({ what: 'close' });
}); }));
server.close(); server.close();
}); });
// We expect 4 connections and close events. // We expect 4 connections and close events.
const connections = new ProgressTracker(4, progress.done.bind(progress)); const connections = new Countdown(4, () => countdown.dec());
const closed = new ProgressTracker(4, progress.done.bind(progress)); const closed = new Countdown(4, () => countdown.dec());
// Create server and send it to child. // Create server and send it to child.
const server = net.createServer(); const server = net.createServer();
server.on('connection', function(socket) {
console.log('PARENT: got connection'); // TODO(@jasnell): The specific number of times the connection
// event is emitted appears to be variable across platforms.
// Need to investigate why and whether it can be made
// more consistent.
server.on('connection', (socket) => {
debug('PARENT: got connection');
socket.destroy(); socket.destroy();
connections.done(); connections.dec();
}); });
server.on('listening', function() {
console.log('PARENT: server listening'); server.on('listening', common.mustCall(() => {
debug('PARENT: server listening');
child.send({ what: 'server' }, server); child.send({ what: 'server' }, server);
}); }));
server.listen(0); server.listen(0);
// Handle client messages. // Handle client messages.
function messageHandlers(msg) { // TODO(@jasnell): The specific number of times the message
// event is emitted appears to be variable across platforms.
// Need to investigate why and whether it can be made
// more consistent.
const messageHandlers = (msg) => {
if (msg.what === 'listening') { if (msg.what === 'listening') {
// Make connections. // Make connections.
let socket; let socket;
for (let i = 0; i < 4; i++) { for (let i = 0; i < 4; i++) {
socket = net.connect(server.address().port, function() { socket = net.connect(server.address().port, common.mustCall(() => {
console.log('CLIENT: connected'); debug('CLIENT: connected');
}); }));
socket.on('close', function() { socket.on('close', common.mustCall(() => {
closed.done(); closed.dec();
console.log('CLIENT: closed'); debug('CLIENT: closed');
}); }));
} }
} else if (msg.what === 'connection') { } else if (msg.what === 'connection') {
// Child got connection // Child got connection
connections.done(); connections.dec();
} else if (msg.what === 'close') { } else if (msg.what === 'close') {
child.removeListener('message', messageHandlers); child.removeListener('message', messageHandlers);
callback(); callback();
} }
} };
child.on('message', messageHandlers); child.on('message', messageHandlers);
} }
// Create server and send it to child. const onReady = common.mustCall((msg) => {
child.on('message', function onReady(msg) {
if (msg.what !== 'ready') return; if (msg.what !== 'ready') return;
child.removeListener('message', onReady); child.removeListener('message', onReady);
testServer(common.mustCall()); testServer(common.mustCall());
}); });
// Create server and send it to child.
child.on('message', onReady);
} }

View File

@ -20,68 +20,77 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const {
mustCall,
mustCallAtLeast,
} = require('../common');
const assert = require('assert'); const assert = require('assert');
const fork = require('child_process').fork; const fork = require('child_process').fork;
const net = require('net'); const net = require('net');
const debug = require('util').debuglog('test');
if (process.argv[2] === 'child') { if (process.argv[2] === 'child') {
process.on('message', function onSocket(msg, socket) { const onSocket = mustCall((msg, socket) => {
if (msg.what !== 'socket') return; if (msg.what !== 'socket') return;
process.removeListener('message', onSocket); process.removeListener('message', onSocket);
socket.end('echo'); socket.end('echo');
console.log('CHILD: got socket'); debug('CHILD: got socket');
}); });
process.on('message', onSocket);
process.send({ what: 'ready' }); process.send({ what: 'ready' });
} else { } else {
const child = fork(process.argv[1], ['child']); const child = fork(process.argv[1], ['child']);
child.on('exit', common.mustCall(function(code, signal) { child.on('exit', mustCall((code, signal) => {
const message = `CHILD: died with ${code}, ${signal}`; const message = `CHILD: died with ${code}, ${signal}`;
assert.strictEqual(code, 0, message); assert.strictEqual(code, 0, message);
})); }));
// Send net.Socket to child. // Send net.Socket to child.
function testSocket(callback) { function testSocket() {
// Create a new server and connect to it, // Create a new server and connect to it,
// but the socket will be handled by the child. // but the socket will be handled by the child.
const server = net.createServer(); const server = net.createServer();
server.on('connection', function(socket) { server.on('connection', mustCall((socket) => {
socket.on('close', function() { // TODO(@jasnell): Close does not seem to actually be called.
console.log('CLIENT: socket closed'); // It is not clear if it is needed.
socket.on('close', () => {
debug('CLIENT: socket closed');
}); });
child.send({ what: 'socket' }, socket); child.send({ what: 'socket' }, socket);
}); }));
server.on('close', function() { server.on('close', mustCall(() => {
console.log('PARENT: server closed'); debug('PARENT: server closed');
callback(); }));
});
server.listen(0, function() { server.listen(0, mustCall(() => {
console.log('testSocket, listening'); debug('testSocket, listening');
const connect = net.connect(server.address().port); const connect = net.connect(server.address().port);
let store = ''; let store = '';
connect.on('data', function(chunk) { connect.on('data', mustCallAtLeast((chunk) => {
store += chunk; store += chunk;
console.log('CLIENT: got data'); debug('CLIENT: got data');
}); }));
connect.on('close', function() { connect.on('close', mustCall(() => {
console.log('CLIENT: closed'); debug('CLIENT: closed');
assert.strictEqual(store, 'echo'); assert.strictEqual(store, 'echo');
server.close(); server.close();
}); }));
}); }));
} }
// Create socket and send it to child. const onReady = mustCall((msg) => {
child.on('message', function onReady(msg) {
if (msg.what !== 'ready') return; if (msg.what !== 'ready') return;
child.removeListener('message', onReady); child.removeListener('message', onReady);
testSocket(common.mustCall()); testSocket();
}); });
// Create socket and send it to child.
child.on('message', onReady);
} }

View File

@ -20,64 +20,69 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const {
mustCall,
mustCallAtLeast,
platformTimeout,
} = require('../common');
const assert = require('assert'); const assert = require('assert');
const fork = require('child_process').fork; const fork = require('child_process').fork;
const net = require('net'); const net = require('net');
const debug = require('util').debuglog('test');
const count = 12; const count = 12;
if (process.argv[2] === 'child') { if (process.argv[2] === 'child') {
const needEnd = []; const needEnd = [];
const id = process.argv[3]; const id = process.argv[3];
process.on('message', function(m, socket) { process.on('message', mustCall((m, socket) => {
if (!socket) return; if (!socket) return;
console.error(`[${id}] got socket ${m}`); debug(`[${id}] got socket ${m}`);
// Will call .end('end') or .write('write'); // Will call .end('end') or .write('write');
socket[m](m); socket[m](m);
socket.resume(); socket.resume();
socket.on('data', function() { socket.on('data', mustCallAtLeast(() => {
console.error(`[${id}] socket.data ${m}`); debug(`[${id}] socket.data ${m}`);
}); }));
socket.on('end', function() { socket.on('end', mustCall(() => {
console.error(`[${id}] socket.end ${m}`); debug(`[${id}] socket.end ${m}`);
}); }));
// Store the unfinished socket // Store the unfinished socket
if (m === 'write') { if (m === 'write') {
needEnd.push(socket); needEnd.push(socket);
} }
socket.on('close', function(had_error) { socket.on('close', mustCall((had_error) => {
console.error(`[${id}] socket.close ${had_error} ${m}`); debug(`[${id}] socket.close ${had_error} ${m}`);
}); }));
socket.on('finish', function() { socket.on('finish', mustCall(() => {
console.error(`[${id}] socket finished ${m}`); debug(`[${id}] socket finished ${m}`);
}); }));
}); }));
process.on('message', function(m) { process.on('message', mustCall((m) => {
if (m !== 'close') return; if (m !== 'close') return;
console.error(`[${id}] got close message`); debug(`[${id}] got close message`);
needEnd.forEach(function(endMe, i) { needEnd.forEach((endMe, i) => {
console.error(`[${id}] ending ${i}/${needEnd.length}`); debug(`[${id}] ending ${i}/${needEnd.length}`);
endMe.end('end'); endMe.end('end');
}); });
}); }));
process.on('disconnect', function() { process.on('disconnect', mustCall(() => {
console.error(`[${id}] process disconnect, ending`); debug(`[${id}] process disconnect, ending`);
needEnd.forEach(function(endMe, i) { needEnd.forEach((endMe, i) => {
console.error(`[${id}] ending ${i}/${needEnd.length}`); debug(`[${id}] ending ${i}/${needEnd.length}`);
endMe.end('end'); endMe.end('end');
}); });
}); }));
} else { } else {
@ -106,8 +111,10 @@ if (process.argv[2] === 'child') {
} }
connected += 1; connected += 1;
socket.once('close', function() { // TODO(@jasnell): This is not actually being called.
console.log(`[m] socket closed, total ${++closed}`); // It is not clear if it is needed.
socket.once('close', () => {
debug(`[m] socket closed, total ${++closed}`);
}); });
if (connected === count) { if (connected === count) {
@ -116,26 +123,27 @@ if (process.argv[2] === 'child') {
}); });
let disconnected = 0; let disconnected = 0;
server.on('listening', function() { server.on('listening', mustCall(() => {
let j = count; let j = count;
while (j--) { while (j--) {
const client = net.connect(this.address().port, '127.0.0.1'); const client = net.connect(server.address().port, '127.0.0.1');
client.on('error', function() { client.on('error', () => {
// This can happen if we kill the subprocess too early. // This can happen if we kill the subprocess too early.
// The client should still get a close event afterwards. // The client should still get a close event afterwards.
console.error('[m] CLIENT: error event'); // It likely won't so don't wrap in a mustCall.
debug('[m] CLIENT: error event');
}); });
client.on('close', function() { client.on('close', mustCall(() => {
console.error('[m] CLIENT: close event'); debug('[m] CLIENT: close event');
disconnected += 1; disconnected += 1;
}); }));
client.resume(); client.resume();
} }
}); }));
let closeEmitted = false; let closeEmitted = false;
server.on('close', common.mustCall(function() { server.on('close', mustCall(function() {
closeEmitted = true; closeEmitted = true;
child1.kill(); child1.kill();
@ -148,12 +156,12 @@ if (process.argv[2] === 'child') {
function closeServer() { function closeServer() {
server.close(); server.close();
setTimeout(function() { setTimeout(() => {
assert(!closeEmitted); assert(!closeEmitted);
child1.send('close'); child1.send('close');
child2.send('close'); child2.send('close');
child3.disconnect(); child3.disconnect();
}, 200); }, platformTimeout(200));
} }
process.on('exit', function() { process.on('exit', function() {

View File

@ -20,26 +20,31 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const {
mustCall,
mustNotCall,
platformTimeout,
} = require('../common');
const fork = require('child_process').fork; const fork = require('child_process').fork;
const debug = require('util').debuglog('test');
if (process.argv[2] === 'child') { if (process.argv[2] === 'child') {
console.log('child -> call disconnect'); debug('child -> call disconnect');
process.disconnect(); process.disconnect();
setTimeout(function() { setTimeout(() => {
console.log('child -> will this keep it alive?'); debug('child -> will this keep it alive?');
process.on('message', common.mustNotCall()); process.on('message', mustNotCall());
}, 400); }, platformTimeout(400));
} else { } else {
const child = fork(__filename, ['child']); const child = fork(__filename, ['child']);
child.on('disconnect', function() { child.on('disconnect', mustCall(() => {
console.log('parent -> disconnect'); debug('parent -> disconnect');
}); }));
child.once('exit', function() { child.once('exit', mustCall(() => {
console.log('parent -> exit'); debug('parent -> exit');
}); }));
} }

View File

@ -18,13 +18,14 @@
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
// Flags: --no-warnings
'use strict'; 'use strict';
const common = require('../common'); const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const fork = require('child_process').fork; const { fork } = require('child_process');
const args = ['foo', 'bar']; const args = ['foo', 'bar'];
const fixtures = require('../common/fixtures'); const fixtures = require('../common/fixtures');
const debug = require('util').debuglog('test');
const n = fork(fixtures.path('child-process-spawn-node.js'), args); const n = fork(fixtures.path('child-process-spawn-node.js'), args);
@ -32,7 +33,7 @@ assert.strictEqual(n.channel, n._channel);
assert.deepStrictEqual(args, ['foo', 'bar']); assert.deepStrictEqual(args, ['foo', 'bar']);
n.on('message', (m) => { n.on('message', (m) => {
console.log('PARENT got message:', m); debug('PARENT got message:', m);
assert.ok(m.foo); assert.ok(m.foo);
}); });

View File

@ -21,47 +21,43 @@
'use strict'; 'use strict';
require('../common'); const {
mustCall,
mustNotCall,
} = require('../common');
const assert = require('assert'); const assert = require('assert');
const debug = require('util').debuglog('test');
const { spawn } = require('child_process'); const { spawn } = require('child_process');
const fixtures = require('../common/fixtures'); const fixtures = require('../common/fixtures');
const sub = fixtures.path('echo.js'); const sub = fixtures.path('echo.js');
let gotHelloWorld = false;
let gotEcho = false;
const child = spawn(process.argv[0], [sub]); const child = spawn(process.argv[0], [sub]);
child.stderr.on('data', function(data) { child.stderr.on('data', mustNotCall());
console.log(`parent stderr: ${data}`);
});
child.stdout.setEncoding('utf8'); child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) { const messages = [
console.log(`child said: ${JSON.stringify(data)}`); 'hello world\r\n',
if (!gotHelloWorld) { 'echo me\r\n',
console.error('testing for hello world'); ];
assert.strictEqual(data, 'hello world\r\n');
gotHelloWorld = true; child.stdout.on('data', mustCall((data) => {
console.error('writing echo me'); debug(`child said: ${JSON.stringify(data)}`);
child.stdin.write('echo me\r\n'); const test = messages.shift();
debug(`testing for '${test}'`);
assert.strictEqual(data, test);
if (messages.length) {
debug(`writing '${messages[0]}'`);
child.stdin.write(messages[0]);
} else { } else {
console.error('testing for echo me'); assert.strictEqual(messages.length, 0);
assert.strictEqual(data, 'echo me\r\n');
gotEcho = true;
child.stdin.end(); child.stdin.end();
} }
}); }, messages.length));
child.stdout.on('end', function(data) { child.stdout.on('end', mustCall((data) => {
console.log('child end'); debug('child end');
}); }));
process.on('exit', function() {
assert.ok(gotHelloWorld);
assert.ok(gotEcho);
});

View File

@ -24,15 +24,16 @@ const common = require('../common');
const assert = require('assert'); const assert = require('assert');
const spawnSync = require('child_process').spawnSync; const spawnSync = require('child_process').spawnSync;
const { getSystemErrorName } = require('util'); const { debuglog, getSystemErrorName } = require('util');
const debug = debuglog('test');
const TIMER = 200; const TIMER = 200;
const SLEEP = common.platformTimeout(5000); const SLEEP = common.platformTimeout(5000);
switch (process.argv[2]) { switch (process.argv[2]) {
case 'child': case 'child':
setTimeout(function() { setTimeout(() => {
console.log('child fired'); debug('child fired');
process.exit(1); process.exit(1);
}, SLEEP); }, SLEEP);
break; break;

View File

@ -20,9 +20,13 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const {
mustCall,
mustCallAtLeast,
mustNotCall,
} = require('../common');
const assert = require('assert'); const assert = require('assert');
const debug = require('util').debuglog('test');
const spawn = require('child_process').spawn; const spawn = require('child_process').spawn;
const cat = spawn('cat'); const cat = spawn('cat');
@ -38,21 +42,21 @@ cat.stdin.end();
let response = ''; let response = '';
cat.stdout.setEncoding('utf8'); cat.stdout.setEncoding('utf8');
cat.stdout.on('data', function(chunk) { cat.stdout.on('data', mustCallAtLeast((chunk) => {
console.log(`stdout: ${chunk}`); debug(`stdout: ${chunk}`);
response += chunk; response += chunk;
}); }));
cat.stdout.on('end', common.mustCall()); cat.stdout.on('end', mustCall());
cat.stderr.on('data', common.mustNotCall()); cat.stderr.on('data', mustNotCall());
cat.stderr.on('end', common.mustCall()); cat.stderr.on('end', mustCall());
cat.on('exit', common.mustCall(function(status) { cat.on('exit', mustCall((status) => {
assert.strictEqual(status, 0); assert.strictEqual(status, 0);
})); }));
cat.on('close', common.mustCall(function() { cat.on('close', mustCall(() => {
assert.strictEqual(response, 'hello world'); assert.strictEqual(response, 'hello world');
})); }));

View File

@ -20,8 +20,13 @@
// USE OR OTHER DEALINGS IN THE SOFTWARE. // USE OR OTHER DEALINGS IN THE SOFTWARE.
'use strict'; 'use strict';
const common = require('../common'); const {
mustCall,
mustCallAtLeast,
} = require('../common');
const assert = require('assert'); const assert = require('assert');
const debug = require('util').debuglog('test');
let bufsize = 0; let bufsize = 0;
switch (process.argv[2]) { switch (process.argv[2]) {
@ -40,12 +45,12 @@ function parent() {
let n = ''; let n = '';
child.stdout.setEncoding('ascii'); child.stdout.setEncoding('ascii');
child.stdout.on('data', function(c) { child.stdout.on('data', mustCallAtLeast((c) => {
n += c; n += c;
}); }));
child.stdout.on('end', common.mustCall(function() { child.stdout.on('end', mustCall(() => {
assert.strictEqual(+n, sent); assert.strictEqual(+n, sent);
console.log('ok'); debug('ok');
})); }));
// Write until the buffer fills up. // Write until the buffer fills up.
@ -71,10 +76,11 @@ function parent() {
function child() { function child() {
let received = 0; let received = 0;
process.stdin.on('data', function(c) { process.stdin.on('data', mustCallAtLeast((c) => {
received += c.length; received += c.length;
}); }));
process.stdin.on('end', function() { process.stdin.on('end', mustCall(() => {
// This console.log is part of the test.
console.log(received); console.log(received);
}); }));
} }

View File

@ -24,6 +24,7 @@ const common = require('../common');
const assert = require('assert'); const assert = require('assert');
// If child process output to console and exit // If child process output to console and exit
// The console.log statements here are part of the test.
if (process.argv[2] === 'child') { if (process.argv[2] === 'child') {
console.log('hello'); console.log('hello');
for (let i = 0; i < 200; i++) { for (let i = 0; i < 200; i++) {
@ -40,18 +41,15 @@ if (process.argv[2] === 'child') {
let stdout = ''; let stdout = '';
child.stderr.setEncoding('utf8'); child.stderr.on('data', common.mustNotCall());
child.stderr.on('data', function(data) {
assert.fail(`Unexpected parent stderr: ${data}`);
});
// Check if we receive both 'hello' at start and 'goodbye' at end // Check if we receive both 'hello' at start and 'goodbye' at end
child.stdout.setEncoding('utf8'); child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) { child.stdout.on('data', common.mustCallAtLeast((data) => {
stdout += data; stdout += data;
}); }));
child.on('close', common.mustCall(function() { child.on('close', common.mustCall(() => {
assert.strictEqual(stdout.slice(0, 6), 'hello\n'); assert.strictEqual(stdout.slice(0, 6), 'hello\n');
assert.strictEqual(stdout.slice(stdout.length - 8), 'goodbye\n'); assert.strictEqual(stdout.slice(stdout.length - 8), 'goodbye\n');
})); }));