1'use strict';
2// Flags: --expose-internals
3const common = require('../common');
4const assert = require('assert');
5const cp = require('child_process');
6
7if (process.argv[2] === 'child') {
8  setTimeout(() => {}, common.platformTimeout(100));
9  return;
10}
11
12// Monkey patch spawn() to create a child process normally, but destroy the
13// stdout and stderr streams. This replicates the conditions where the streams
14// cannot be properly created.
15const ChildProcess = require('internal/child_process').ChildProcess;
16const original = ChildProcess.prototype.spawn;
17
18ChildProcess.prototype.spawn = function() {
19  const err = original.apply(this, arguments);
20
21  this.stdout.destroy();
22  this.stderr.destroy();
23  this.stdout = null;
24  this.stderr = null;
25
26  return err;
27};
28
29function createChild(options, callback) {
30  const cmd = `"${process.execPath}" "${__filename}" child`;
31
32  return cp.exec(cmd, options, common.mustCall(callback));
33}
34
35// Verify that normal execution of a child process is handled.
36{
37  createChild({}, (err, stdout, stderr) => {
38    assert.strictEqual(err, null);
39    assert.strictEqual(stdout, '');
40    assert.strictEqual(stderr, '');
41  });
42}
43
44// Verify that execution with an error event is handled.
45{
46  const error = new Error('foo');
47  const child = createChild({}, (err, stdout, stderr) => {
48    assert.strictEqual(err, error);
49    assert.strictEqual(stdout, '');
50    assert.strictEqual(stderr, '');
51  });
52
53  child.emit('error', error);
54}
55
56// Verify that execution with a killed process is handled.
57{
58  createChild({ timeout: 1 }, (err, stdout, stderr) => {
59    assert.strictEqual(err.killed, true);
60    assert.strictEqual(stdout, '');
61    assert.strictEqual(stderr, '');
62  });
63}
64