Skip to content
Myr

Add `.node()` method (#200)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Guillaume Martigny · committed by Sindre Sorhus · parent be1d70f · Browse files · 53 files+1161 added−965 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

53 files+1161 added−965 removed

  • tests:+1041 added−34 removed
  • other:+120 added−931 removed

53 files+1161 added−965 removed

deleted:fixtures/command with space-3 removed
1#!/usr/bin/env node2'use strict';3console.log(process.argv.slice(2).join('\n'));
deleted:fixtures/delay-4 removed
1#!/usr/bin/env node2'use strict';34setTimeout(() => {}, Number(process.argv[2]));
deleted:fixtures/detach-8 removed
1#!/usr/bin/env node2'use strict';34const execa = require('..');56const subprocess = execa('node', ['./fixtures/forever'], {detached: true});7console.log(subprocess.pid);8process.exit();
deleted:fixtures/echo-3 removed
1#!/usr/bin/env node2'use strict';3console.log(process.argv.slice(2).join('\n'))
deleted:fixtures/environment-4 removed
1#!/usr/bin/env node2'use strict';3console.log(process.env.FOO);4console.log(process.env.BAR);
deleted:fixtures/exit-3 removed
1#!/usr/bin/env node2'use strict';3process.exit(Number(process.argv[2]));
deleted:fixtures/fail-4 removed
1#!/usr/bin/env node2'use strict';34process.exit(2);
deleted:fixtures/fast-exit-darwinbinary

A binary file, deleted.

deleted:fixtures/fast-exit-linuxbinary

A binary file, deleted.

deleted:fixtures/forever-4 removed
1#!/usr/bin/env node2'use strict';34setTimeout(() => {}, 1e8);
deleted:fixtures/hello.cmd-1 removed
1ECHO Hello World
deleted:fixtures/max-buffer-6 removed
1#!/usr/bin/env node2'use strict';3const output = process.argv[2];4const bytes = Number(process.argv[3]);56process[output].write('.'.repeat(bytes - 1) + '\n');
deleted:fixtures/no-killable-12 removed
1#!/usr/bin/env node2'use strict';34process.on('SIGTERM', () => {5 console.log('Received SIGTERM, but we ignore it');6});78process.send('');910setInterval(() => {11 // Run forever12}, 20000);
deleted:fixtures/non-executable-2 removed
1#!/usr/bin/env node2'use strict';
deleted:fixtures/noop-3 removed
1#!/usr/bin/env node2'use strict';3console.log(process.argv[2]);
deleted:fixtures/noop-132-9 removed
1#!/usr/bin/env node2'use strict';34process.stdout.write('1');5process.stderr.write('3');67setTimeout(() => {8 process.stdout.write('2');9}, 1000);
deleted:fixtures/noop-err-3 removed
1#!/usr/bin/env node2'use strict';3console.error(process.argv[2]);
deleted:fixtures/noop-throw-4 removed
1#!/usr/bin/env node2'use strict';3console.error(process.argv[2]);4process.exit(2);
deleted:fixtures/stdin-3 removed
1#!/usr/bin/env node2'use strict';3process.stdin.pipe(process.stdout);
deleted:fixtures/sub-process-8 removed
1#!/usr/bin/env node2'use strict';3const execa = require('..');45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7const subprocess = execa('node', ['./fixtures/forever'], {cleanup, detached});8process.send(subprocess.pid);
deleted:fixtures/sub-process-exit-7 removed
1#!/usr/bin/env node2'use strict';3const execa = require('..');45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7execa('node', ['./fixtures/noop'], {cleanup, detached});
modified:lib/stdio.js+21 added-1 removed
1 unmodified line
2const alias = ['stdin', 'stdout', 'stderr'];34const hasAlias = opts => alias.some(x => Boolean(opts[x]));56module.exports = opts => {6const stdio = opts => {7 if (!opts) {8 return;9 }10
27 unmodified lines
38 }3940 return result;41};4243module.exports = stdio;4445module.exports.node = opts => {46 const defaultOption = 'pipe';4748 let stdioOption = stdio(opts || {stdio: defaultOption});4950 if (typeof stdioOption === 'string') {51 stdioOption = [...new Array(3)].fill(stdioOption);52 } else if (Array.isArray(stdioOption)) {53 stdioOption = stdioOption.map((channel = defaultOption) => channel);54 }5556 if (!stdioOption.includes('ipc')) {57 stdioOption.push('ipc');58 }5960 return stdioOption;61};
added:test/fixtures/command with space+3 added
1#!/usr/bin/env node2'use strict';3console.log(process.argv.slice(2).join('\n'));
added:test/fixtures/delay+4 added
1#!/usr/bin/env node2'use strict';34setTimeout(() => {}, Number(process.argv[2]));
added:test/fixtures/detach+8 added
1#!/usr/bin/env node2'use strict';34const execa = require('../..');56const subprocess = execa('node', ['./test/fixtures/forever'], {detached: true});7console.log(subprocess.pid);8process.exit();
added:test/fixtures/echo+3 added
1#!/usr/bin/env node2'use strict';3console.log(process.argv.slice(2).join('\n'));
added:test/fixtures/environment+4 added
1#!/usr/bin/env node2'use strict';3console.log(process.env.FOO);4console.log(process.env.BAR);
added:test/fixtures/exit+3 added
1#!/usr/bin/env node2'use strict';3process.exit(Number(process.argv[2]));
added:test/fixtures/fail+4 added
1#!/usr/bin/env node2'use strict';34process.exit(2);
added:test/fixtures/fast-exit-darwinbinary

A binary file, added.

added:test/fixtures/fast-exit-linuxbinary

A binary file, added.

added:test/fixtures/forever+4 added
1#!/usr/bin/env node2'use strict';34setTimeout(() => {}, 1e8);
added:test/fixtures/hello.cmd+1 added
1ECHO Hello World
added:test/fixtures/hello.sh+1 added
1echo Hello World
added:test/fixtures/max-buffer+6 added
1#!/usr/bin/env node2'use strict';3const output = process.argv[2];4const bytes = Number(process.argv[3]);56process[output].write('.'.repeat(bytes - 1) + '\n');
added:test/fixtures/no-killable+12 added
1#!/usr/bin/env node2'use strict';34process.on('SIGTERM', () => {5 console.log('Received SIGTERM, but we ignore it');6});78process.send('');910setInterval(() => {11 // Run forever12}, 20000);
added:test/fixtures/non-executable+2 added
1#!/usr/bin/env node2'use strict';
added:test/fixtures/noop+3 added
1#!/usr/bin/env node2'use strict';3console.log(process.argv[2]);
added:test/fixtures/noop-132+9 added
1#!/usr/bin/env node2'use strict';34process.stdout.write('1');5process.stderr.write('3');67setTimeout(() => {8 process.stdout.write('2');9}, 1000);
added:test/fixtures/noop-err+3 added
1#!/usr/bin/env node2'use strict';3console.error(process.argv[2]);
added:test/fixtures/noop-throw+4 added
1#!/usr/bin/env node2'use strict';3console.error(process.argv[2]);4process.exit(2);
added:test/fixtures/send+9 added
1#!/usr/bin/env node2'use strict';3process.on('message', message => {4 if (message === 'ping') {5 process.send('pong');6 } else {7 throw new Error('Receive wrong message');8 }9});
added:test/fixtures/stdin+3 added
1#!/usr/bin/env node2'use strict';3process.stdin.pipe(process.stdout);
added:test/fixtures/sub-process+8 added
1#!/usr/bin/env node2'use strict';3const execa = require('../..');45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7const subprocess = execa('node', ['./test/fixtures/forever'], {cleanup, detached});8process.send(subprocess.pid);
added:test/fixtures/sub-process-exit+7 added
1#!/usr/bin/env node2'use strict';3const execa = require('../..');45const cleanup = process.argv[2] === 'true';6const detached = process.argv[3] === 'true';7execa('node', ['./test/fixtures/noop'], {cleanup, detached});
added:test/node.js+46 added
1import test from 'ava';2import pEvent from 'p-event';3import path from 'path';4import execa from '..';56process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;78test('node()', async t => {9 const {exitCode} = await execa.node('test/fixtures/noop');10 t.is(exitCode, 0);11});1213test('node pipe stdout', async t => {14 const {stdout} = await execa.node('test/fixtures/noop', ['foo'], {15 stdout: 'pipe'16 });1718 t.is(stdout, 'foo');19});2021test('node correctly use nodePath', async t => {22 const {stdout} = await execa.node(process.platform === 'win32' ? 'hello.cmd' : 'hello.sh', {23 stdout: 'pipe',24 nodePath: process.platform === 'win32' ? 'cmd.exe' : 'bash',25 nodeArguments: process.platform === 'win32' ? ['/c'] : []26 });2728 t.is(stdout, 'Hello World');29});3031test('node pass on nodeArguments', async t => {32 const {stdout} = await execa.node('console.log("foo")', {33 stdout: 'pipe',34 nodeArguments: ['-e']35 });3637 t.is(stdout, 'foo');38});3940test('node\'s forked script has a communication channel', async t => {41 const subprocess = execa.node('test/fixtures/send');42 subprocess.send('ping');4344 const message = await pEvent(subprocess, 'message');45 t.is(message, 'pong');46});
modified:test/stdio.js+57 added-34 removed
2 unmodified lines
3import stdio from '../lib/stdio';45util.inspect.styles.name = 'magenta';67function macro(t, input, expected) {8 if (expected instanceof Error) {9 t.throws(() => stdio(input), expected.message);10 return;11 }7function createMacro(func) {8 const macro = (t, input, expected) => {9 if (expected instanceof Error) {10 t.throws(() => {11 stdio(input);12 }, expected.message);13 return;14 }1513 const result = stdio(input);16 const result = func(input);1715 if (typeof expected === 'object' && expected !== null) {16 t.deepEqual(result, expected);17 } else {18 t.is(result, expected);19 }18 if (typeof expected === 'object' && expected !== null) {19 t.deepEqual(result, expected);20 } else {21 t.is(result, expected);22 }23 };2425 macro.title = (providedTitle, input) => `${func.name} ${(providedTitle || util.inspect(input, {colors: true}))}`;2627 return macro;28}2922macro.title = (providedTitle, input) => providedTitle || util.inspect(input, {colors: true});30const stdioMacro = createMacro(stdio);3124test(macro, undefined, undefined);32test(stdioMacro, undefined, undefined);33test(stdioMacro, null, undefined);3426test(macro, {stdio: 'inherit'}, 'inherit');27test(macro, {stdio: 'pipe'}, 'pipe');28test(macro, {stdio: 'ignore'}, 'ignore');29test(macro, {stdio: [0, 1, 2]}, [0, 1, 2]);35test(stdioMacro, {stdio: 'inherit'}, 'inherit');36test(stdioMacro, {stdio: 'pipe'}, 'pipe');37test(stdioMacro, {stdio: 'ignore'}, 'ignore');38test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);3931test(macro, {}, [undefined, undefined, undefined]);32test(macro, {stdio: []}, [undefined, undefined, undefined]);33test(macro, {stdin: 'pipe'}, ['pipe', undefined, undefined]);34test(macro, {stdout: 'ignore'}, [undefined, 'ignore', undefined]);35test(macro, {stderr: 'inherit'}, [undefined, undefined, 'inherit']);36test(macro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);37test(macro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', undefined]);38test(macro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', undefined, 'inherit']);39test(macro, {stdout: 'ignore', stderr: 'inherit'}, [undefined, 'ignore', 'inherit']);40test(macro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);41test(macro, {stdin: 0, stdout: 1}, [0, 1, undefined]);42test(macro, {stdin: 0, stderr: 2}, [0, undefined, 2]);43test(macro, {stdout: 1, stderr: 2}, [undefined, 1, 2]);40test(stdioMacro, {}, [undefined, undefined, undefined]);41test(stdioMacro, {stdio: []}, [undefined, undefined, undefined]);42test(stdioMacro, {stdin: 'pipe'}, ['pipe', undefined, undefined]);43test(stdioMacro, {stdout: 'ignore'}, [undefined, 'ignore', undefined]);44test(stdioMacro, {stderr: 'inherit'}, [undefined, undefined, 'inherit']);45test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);46test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', undefined]);47test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', undefined, 'inherit']);48test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, [undefined, 'ignore', 'inherit']);49test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);50test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, undefined]);51test(stdioMacro, {stdin: 0, stderr: 2}, [0, undefined, 2]);52test(stdioMacro, {stdout: 1, stderr: 2}, [undefined, 1, 2]);5345test(macro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));54test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));5547test(macro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));48test(macro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));49test(macro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));56test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));57test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));58test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));5960const forkMacro = createMacro(stdio.node);6162test(forkMacro, undefined, ['pipe', 'pipe', 'pipe', 'ipc']);63test(forkMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore', 'ipc']);64test(forkMacro, {stdio: [0, 1, 2]}, [0, 1, 2, 'ipc']);65test(forkMacro, {stdio: [0, 1, 2, 3]}, [0, 1, 2, 3, 'ipc']);66test(forkMacro, {stdio: [0, 1, 2, 'ipc']}, [0, 1, 2, 'ipc']);6768test(forkMacro, {stdout: 'ignore'}, ['pipe', 'ignore', 'pipe', 'ipc']);69test(forkMacro, {stdout: 'ignore', stderr: 'ignore'}, ['pipe', 'ignore', 'ignore', 'ipc']);7071test(forkMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));72test(forkMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));
added:test/test.js+837 added
1import path from 'path';2import fs from 'fs';3import stream from 'stream';4import childProcess from 'child_process';5import test from 'ava';6import getStream from 'get-stream';7import isRunning from 'is-running';8import tempfile from 'tempfile';9import pEvent from 'p-event';10import execa from '..';1112process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;13process.env.FOO = 'foo';1415const TIMEOUT_REGEXP = /timed out after/;1617const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);1819test('execa()', async t => {20 const {stdout} = await execa('noop', ['foo']);21 t.is(stdout, 'foo');22});2324if (process.platform === 'win32') {25 test('execa() - cmd file', async t => {26 const {stdout} = await execa('hello.cmd');27 t.is(stdout, 'Hello World');28 });2930 test('execa() - run cmd command', async t => {31 const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);32 t.is(stdout, 'Hello World');33 });34}3536test('buffer', async t => {37 const {stdout} = await execa('noop', ['foo'], {encoding: null});38 t.true(Buffer.isBuffer(stdout));39 t.is(stdout.toString(), 'foo');40});4142test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {43 const {all} = await execa('noop-132');44 t.is(all, '132');45});4647test('stdout/stderr/all available on errors', async t => {48 const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});49 t.is(typeof stdout, 'string');50 t.is(typeof stderr, 'string');51 t.is(typeof all, 'string');52});5354test('stdout/stderr/all are undefined if ignored', async t => {55 const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore'});56 t.is(stdout, undefined);57 t.is(stderr, undefined);58 t.is(all, undefined);59});6061test('stdout/stderr/all are undefined if ignored in sync mode', t => {62 const {stdout, stderr, all} = execa.sync('noop', {stdio: 'ignore'});63 t.is(stdout, undefined);64 t.is(stderr, undefined);65 t.is(all, undefined);66});6768const WRONG_COMMAND = process.platform === 'win32' ?69 '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :70 '';7172test('stdout/stderr/all on process errors', async t => {73 const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command'));74 t.is(stdout, '');75 t.is(stderr, WRONG_COMMAND);76 t.is(all, WRONG_COMMAND);77});7879test('stdout/stderr/all on process errors, in sync mode', t => {80 const {stdout, stderr, all} = t.throws(() => {81 execa.sync('wrong command');82 });83 t.is(stdout, '');84 t.is(stderr, WRONG_COMMAND);85 t.is(all, undefined);86});8788test('pass `stdout` to a file descriptor', async t => {89 const file = tempfile('.txt');90 await execa('test/fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});91 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');92});9394test('pass `stderr` to a file descriptor', async t => {95 const file = tempfile('.txt');96 await execa('test/fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});97 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');98});99100test('execa.sync()', t => {101 const {stdout} = execa.sync('noop', ['foo']);102 t.is(stdout, 'foo');103});104105test('execa.sync() throws error if written to stderr', t => {106 t.throws(() => {107 execa.sync('foo');108 }, process.platform === 'win32' ? /failed with exit code 1/ : /spawnSync foo ENOENT/);109});110111test('skip throwing when using reject option', async t => {112 const {exitCode} = await execa('fail', {reject: false});113 t.is(exitCode, 2);114});115116test('skip throwing when using reject option in sync mode', t => {117 const {exitCode} = execa.sync('fail', {reject: false});118 t.is(exitCode, 2);119});120121test('kill("SIGKILL") should terminate cleanly', async t => {122 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});123 await pEvent(subprocess, 'message');124125 subprocess.kill('SIGKILL');126127 const {signal} = await t.throwsAsync(subprocess);128 t.is(signal, 'SIGKILL');129});130131// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).132// Therefore, this feature and those tests do not make sense on Windows.133if (process.platform !== 'win32') {134 test('`forceKillAfterTimeout: false` should not kill after a timeout', async t => {135 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});136 await pEvent(subprocess, 'message');137138 subprocess.kill('SIGTERM', {forceKillAfterTimeout: false});139140 t.true(isRunning(subprocess.pid));141 subprocess.kill('SIGKILL');142 });143144 test('`forceKillAfterTimeout: number` should kill after a timeout', async t => {145 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});146 await pEvent(subprocess, 'message');147148 subprocess.kill('SIGTERM', {forceKillAfterTimeout: 50});149150 const {signal} = await t.throwsAsync(subprocess);151 t.is(signal, 'SIGKILL');152 });153154 test('`forceKillAfterTimeout: true` should kill after a timeout', async t => {155 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});156 await pEvent(subprocess, 'message');157158 subprocess.kill('SIGTERM', {forceKillAfterTimeout: true});159160 const {signal} = await t.throwsAsync(subprocess);161 t.is(signal, 'SIGKILL');162 });163164 test('kill() with no arguments should kill after a timeout', async t => {165 const subprocess = execa('node', ['./test/fixtures/no-killable'], {stdio: ['ipc']});166 await pEvent(subprocess, 'message');167168 subprocess.kill();169170 const {signal} = await t.throwsAsync(subprocess);171 t.is(signal, 'SIGKILL');172 });173174 test('`forceKillAfterTimeout` should not be a float', t => {175 t.throws(() => {176 execa('noop').kill('SIGTERM', {forceKillAfterTimeout: 0.5});177 }, {instanceOf: TypeError, message: /non-negative integer/});178 });179180 test('`forceKillAfterTimeout` should not be negative', t => {181 t.throws(() => {182 execa('noop').kill('SIGTERM', {forceKillAfterTimeout: -1});183 }, {instanceOf: TypeError, message: /non-negative integer/});184 });185}186187test('stripFinalNewline: true', async t => {188 const {stdout} = await execa('noop', ['foo']);189 t.is(stdout, 'foo');190});191192test('stripFinalNewline: false', async t => {193 const {stdout} = await execa('noop', ['foo'], {stripFinalNewline: false});194 t.is(stdout, 'foo\n');195});196197test('stripFinalNewline on failure', async t => {198 const {stderr} = await t.throwsAsync(execa('noop-throw', ['foo'], {stripFinalNewline: true}));199 t.is(stderr, 'foo');200});201202test('stripFinalNewline in sync mode', t => {203 const {stdout} = execa.sync('noop', ['foo'], {stripFinalNewline: true});204 t.is(stdout, 'foo');205});206207test('stripFinalNewline in sync mode on failure', t => {208 const {stderr} = t.throws(() => {209 execa.sync('noop-throw', ['foo'], {stripFinalNewline: true});210 });211 t.is(stderr, 'foo');212});213214test('preferLocal option', async t => {215 await execa('ava', ['--version'], {env: {PATH: ''}});216 const errorRegExp = process.platform === 'win32' ? /failed with exit code 1/ : /spawn ava ENOENT/;217 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: {PATH: ''}}), errorRegExp);218});219220test('localDir option', async t => {221 const command = process.platform === 'win32' ? 'echo %PATH%' : 'echo $PATH';222 const {stdout} = await execa(command, {shell: true, localDir: '/test'});223 const envPaths = stdout.split(path.delimiter).map(envPath =>224 envPath.replace(/\\/g, '/').replace(/^[^/]+/, '')225 );226 t.true(envPaths.some(envPath => envPath === '/test/node_modules/.bin'));227});228229test('input option can be a String', async t => {230 const {stdout} = await execa('stdin', {input: 'foobar'});231 t.is(stdout, 'foobar');232});233234test('input option can be a Buffer', async t => {235 const {stdout} = await execa('stdin', {input: 'testing12'});236 t.is(stdout, 'testing12');237});238239test('input can be a Stream', async t => {240 const s = new stream.PassThrough();241 s.write('howdy');242 s.end();243 const {stdout} = await execa('stdin', {input: s});244 t.is(stdout, 'howdy');245});246247test('you can write to child.stdin', async t => {248 const child = execa('stdin');249 child.stdin.end('unicorns');250 t.is((await child).stdout, 'unicorns');251});252253test('input option can be a String - sync', t => {254 const {stdout} = execa.sync('stdin', {input: 'foobar'});255 t.is(stdout, 'foobar');256});257258test('input option can be a Buffer - sync', t => {259 const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});260 t.is(stdout, 'testing12');261});262263test('stdin errors are handled', async t => {264 const child = execa('noop');265 child.stdin.emit('error', new Error('test'));266 await t.throwsAsync(child, /test/);267});268269test('child process errors are handled', async t => {270 const child = execa('noop');271 child.emit('error', new Error('test'));272 await t.throwsAsync(child, /test/);273});274275test('opts.stdout:ignore - stdout will not collect data', async t => {276 const {stdout} = await execa('stdin', {277 input: 'hello',278 stdio: [undefined, 'ignore', undefined]279 });280 t.is(stdout, undefined);281});282283test('helpful error trying to provide an input stream in sync mode', t => {284 t.throws(285 () => {286 execa.sync('stdin', {input: new stream.PassThrough()});287 },288 /The `input` option cannot be a stream in sync mode/289 );290});291292test('child process errors rejects promise right away', async t => {293 const child = execa('forever');294 child.emit('error', new Error('test'));295 await t.throwsAsync(child, /test/);296});297298test('execa() returns a promise with kill() and pid', t => {299 const {kill, pid} = execa('noop', ['foo']);300 t.is(typeof kill, 'function');301 t.is(typeof pid, 'number');302});303304test('child_process.spawn() propagated errors have correct shape', t => {305 const cp = execa('noop', {uid: -1});306 t.notThrows(() => {307 cp.catch(() => {});308 cp.unref();309 cp.on('error', () => {});310 });311});312313test('child_process.spawn() errors are propagated', async t => {314 const {failed} = await t.throwsAsync(execa('noop', {uid: -1}));315 t.true(failed);316});317318test('child_process.spawnSync() errors are propagated with a correct shape', t => {319 const {failed} = t.throws(() => {320 execa.sync('noop', {timeout: -1});321 });322 t.true(failed);323});324325test('maxBuffer affects stdout', async t => {326 await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));327 const {stdout, all} = await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /max-buffer stdout/);328 t.is(stdout, '.'.repeat(10));329 t.is(all, '.'.repeat(10));330});331332test('maxBuffer affects stderr', async t => {333 await t.notThrowsAsync(execa('max-buffer', ['stderr', '10'], {maxBuffer: 10}));334 const {stderr, all} = await t.throwsAsync(execa('max-buffer', ['stderr', '11'], {maxBuffer: 10}), /max-buffer stderr/);335 t.is(stderr, '.'.repeat(10));336 t.is(all, '.'.repeat(10));337});338339test('do not buffer stdout when `buffer` set to `false`', async t => {340 const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});341 const [result, stdout] = await Promise.all([342 promise,343 getStream(promise.stdout),344 getStream(promise.all)345 ]);346347 t.is(result.stdout, undefined);348 t.is(stdout, '.........\n');349});350351test('do not buffer stderr when `buffer` set to `false`', async t => {352 const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});353 const [result, stderr] = await Promise.all([354 promise,355 getStream(promise.stderr),356 getStream(promise.all)357 ]);358359 t.is(result.stderr, undefined);360 t.is(stderr, '.........\n');361});362363test('allow unknown exit code', async t => {364 const {exitCode, exitCodeName} = await t.throwsAsync(execa('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});365 t.is(exitCode, 255);366 t.is(exitCodeName, 'Unknown system error -255');367});368369test('execa() does not return code and failed properties on success', async t => {370 const {exitCode, exitCodeName, failed} = await execa('noop', ['foo']);371 t.is(exitCode, 0);372 t.is(exitCodeName, 'SUCCESS');373 t.false(failed);374});375376test('execa() returns code and failed properties', async t => {377 const {exitCode, exitCodeName, failed} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});378 t.is(exitCode, 2);379 const expectedName = process.platform === 'win32' ? 'Unknown system error -2' : 'ENOENT';380 t.is(exitCodeName, expectedName);381 t.true(failed);382});383384test('use relative path with \'..\' chars', async t => {385 const pathViaParentDir = path.join('..', path.basename(path.dirname(__dirname)), 'test', 'fixtures', 'noop');386 const {stdout} = await execa(pathViaParentDir, ['foo']);387 t.is(stdout, 'foo');388});389390if (process.platform !== 'win32') {391 test('execa() rejects if running non-executable', async t => {392 const cp = execa('non-executable');393 await t.throwsAsync(cp);394 });395396 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {397 await t.throwsAsync(execa('non-executable', {input: 'Hey!'}), /EACCES/);398 });399}400401test('error.killed is true if process was killed directly', async t => {402 const cp = execa('forever');403404 cp.kill();405406 const {killed} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});407 t.true(killed);408});409410test('error.killed is false if process was killed indirectly', async t => {411 const cp = execa('forever');412413 process.kill(cp.pid, 'SIGINT');414415 // `process.kill()` is emulated by Node.js on Windows416 const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;417 const {killed} = await t.throwsAsync(cp, {message});418 t.false(killed);419});420421test('result.killed is false if not killed', async t => {422 const {killed} = await execa('noop');423 t.false(killed);424});425426test('result.killed is false if not killed, in sync mode', t => {427 const {killed} = execa.sync('noop');428 t.false(killed);429});430431test('result.killed is false on process error', async t => {432 const {killed} = await t.throwsAsync(execa('wrong command'));433 t.false(killed);434});435436test('result.killed is false on process error, in sync mode', t => {437 const {killed} = t.throws(() => {438 execa.sync('wrong command');439 });440 t.false(killed);441});442443if (process.platform === 'darwin') {444 test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {445 const {pid} = childProcess.exec('forever', error => {446 t.truthy(error);447 t.false(error.killed);448 t.end();449 });450451 process.kill(pid, 'SIGINT');452 });453}454455if (process.platform !== 'win32') {456 test('error.signal is SIGINT', async t => {457 const cp = execa('forever');458459 process.kill(cp.pid, 'SIGINT');460461 const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGINT/});462 t.is(signal, 'SIGINT');463 });464465 test('error.signal is SIGTERM', async t => {466 const cp = execa('forever');467468 process.kill(cp.pid, 'SIGTERM');469470 const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});471 t.is(signal, 'SIGTERM');472 });473474 test('custom error.signal', async t => {475 const {signal} = await t.throwsAsync(execa('forever', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));476 t.is(signal, 'SIGHUP');477 });478}479480test('result.signal is undefined for successful execution', async t => {481 const {signal} = await execa('noop');482 t.is(signal, undefined);483});484485test('result.signal is undefined if process failed, but was not killed', async t => {486 const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});487 t.is(signal, undefined);488});489490async function testExitCode(t, num) {491 const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});492 t.is(exitCode, num);493}494495test('error.exitCode is 2', testExitCode, 2);496test('error.exitCode is 3', testExitCode, 3);497test('error.exitCode is 4', testExitCode, 4);498499test('timeout kills the process if it times out', async t => {500 const {killed, timedOut} = await t.throwsAsync(execa('forever', {timeout: 1, message: TIMEOUT_REGEXP}));501 t.false(killed);502 t.true(timedOut);503});504505test('timeout kills the process if it times out, in sync mode', async t => {506 const {killed, timedOut} = await t.throws(() => {507 execa.sync('forever', {timeout: 1, message: TIMEOUT_REGEXP});508 });509 t.false(killed);510 t.true(timedOut);511});512513test('timeout does not kill the process if it does not time out', async t => {514 const {timedOut} = await execa('delay', ['500'], {timeout: 1e8});515 t.false(timedOut);516});517518test('timedOut is false if no timeout was set', async t => {519 const {timedOut} = await execa('noop');520 t.false(timedOut);521});522523test('timedOut will be false if no timeout was set and zero exit code in sync mode', t => {524 const {timedOut} = execa.sync('noop');525 t.false(timedOut);526});527528async function errorMessage(t, expected, ...args) {529 await t.throwsAsync(execa('exit', args), {message: expected});530}531532errorMessage.title = (message, expected) => `error.message matches: ${expected}`;533534test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');535test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');536537async function command(t, expected, ...args) {538 const {command: failCommand} = await t.throwsAsync(execa('fail', args));539 t.is(failCommand, `fail${expected}`);540541 const {command} = await execa('noop', args);542 t.is(command, `noop${expected}`);543}544545command.title = (message, expected) => `command is: ${JSON.stringify(expected)}`;546547test(command, ' foo bar', 'foo', 'bar');548test(command, ' baz quz', 'baz', 'quz');549test(command, '');550551// When child process exits before parent process552async function spawnAndExit(t, cleanup, detached) {553 await t.notThrowsAsync(execa('sub-process-exit', [cleanup, detached]));554}555556test('spawnAndExit', spawnAndExit, false, false);557test('spawnAndExit cleanup', spawnAndExit, true, false);558test('spawnAndExit detached', spawnAndExit, false, true);559test('spawnAndExit cleanup detached', spawnAndExit, true, true);560561// When parent process exits before child process562async function spawnAndKill(t, signal, cleanup, detached, isKilled) {563 const subprocess = execa('sub-process', [cleanup, detached], {stdio: ['ignore', 'ignore', 'ignore', 'ipc']});564565 const pid = await pEvent(subprocess, 'message');566 t.true(Number.isInteger(pid));567 t.true(isRunning(pid));568569 process.kill(subprocess.pid, signal);570571 await t.throwsAsync(subprocess);572573 t.false(isRunning(subprocess.pid));574 t.is(isRunning(pid), !isKilled);575576 if (!isKilled) {577 process.kill(pid, 'SIGKILL');578 }579}580581// Without `options.cleanup`:582// - on Windows subprocesses are killed if `options.detached: false`, but not583// if `options.detached: true`584// - on Linux subprocesses are never killed regardless of `options.detached`585// With `options.cleanup`, subprocesses are always killed586// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled587const exitIfWindows = process.platform === 'win32';588test('spawnAndKill SIGTERM', spawnAndKill, 'SIGTERM', false, false, exitIfWindows);589test('spawnAndKill SIGKILL', spawnAndKill, 'SIGKILL', false, false, exitIfWindows);590test('spawnAndKill cleanup SIGTERM', spawnAndKill, 'SIGTERM', true, false, true);591test('spawnAndKill cleanup SIGKILL', spawnAndKill, 'SIGKILL', true, false, exitIfWindows);592test('spawnAndKill detached SIGTERM', spawnAndKill, 'SIGTERM', false, true, false);593test('spawnAndKill detached SIGKILL', spawnAndKill, 'SIGKILL', false, true, false);594test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, 'SIGTERM', true, true, false);595test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, 'SIGKILL', true, true, false);596597if (process.platform !== 'win32') {598 test('write to fast-exit process', async t => {599 // Try-catch here is necessary, because this test is not 100% accurate600 // Sometimes process can manage to accept input before exiting601 try {602 await execa(`fast-exit-${process.platform}`, [], {input: 'data'});603 t.pass();604 } catch (error) {605 t.is(error.exitCode, 32);606 }607 });608}609610test('use environment variables by default', async t => {611 const {stdout} = await execa('environment');612 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);613});614615test('extend environment variables by default', async t => {616 const {stdout} = await execa('environment', [], {env: {BAR: 'bar'}});617 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);618});619620test('do not extend environment with `extendEnv: false`', async t => {621 const {stdout} = await execa('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});622 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);623});624625test('can use `options.shell: true`', async t => {626 const {stdout} = await execa('node test/fixtures/noop foo', {shell: true});627 t.is(stdout, 'foo');628});629630test('can use `options.shell: string`', async t => {631 const shell = process.platform === 'win32' ? 'cmd.exe' : '/bin/bash';632 const {stdout} = await execa('node test/fixtures/noop foo', {shell});633 t.is(stdout, 'foo');634});635636test('use extend environment with `extendEnv: true` and `shell: true`', async t => {637 process.env.TEST = 'test';638 const command = process.platform === 'win32' ? 'echo %TEST%' : 'echo $TEST';639 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});640 t.is(stdout, 'test');641 delete process.env.TEST;642});643644test('do not buffer when streaming', async t => {645 const {stdout} = execa('max-buffer', ['stdout', '21'], {maxBuffer: 10});646 const result = await getStream(stdout);647 t.is(result, '....................\n');648});649650test('detach child process', async t => {651 const {stdout} = await execa('detach');652 const pid = Number(stdout);653 t.true(Number.isInteger(pid));654 t.true(isRunning(pid));655656 process.kill(pid, 'SIGKILL');657});658659// See #128660test('removes exit handler on exit', async t => {661 // FIXME: This relies on `signal-exit` internals662 const ee = process.__signal_exit_emitter__;663664 const child = execa('noop');665 const listener = ee.listeners('exit').pop();666667 await new Promise((resolve, reject) => {668 child.on('error', reject);669 child.on('exit', resolve);670 });671672 const included = ee.listeners('exit').includes(listener);673 t.false(included);674});675676test('promise methods are not enumerable', t => {677 const descriptors = Object.getOwnPropertyDescriptors(execa('noop'));678 // eslint-disable-next-line promise/prefer-await-to-then679 t.false(descriptors.then.enumerable);680 t.false(descriptors.catch.enumerable);681 // TOOD: Remove the `if`-guard when targeting Node.js 10682 if (Promise.prototype.finally) {683 t.false(descriptors.finally.enumerable);684 }685});686687// TOOD: Remove the `if`-guard when targeting Node.js 10688if (Promise.prototype.finally) {689 test('finally function is executed on success', async t => {690 let isCalled = false;691 const {stdout} = await execa('noop', ['foo']).finally(() => {692 isCalled = true;693 });694 t.is(isCalled, true);695 t.is(stdout, 'foo');696 });697698 test('finally function is executed on failure', async t => {699 let isError = false;700 const {stdout, stderr} = await t.throwsAsync(execa('exit', ['2']).finally(() => {701 isError = true;702 }));703 t.is(isError, true);704 t.is(typeof stdout, 'string');705 t.is(typeof stderr, 'string');706 });707708 test('throw in finally function bubbles up on success', async t => {709 const {message} = await t.throwsAsync(execa('noop', ['foo']).finally(() => {710 throw new Error('called');711 }));712 t.is(message, 'called');713 });714715 test('throw in finally bubbles up on error', async t => {716 const {message} = await t.throwsAsync(execa('exit', ['2']).finally(() => {717 throw new Error('called');718 }));719 t.is(message, 'called');720 });721}722723test('cancel method kills the subprocess', t => {724 const subprocess = execa('node');725 subprocess.cancel();726 t.true(subprocess.killed);727});728729test('result.isCanceled is false when spawned.cancel() isn\'t called (success)', async t => {730 const {isCanceled} = await execa('noop');731 t.false(isCanceled);732});733734test('result.isCanceled is false when spawned.cancel() isn\'t called (failure)', async t => {735 const {isCanceled} = await t.throwsAsync(execa('fail'));736 t.false(isCanceled);737});738739test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (success)', t => {740 const {isCanceled} = execa.sync('noop');741 t.false(isCanceled);742});743744test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (failure)', t => {745 const {isCanceled} = t.throws(() => {746 execa.sync('fail');747 });748 t.false(isCanceled);749});750751test('calling cancel method throws an error with message "Command was canceled"', async t => {752 const subprocess = execa('noop');753 subprocess.cancel();754 await t.throwsAsync(subprocess, {message: /Command was canceled/});755});756757test('error.isCanceled is true when cancel method is used', async t => {758 const subprocess = execa('noop');759 subprocess.cancel();760 const {isCanceled} = await t.throwsAsync(subprocess);761 t.true(isCanceled);762});763764test('error.isCanceled is false when kill method is used', async t => {765 const subprocess = execa('noop');766 subprocess.kill();767 const {isCanceled} = await t.throwsAsync(subprocess);768 t.false(isCanceled);769});770771test('calling cancel method twice should show the same behaviour as calling it once', async t => {772 const subprocess = execa('noop');773 subprocess.cancel();774 subprocess.cancel();775 const {isCanceled} = await t.throwsAsync(subprocess);776 t.true(isCanceled);777 t.true(subprocess.killed);778});779780test('calling cancel method on a successfully completed process does not make result.isCanceled true', async t => {781 const subprocess = execa('noop');782 const {isCanceled} = await subprocess;783 subprocess.cancel();784 t.false(isCanceled);785});786787test('calling cancel method on a process which has been killed does not make error.isCanceled true', async t => {788 const subprocess = execa('noop');789 subprocess.kill();790 const {isCanceled} = await t.throwsAsync(subprocess);791 t.false(isCanceled);792});793794test('allow commands with spaces and no array arguments', async t => {795 const {stdout} = await execa('command with space');796 t.is(stdout, '');797});798799test('allow commands with spaces and array arguments', async t => {800 const {stdout} = await execa('command with space', ['foo', 'bar']);801 t.is(stdout, 'foo\nbar');802});803804test('execa.command()', async t => {805 const {stdout} = await execa.command('node test/fixtures/echo foo bar');806 t.is(stdout, 'foo\nbar');807});808809test('execa.command() ignores consecutive spaces', async t => {810 const {stdout} = await execa.command('node test/fixtures/echo foo bar');811 t.is(stdout, 'foo\nbar');812});813814test('execa.command() allows escaping spaces in commands', async t => {815 const {stdout} = await execa.command('command\\ with\\ space foo bar');816 t.is(stdout, 'foo\nbar');817});818819test('execa.command() allows escaping spaces in arguments', async t => {820 const {stdout} = await execa.command('node test/fixtures/echo foo\\ bar');821 t.is(stdout, 'foo bar');822});823824test('execa.command() escapes other whitespaces', async t => {825 const {stdout} = await execa.command('node test/fixtures/echo foo\tbar');826 t.is(stdout, 'foo\tbar');827});828829test('execa.command() trims', async t => {830 const {stdout} = await execa.command(' node test/fixtures/echo foo bar ');831 t.is(stdout, 'foo\nbar');832});833834test('execa.command.sync()', t => {835 const {stdout} = execa.commandSync('node test/fixtures/echo foo bar');836 t.is(stdout, 'foo\nbar');837});
modified:index.d.ts+37 added-2 removed
185 unmodified lines
186 */187 readonly input?: string | Buffer | ReadableStream;188 }189190 interface SyncOptions<EncodingType = string>191 extends CommonOptions<EncodingType> {190 interface SyncOptions<EncodingType = string> extends CommonOptions<EncodingType> {191 /**192 Write some input to the `stdin` of your binary.193 */194 readonly input?: string | Buffer;195 }196197 interface NodeOptions<EncodingType = string> extends Options<EncodingType> {198 /**199 The Node.js executable to use.200201 @default process.execPath202 */203 readonly nodePath?: string;204205 /**206 List of string arguments passed to the Node.js executable.207208 @default process.execArgv209 */210 readonly nodeArguments?: string[];211 }212213 interface ExecaReturnBase<StdoutStderrType> {214 /**215 The file and arguments that were run.216 */
214 unmodified lines
431 @returns A result `Object` with `stdout` and `stderr` properties.432 */433 commandSync(command: string, options?: execa.SyncOptions): execa.ExecaSyncReturnValue;434 commandSync(command: string, options?: execa.SyncOptions<null>): execa.ExecaSyncReturnValue<Buffer>;435436 /**437 Execute a Node.js script as a child process.438439 @param scriptPath - Node.js script to execute.440 @param arguments - Arguments to pass to `scriptPath` on execution.441 @returns A [`child_process` instance](https://nodejs.org/api/child_process.html#child_process_class_childprocess), which is enhanced to also be a `Promise` for a result `Object` with `stdout` and `stderr` properties.442 */443 node(444 scriptPath: string,445 arguments?: readonly string[],446 options?: execa.NodeOptions447 ): execa.ExecaChildProcess;448 node(449 file: string,450 arguments?: readonly string[],451 options?: execa.Options<null>452 ): execa.ExecaChildProcess<Buffer>;453 node(file: string, options?: execa.Options): execa.ExecaChildProcess;454 node(file: string, options?: execa.Options<null>): execa.ExecaChildProcess<Buffer>;455};456457export = execa;
modified:index.js+27 added
518 unmodified lines
519module.exports.commandSync = (command, options) => {520 const [file, ...args] = parseCommand(command);521 return execa.sync(file, args, options);522};523524module.exports.node = (scriptPath, args, options) => {525 if (args && !Array.isArray(args) && typeof args === 'object') {526 options = args;527 args = [];528 }529530 const stdioOption = stdio.node(options);531 options = options || {};532533 return execa(534 options.nodePath || process.execPath,535 [536 ...(options.nodeArguments || process.execArgv),537 scriptPath,538 ...(Array.isArray(args) ? args : [])539 ],540 {541 ...options,542 stdin: undefined,543 stdout: undefined,544 stderr: undefined,545 stdio: stdioOption,546 shell: false547 }548 );549};
modified:index.test-d.ts+13 added
164 unmodified lines
165expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns', {encoding: 'utf8'}));166expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns', {encoding: null}));167expectType<ExecaSyncReturnValue<string>>(execa.commandSync('unicorns foo', {encoding: 'utf8'}));168expectType<ExecaSyncReturnValue<Buffer>>(execa.commandSync('unicorns foo', {encoding: null}));169170expectType<ExecaChildProcess<string>>(execa.node('unicorns'));171expectType<ExecaReturnValue<string>>(await execa.node('unicorns'));172expectType<ExecaReturnValue<string>>(173 await execa.node('unicorns', {encoding: 'utf8'})174);175expectType<ExecaReturnValue<Buffer>>(await execa.node('unicorns', {encoding: null}));176expectType<ExecaReturnValue<string>>(177 await execa.node('unicorns', ['foo'], {encoding: 'utf8'})178);179expectType<ExecaReturnValue<Buffer>>(180 await execa.node('unicorns', ['foo'], {encoding: null})181);
modified:readme.md+22 added
182 unmodified lines
183Same as [`execa.command()`](#execacommand-command-options) but synchronous.184185Returns or throws a [`childProcessResult`](#childProcessResult).186187### execa.node(scriptPath, [arguments], [options])188189Execute a Node.js script as a child process.190191Same as `execa('node', [file, ...arguments], options)` except (like [`child_process#fork()`](https://nodejs.org/api/child_process.html#child_process_child_process_fork_modulepath_args_options)):192 - the [`nodePath`](#nodepath-for-node-only) and [`nodeArguments`](#nodearguments-for-node-only) options can be used193 - the [`shell`](#shell) option cannot be used 194 - an extra channel [`ipc`](https://nodejs.org/api/child_process.html#child_process_options_stdio) is passed to [`stdio`](#stdio)195196### childProcessResult197198Type: `object`199
246 unmodified lines
446Default: `false`447448If `true`, no quoting or escaping of arguments is done on Windows. Ignored on other platforms. This is set to `true` automatically when the `shell` option is `true`.449450#### nodePath *(for `.node()` only)*451452Type: `string`<br>453Default: [`process.execPath`](https://nodejs.org/api/process.html#process_process_execpath)454455Node.js executable used to create the child process.456457#### nodeArguments *(for `.node()` only)*458459Type: `string[]`<br>460Default: [`process.execArgv`](https://nodejs.org/api/process.html#process_process_execargv)461462List of string arguments passed to the Node.js executable.463464## Tips465466### Save and pipe output from a child process467
55 unmodified lines
deleted:test.js-837 removed
1import path from 'path';2import fs from 'fs';3import stream from 'stream';4import childProcess from 'child_process';5import test from 'ava';6import getStream from 'get-stream';7import isRunning from 'is-running';8import tempfile from 'tempfile';9import pEvent from 'p-event';10import execa from '.';1112process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;13process.env.FOO = 'foo';1415const TIMEOUT_REGEXP = /timed out after/;1617const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);1819test('execa()', async t => {20 const {stdout} = await execa('noop', ['foo']);21 t.is(stdout, 'foo');22});2324if (process.platform === 'win32') {25 test('execa() - cmd file', async t => {26 const {stdout} = await execa('hello.cmd');27 t.is(stdout, 'Hello World');28 });2930 test('execa() - run cmd command', async t => {31 const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);32 t.is(stdout, 'Hello World');33 });34}3536test('buffer', async t => {37 const {stdout} = await execa('noop', ['foo'], {encoding: null});38 t.true(Buffer.isBuffer(stdout));39 t.is(stdout.toString(), 'foo');40});4142test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {43 const {all} = await execa('noop-132');44 t.is(all, '132');45});4647test('stdout/stderr/all available on errors', async t => {48 const {stdout, stderr, all} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});49 t.is(typeof stdout, 'string');50 t.is(typeof stderr, 'string');51 t.is(typeof all, 'string');52});5354test('stdout/stderr/all are undefined if ignored', async t => {55 const {stdout, stderr, all} = await execa('noop', {stdio: 'ignore'});56 t.is(stdout, undefined);57 t.is(stderr, undefined);58 t.is(all, undefined);59});6061test('stdout/stderr/all are undefined if ignored in sync mode', t => {62 const {stdout, stderr, all} = execa.sync('noop', {stdio: 'ignore'});63 t.is(stdout, undefined);64 t.is(stderr, undefined);65 t.is(all, undefined);66});6768const WRONG_COMMAND = process.platform === 'win32' ?69 '\'wrong\' is not recognized as an internal or external command,\r\noperable program or batch file.' :70 '';7172test('stdout/stderr/all on process errors', async t => {73 const {stdout, stderr, all} = await t.throwsAsync(execa('wrong command'));74 t.is(stdout, '');75 t.is(stderr, WRONG_COMMAND);76 t.is(all, WRONG_COMMAND);77});7879test('stdout/stderr/all on process errors, in sync mode', t => {80 const {stdout, stderr, all} = t.throws(() => {81 execa.sync('wrong command');82 });83 t.is(stdout, '');84 t.is(stderr, WRONG_COMMAND);85 t.is(all, undefined);86});8788test('pass `stdout` to a file descriptor', async t => {89 const file = tempfile('.txt');90 await execa('fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});91 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');92});9394test('pass `stderr` to a file descriptor', async t => {95 const file = tempfile('.txt');96 await execa('fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});97 t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');98});99100test('execa.sync()', t => {101 const {stdout} = execa.sync('noop', ['foo']);102 t.is(stdout, 'foo');103});104105test('execa.sync() throws error if written to stderr', t => {106 t.throws(() => {107 execa.sync('foo');108 }, process.platform === 'win32' ? /failed with exit code 1/ : /spawnSync foo ENOENT/);109});110111test('skip throwing when using reject option', async t => {112 const {exitCode} = await execa('fail', {reject: false});113 t.is(exitCode, 2);114});115116test('skip throwing when using reject option in sync mode', t => {117 const {exitCode} = execa.sync('fail', {reject: false});118 t.is(exitCode, 2);119});120121test('kill("SIGKILL") should terminate cleanly', async t => {122 const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});123 await pEvent(subprocess, 'message');124125 subprocess.kill('SIGKILL');126127 const {signal} = await t.throwsAsync(subprocess);128 t.is(signal, 'SIGKILL');129});130131// `SIGTERM` cannot be caught on Windows, and it always aborts the process (like `SIGKILL` on Unix).132// Therefore, this feature and those tests do not make sense on Windows.133if (process.platform !== 'win32') {134 test('`forceKillAfterTimeout: false` should not kill after a timeout', async t => {135 const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});136 await pEvent(subprocess, 'message');137138 subprocess.kill('SIGTERM', {forceKillAfterTimeout: false});139140 t.true(isRunning(subprocess.pid));141 subprocess.kill('SIGKILL');142 });143144 test('`forceKillAfterTimeout: number` should kill after a timeout', async t => {145 const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});146 await pEvent(subprocess, 'message');147148 subprocess.kill('SIGTERM', {forceKillAfterTimeout: 50});149150 const {signal} = await t.throwsAsync(subprocess);151 t.is(signal, 'SIGKILL');152 });153154 test('`forceKillAfterTimeout: true` should kill after a timeout', async t => {155 const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});156 await pEvent(subprocess, 'message');157158 subprocess.kill('SIGTERM', {forceKillAfterTimeout: true});159160 const {signal} = await t.throwsAsync(subprocess);161 t.is(signal, 'SIGKILL');162 });163164 test('kill() with no arguments should kill after a timeout', async t => {165 const subprocess = execa('node', ['fixtures/no-killable'], {stdio: ['ipc']});166 await pEvent(subprocess, 'message');167168 subprocess.kill();169170 const {signal} = await t.throwsAsync(subprocess);171 t.is(signal, 'SIGKILL');172 });173174 test('`forceKillAfterTimeout` should not be a float', t => {175 t.throws(() => {176 execa('noop').kill('SIGTERM', {forceKillAfterTimeout: 0.5});177 }, {instanceOf: TypeError, message: /non-negative integer/});178 });179180 test('`forceKillAfterTimeout` should not be negative', t => {181 t.throws(() => {182 execa('noop').kill('SIGTERM', {forceKillAfterTimeout: -1});183 }, {instanceOf: TypeError, message: /non-negative integer/});184 });185}186187test('stripFinalNewline: true', async t => {188 const {stdout} = await execa('noop', ['foo']);189 t.is(stdout, 'foo');190});191192test('stripFinalNewline: false', async t => {193 const {stdout} = await execa('noop', ['foo'], {stripFinalNewline: false});194 t.is(stdout, 'foo\n');195});196197test('stripFinalNewline on failure', async t => {198 const {stderr} = await t.throwsAsync(execa('noop-throw', ['foo'], {stripFinalNewline: true}));199 t.is(stderr, 'foo');200});201202test('stripFinalNewline in sync mode', t => {203 const {stdout} = execa.sync('noop', ['foo'], {stripFinalNewline: true});204 t.is(stdout, 'foo');205});206207test('stripFinalNewline in sync mode on failure', t => {208 const {stderr} = t.throws(() => {209 execa.sync('noop-throw', ['foo'], {stripFinalNewline: true});210 });211 t.is(stderr, 'foo');212});213214test('preferLocal option', async t => {215 await execa('ava', ['--version'], {env: {PATH: ''}});216 const errorRegExp = process.platform === 'win32' ? /failed with exit code 1/ : /spawn ava ENOENT/;217 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: {PATH: ''}}), errorRegExp);218});219220test('localDir option', async t => {221 const command = process.platform === 'win32' ? 'echo %PATH%' : 'echo $PATH';222 const {stdout} = await execa(command, {shell: true, localDir: '/test'});223 const envPaths = stdout.split(path.delimiter).map(envPath =>224 envPath.replace(/\\/g, '/').replace(/^[^/]+/, '')225 );226 t.true(envPaths.some(envPath => envPath === '/test/node_modules/.bin'));227});228229test('input option can be a String', async t => {230 const {stdout} = await execa('stdin', {input: 'foobar'});231 t.is(stdout, 'foobar');232});233234test('input option can be a Buffer', async t => {235 const {stdout} = await execa('stdin', {input: 'testing12'});236 t.is(stdout, 'testing12');237});238239test('input can be a Stream', async t => {240 const s = new stream.PassThrough();241 s.write('howdy');242 s.end();243 const {stdout} = await execa('stdin', {input: s});244 t.is(stdout, 'howdy');245});246247test('you can write to child.stdin', async t => {248 const child = execa('stdin');249 child.stdin.end('unicorns');250 t.is((await child).stdout, 'unicorns');251});252253test('input option can be a String - sync', t => {254 const {stdout} = execa.sync('stdin', {input: 'foobar'});255 t.is(stdout, 'foobar');256});257258test('input option can be a Buffer - sync', t => {259 const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});260 t.is(stdout, 'testing12');261});262263test('stdin errors are handled', async t => {264 const child = execa('noop');265 child.stdin.emit('error', new Error('test'));266 await t.throwsAsync(child, /test/);267});268269test('child process errors are handled', async t => {270 const child = execa('noop');271 child.emit('error', new Error('test'));272 await t.throwsAsync(child, /test/);273});274275test('opts.stdout:ignore - stdout will not collect data', async t => {276 const {stdout} = await execa('stdin', {277 input: 'hello',278 stdio: [undefined, 'ignore', undefined]279 });280 t.is(stdout, undefined);281});282283test('helpful error trying to provide an input stream in sync mode', t => {284 t.throws(285 () => {286 execa.sync('stdin', {input: new stream.PassThrough()});287 },288 /The `input` option cannot be a stream in sync mode/289 );290});291292test('child process errors rejects promise right away', async t => {293 const child = execa('forever');294 child.emit('error', new Error('test'));295 await t.throwsAsync(child, /test/);296});297298test('execa() returns a promise with kill() and pid', t => {299 const {kill, pid} = execa('noop', ['foo']);300 t.is(typeof kill, 'function');301 t.is(typeof pid, 'number');302});303304test('child_process.spawn() propagated errors have correct shape', t => {305 const cp = execa('noop', {uid: -1});306 t.notThrows(() => {307 cp.catch(() => {});308 cp.unref();309 cp.on('error', () => {});310 });311});312313test('child_process.spawn() errors are propagated', async t => {314 const {failed} = await t.throwsAsync(execa('noop', {uid: -1}));315 t.true(failed);316});317318test('child_process.spawnSync() errors are propagated with a correct shape', t => {319 const {failed} = t.throws(() => {320 execa.sync('noop', {timeout: -1});321 });322 t.true(failed);323});324325test('maxBuffer affects stdout', async t => {326 await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));327 const {stdout, all} = await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /max-buffer stdout/);328 t.is(stdout, '.'.repeat(10));329 t.is(all, '.'.repeat(10));330});331332test('maxBuffer affects stderr', async t => {333 await t.notThrowsAsync(execa('max-buffer', ['stderr', '10'], {maxBuffer: 10}));334 const {stderr, all} = await t.throwsAsync(execa('max-buffer', ['stderr', '11'], {maxBuffer: 10}), /max-buffer stderr/);335 t.is(stderr, '.'.repeat(10));336 t.is(all, '.'.repeat(10));337});338339test('do not buffer stdout when `buffer` set to `false`', async t => {340 const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});341 const [result, stdout] = await Promise.all([342 promise,343 getStream(promise.stdout),344 getStream(promise.all)345 ]);346347 t.is(result.stdout, undefined);348 t.is(stdout, '.........\n');349});350351test('do not buffer stderr when `buffer` set to `false`', async t => {352 const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});353 const [result, stderr] = await Promise.all([354 promise,355 getStream(promise.stderr),356 getStream(promise.all)357 ]);358359 t.is(result.stderr, undefined);360 t.is(stderr, '.........\n');361});362363test('allow unknown exit code', async t => {364 const {exitCode, exitCodeName} = await t.throwsAsync(execa('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});365 t.is(exitCode, 255);366 t.is(exitCodeName, 'Unknown system error -255');367});368369test('execa() does not return code and failed properties on success', async t => {370 const {exitCode, exitCodeName, failed} = await execa('noop', ['foo']);371 t.is(exitCode, 0);372 t.is(exitCodeName, 'SUCCESS');373 t.false(failed);374});375376test('execa() returns code and failed properties', async t => {377 const {exitCode, exitCodeName, failed} = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});378 t.is(exitCode, 2);379 const expectedName = process.platform === 'win32' ? 'Unknown system error -2' : 'ENOENT';380 t.is(exitCodeName, expectedName);381 t.true(failed);382});383384test('use relative path with \'..\' chars', async t => {385 const pathViaParentDir = path.join('..', path.basename(__dirname), 'fixtures', 'noop');386 const {stdout} = await execa(pathViaParentDir, ['foo']);387 t.is(stdout, 'foo');388});389390if (process.platform !== 'win32') {391 test('execa() rejects if running non-executable', async t => {392 const cp = execa('non-executable');393 await t.throwsAsync(cp);394 });395396 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {397 await t.throwsAsync(execa('non-executable', {input: 'Hey!'}), /EACCES/);398 });399}400401test('error.killed is true if process was killed directly', async t => {402 const cp = execa('forever');403404 cp.kill();405406 const {killed} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});407 t.true(killed);408});409410test('error.killed is false if process was killed indirectly', async t => {411 const cp = execa('forever');412413 process.kill(cp.pid, 'SIGINT');414415 // `process.kill()` is emulated by Node.js on Windows416 const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;417 const {killed} = await t.throwsAsync(cp, {message});418 t.false(killed);419});420421test('result.killed is false if not killed', async t => {422 const {killed} = await execa('noop');423 t.false(killed);424});425426test('result.killed is false if not killed, in sync mode', t => {427 const {killed} = execa.sync('noop');428 t.false(killed);429});430431test('result.killed is false on process error', async t => {432 const {killed} = await t.throwsAsync(execa('wrong command'));433 t.false(killed);434});435436test('result.killed is false on process error, in sync mode', t => {437 const {killed} = t.throws(() => {438 execa.sync('wrong command');439 });440 t.false(killed);441});442443if (process.platform === 'darwin') {444 test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {445 const {pid} = childProcess.exec('forever', error => {446 t.truthy(error);447 t.false(error.killed);448 t.end();449 });450451 process.kill(pid, 'SIGINT');452 });453}454455if (process.platform !== 'win32') {456 test('error.signal is SIGINT', async t => {457 const cp = execa('forever');458459 process.kill(cp.pid, 'SIGINT');460461 const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGINT/});462 t.is(signal, 'SIGINT');463 });464465 test('error.signal is SIGTERM', async t => {466 const cp = execa('forever');467468 process.kill(cp.pid, 'SIGTERM');469470 const {signal} = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});471 t.is(signal, 'SIGTERM');472 });473474 test('custom error.signal', async t => {475 const {signal} = await t.throwsAsync(execa('forever', {killSignal: 'SIGHUP', timeout: 1, message: TIMEOUT_REGEXP}));476 t.is(signal, 'SIGHUP');477 });478}479480test('result.signal is undefined for successful execution', async t => {481 const {signal} = await execa('noop');482 t.is(signal, undefined);483});484485test('result.signal is undefined if process failed, but was not killed', async t => {486 const {signal} = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});487 t.is(signal, undefined);488});489490async function testExitCode(t, num) {491 const {exitCode} = await t.throwsAsync(execa('exit', [`${num}`]), {message: getExitRegExp(num)});492 t.is(exitCode, num);493}494495test('error.exitCode is 2', testExitCode, 2);496test('error.exitCode is 3', testExitCode, 3);497test('error.exitCode is 4', testExitCode, 4);498499test('timeout kills the process if it times out', async t => {500 const {killed, timedOut} = await t.throwsAsync(execa('forever', {timeout: 1, message: TIMEOUT_REGEXP}));501 t.false(killed);502 t.true(timedOut);503});504505test('timeout kills the process if it times out, in sync mode', async t => {506 const {killed, timedOut} = await t.throws(() => {507 execa.sync('forever', {timeout: 1, message: TIMEOUT_REGEXP});508 });509 t.false(killed);510 t.true(timedOut);511});512513test('timeout does not kill the process if it does not time out', async t => {514 const {timedOut} = await execa('delay', ['500'], {timeout: 1e8});515 t.false(timedOut);516});517518test('timedOut is false if no timeout was set', async t => {519 const {timedOut} = await execa('noop');520 t.false(timedOut);521});522523test('timedOut will be false if no timeout was set and zero exit code in sync mode', t => {524 const {timedOut} = execa.sync('noop');525 t.false(timedOut);526});527528async function errorMessage(t, expected, ...args) {529 await t.throwsAsync(execa('exit', args), {message: expected});530}531532errorMessage.title = (message, expected) => `error.message matches: ${expected}`;533534test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');535test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');536537async function command(t, expected, ...args) {538 const {command: failCommand} = await t.throwsAsync(execa('fail', args));539 t.is(failCommand, `fail${expected}`);540541 const {command} = await execa('noop', args);542 t.is(command, `noop${expected}`);543}544545command.title = (message, expected) => `command is: ${JSON.stringify(expected)}`;546547test(command, ' foo bar', 'foo', 'bar');548test(command, ' baz quz', 'baz', 'quz');549test(command, '');550551// When child process exits before parent process552async function spawnAndExit(t, cleanup, detached) {553 await t.notThrowsAsync(execa('sub-process-exit', [cleanup, detached]));554}555556test('spawnAndExit', spawnAndExit, false, false);557test('spawnAndExit cleanup', spawnAndExit, true, false);558test('spawnAndExit detached', spawnAndExit, false, true);559test('spawnAndExit cleanup detached', spawnAndExit, true, true);560561// When parent process exits before child process562async function spawnAndKill(t, signal, cleanup, detached, isKilled) {563 const subprocess = execa('sub-process', [cleanup, detached], {stdio: ['ignore', 'ignore', 'ignore', 'ipc']});564565 const pid = await pEvent(subprocess, 'message');566 t.true(Number.isInteger(pid));567 t.true(isRunning(pid));568569 process.kill(subprocess.pid, signal);570571 await t.throwsAsync(subprocess);572573 t.false(isRunning(subprocess.pid));574 t.is(isRunning(pid), !isKilled);575576 if (!isKilled) {577 process.kill(pid, 'SIGKILL');578 }579}580581// Without `options.cleanup`:582// - on Windows subprocesses are killed if `options.detached: false`, but not583// if `options.detached: true`584// - on Linux subprocesses are never killed regardless of `options.detached`585// With `options.cleanup`, subprocesses are always killed586// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled587const exitIfWindows = process.platform === 'win32';588test('spawnAndKill SIGTERM', spawnAndKill, 'SIGTERM', false, false, exitIfWindows);589test('spawnAndKill SIGKILL', spawnAndKill, 'SIGKILL', false, false, exitIfWindows);590test('spawnAndKill cleanup SIGTERM', spawnAndKill, 'SIGTERM', true, false, true);591test('spawnAndKill cleanup SIGKILL', spawnAndKill, 'SIGKILL', true, false, exitIfWindows);592test('spawnAndKill detached SIGTERM', spawnAndKill, 'SIGTERM', false, true, false);593test('spawnAndKill detached SIGKILL', spawnAndKill, 'SIGKILL', false, true, false);594test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, 'SIGTERM', true, true, false);595test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, 'SIGKILL', true, true, false);596597if (process.platform !== 'win32') {598 test('write to fast-exit process', async t => {599 // Try-catch here is necessary, because this test is not 100% accurate600 // Sometimes process can manage to accept input before exiting601 try {602 await execa(`fast-exit-${process.platform}`, [], {input: 'data'});603 t.pass();604 } catch (error) {605 t.is(error.exitCode, 32);606 }607 });608}609610test('use environment variables by default', async t => {611 const {stdout} = await execa('environment');612 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);613});614615test('extend environment variables by default', async t => {616 const {stdout} = await execa('environment', [], {env: {BAR: 'bar'}});617 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);618});619620test('do not extend environment with `extendEnv: false`', async t => {621 const {stdout} = await execa('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});622 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);623});624625test('can use `options.shell: true`', async t => {626 const {stdout} = await execa('node fixtures/noop foo', {shell: true});627 t.is(stdout, 'foo');628});629630test('can use `options.shell: string`', async t => {631 const shell = process.platform === 'win32' ? 'cmd.exe' : '/bin/bash';632 const {stdout} = await execa('node fixtures/noop foo', {shell});633 t.is(stdout, 'foo');634});635636test('use extend environment with `extendEnv: true` and `shell: true`', async t => {637 process.env.TEST = 'test';638 const command = process.platform === 'win32' ? 'echo %TEST%' : 'echo $TEST';639 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});640 t.is(stdout, 'test');641 delete process.env.TEST;642});643644test('do not buffer when streaming', async t => {645 const {stdout} = execa('max-buffer', ['stdout', '21'], {maxBuffer: 10});646 const result = await getStream(stdout);647 t.is(result, '....................\n');648});649650test('detach child process', async t => {651 const {stdout} = await execa('detach');652 const pid = Number(stdout);653 t.true(Number.isInteger(pid));654 t.true(isRunning(pid));655656 process.kill(pid, 'SIGKILL');657});658659// See #128660test('removes exit handler on exit', async t => {661 // FIXME: This relies on `signal-exit` internals662 const ee = process.__signal_exit_emitter__;663664 const child = execa('noop');665 const listener = ee.listeners('exit').pop();666667 await new Promise((resolve, reject) => {668 child.on('error', reject);669 child.on('exit', resolve);670 });671672 const included = ee.listeners('exit').includes(listener);673 t.false(included);674});675676test('promise methods are not enumerable', t => {677 const descriptors = Object.getOwnPropertyDescriptors(execa('noop'));678 // eslint-disable-next-line promise/prefer-await-to-then679 t.false(descriptors.then.enumerable);680 t.false(descriptors.catch.enumerable);681 // TOOD: Remove the `if`-guard when targeting Node.js 10682 if (Promise.prototype.finally) {683 t.false(descriptors.finally.enumerable);684 }685});686687// TOOD: Remove the `if`-guard when targeting Node.js 10688if (Promise.prototype.finally) {689 test('finally function is executed on success', async t => {690 let isCalled = false;691 const {stdout} = await execa('noop', ['foo']).finally(() => {692 isCalled = true;693 });694 t.is(isCalled, true);695 t.is(stdout, 'foo');696 });697698 test('finally function is executed on failure', async t => {699 let isError = false;700 const {stdout, stderr} = await t.throwsAsync(execa('exit', ['2']).finally(() => {701 isError = true;702 }));703 t.is(isError, true);704 t.is(typeof stdout, 'string');705 t.is(typeof stderr, 'string');706 });707708 test('throw in finally function bubbles up on success', async t => {709 const {message} = await t.throwsAsync(execa('noop', ['foo']).finally(() => {710 throw new Error('called');711 }));712 t.is(message, 'called');713 });714715 test('throw in finally bubbles up on error', async t => {716 const {message} = await t.throwsAsync(execa('exit', ['2']).finally(() => {717 throw new Error('called');718 }));719 t.is(message, 'called');720 });721}722723test('cancel method kills the subprocess', t => {724 const subprocess = execa('node');725 subprocess.cancel();726 t.true(subprocess.killed);727});728729test('result.isCanceled is false when spawned.cancel() isn\'t called (success)', async t => {730 const {isCanceled} = await execa('noop');731 t.false(isCanceled);732});733734test('result.isCanceled is false when spawned.cancel() isn\'t called (failure)', async t => {735 const {isCanceled} = await t.throwsAsync(execa('fail'));736 t.false(isCanceled);737});738739test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (success)', t => {740 const {isCanceled} = execa.sync('noop');741 t.false(isCanceled);742});743744test('result.isCanceled is false when spawned.cancel() isn\'t called in sync mode (failure)', t => {745 const {isCanceled} = t.throws(() => {746 execa.sync('fail');747 });748 t.false(isCanceled);749});750751test('calling cancel method throws an error with message "Command was canceled"', async t => {752 const subprocess = execa('noop');753 subprocess.cancel();754 await t.throwsAsync(subprocess, {message: /Command was canceled/});755});756757test('error.isCanceled is true when cancel method is used', async t => {758 const subprocess = execa('noop');759 subprocess.cancel();760 const {isCanceled} = await t.throwsAsync(subprocess);761 t.true(isCanceled);762});763764test('error.isCanceled is false when kill method is used', async t => {765 const subprocess = execa('noop');766 subprocess.kill();767 const {isCanceled} = await t.throwsAsync(subprocess);768 t.false(isCanceled);769});770771test('calling cancel method twice should show the same behaviour as calling it once', async t => {772 const subprocess = execa('noop');773 subprocess.cancel();774 subprocess.cancel();775 const {isCanceled} = await t.throwsAsync(subprocess);776 t.true(isCanceled);777 t.true(subprocess.killed);778});779780test('calling cancel method on a successfuly completed process does not make result.isCanceled true', async t => {781 const subprocess = execa('noop');782 const {isCanceled} = await subprocess;783 subprocess.cancel();784 t.false(isCanceled);785});786787test('calling cancel method on a process which has been killed does not make error.isCanceled true', async t => {788 const subprocess = execa('noop');789 subprocess.kill();790 const {isCanceled} = await t.throwsAsync(subprocess);791 t.false(isCanceled);792});793794test('allow commands with spaces and no array arguments', async t => {795 const {stdout} = await execa('./fixtures/command with space');796 t.is(stdout, '');797});798799test('allow commands with spaces and array arguments', async t => {800 const {stdout} = await execa('./fixtures/command with space', ['foo', 'bar']);801 t.is(stdout, 'foo\nbar');802});803804test('execa.command()', async t => {805 const {stdout} = await execa.command('node fixtures/echo foo bar');806 t.is(stdout, 'foo\nbar');807});808809test('execa.command() ignores consecutive spaces', async t => {810 const {stdout} = await execa.command('node fixtures/echo foo bar');811 t.is(stdout, 'foo\nbar');812});813814test('execa.command() allows escaping spaces in commands', async t => {815 const {stdout} = await execa.command('./fixtures/command\\ with\\ space foo bar');816 t.is(stdout, 'foo\nbar');817});818819test('execa.command() allows escaping spaces in arguments', async t => {820 const {stdout} = await execa.command('node fixtures/echo foo\\ bar');821 t.is(stdout, 'foo bar');822});823824test('execa.command() escapes other whitespaces', async t => {825 const {stdout} = await execa.command('node fixtures/echo foo\tbar');826 t.is(stdout, 'foo\tbar');827});828829test('execa.command() trims', async t => {830 const {stdout} = await execa.command(' node fixtures/echo foo bar ');831 t.is(stdout, 'foo\nbar');832});833834test('execa.command.sync()', t => {835 const {stdout} = execa.commandSync('node fixtures/echo foo bar');836 t.is(stdout, 'foo\nbar');837});