Skip to content
Myr

test.js

This file

Path

test.js

642 lines · 19.6 KiB · JavaScript

Last changed by

Clean up #189Sindre Sorhusbefore adoptionf24e7c7

History of this file

Take it

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 delay from 'delay';9import tempfile from 'tempfile';10import execa from '.';1112process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;13process.env.FOO = 'foo';1415const NO_NEWLINES_REGEXP = /^[^\n]*$/;16const STDERR_STDOUT_REGEXP = /stderr[^]*stdout/;17const TIMEOUT_REGEXP = /timed out after/;1819const getExitRegExp = exitMessage => new RegExp(`failed with exit code ${exitMessage}`);2021test('execa()', async t => {22	const {stdout} = await execa('noop', ['foo']);23	t.is(stdout, 'foo');24});2526if (process.platform === 'win32') {27	test('execa() - cmd file', async t => {28		const {stdout} = await execa('hello.cmd');29		t.is(stdout, 'Hello World');30	});31}3233test('buffer', async t => {34	const {stdout} = await execa('noop', ['foo'], {encoding: null});35	t.true(Buffer.isBuffer(stdout));36	t.is(stdout.toString(), 'foo');37});3839test('execa.stdout()', async t => {40	const stdout = await execa.stdout('noop', ['foo']);41	t.is(stdout, 'foo');42});4344test('execa.stderr()', async t => {45	const stderr = await execa.stderr('noop-err', ['foo']);46	t.is(stderr, 'foo');47});4849test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {50	const result = await execa('noop-132');51	t.is(result.all, '132');52});5354test('stdout/stderr/all available on errors', async t => {55	const err = await t.throwsAsync(execa('exit', ['2']), {message: getExitRegExp('2')});56	t.is(typeof err.stdout, 'string');57	t.is(typeof err.stderr, 'string');58	t.is(typeof err.all, 'string');59});6061test('include stdout and stderr in errors for improved debugging', async t => {62	await t.throwsAsync(execa('fixtures/error-message.js'), {message: STDERR_STDOUT_REGEXP, code: 1});63});6465test('do not include in errors when `stdio` is set to `inherit`', async t => {66	await t.throwsAsync(execa('fixtures/error-message.js', {stdio: 'inherit'}), {message: NO_NEWLINES_REGEXP});67});6869test('do not include `stderr` and `stdout` in errors when set to `inherit`', async t => {70	await t.throwsAsync(execa('fixtures/error-message.js', {stdout: 'inherit', stderr: 'inherit'}), {message: NO_NEWLINES_REGEXP});71});7273test('do not include `stderr` and `stdout` in errors when `stdio` is set to `inherit`', async t => {74	await t.throwsAsync(execa('fixtures/error-message.js', {stdio: [null, 'inherit', 'inherit']}), {message: NO_NEWLINES_REGEXP});75});7677test('do not include `stdout` in errors when set to `inherit`', async t => {78	const err = await t.throwsAsync(execa('fixtures/error-message.js', {stdout: 'inherit'}), {message: /stderr/});79	t.notRegex(err.message, /stdout/);80});8182test('do not include `stderr` in errors when set to `inherit`', async t => {83	const err = await t.throwsAsync(execa('fixtures/error-message.js', {stderr: 'inherit'}), {message: /stdout/});84	t.notRegex(err.message, /stderr/);85});8687test('pass `stdout` to a file descriptor', async t => {88	const file = tempfile('.txt');89	await execa('fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});90	t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');91});9293test('pass `stderr` to a file descriptor', async t => {94	const file = tempfile('.txt');95	await execa('fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});96	t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');97});9899test('execa.shell()', async t => {100	const {stdout} = await execa.shell('node fixtures/noop foo');101	t.is(stdout, 'foo');102});103104test('execa.sync()', t => {105	const {stdout} = execa.sync('noop', ['foo']);106	t.is(stdout, 'foo');107});108109test('execa.sync() throws error if written to stderr', t => {110	t.throws(() => execa.sync('foo'), process.platform === 'win32' ? /'foo' is not recognized as an internal or external command/ : /spawnSync foo ENOENT/);111});112113test('execa.sync() includes stdout and stderr in errors for improved debugging', t => {114	t.throws(() => execa.sync('node', ['fixtures/error-message.js']), {message: STDERR_STDOUT_REGEXP, code: 1});115});116117test('skip throwing when using reject option in execa.sync()', t => {118	const err = execa.sync('node', ['fixtures/error-message.js'], {reject: false});119	t.is(typeof err.stdout, 'string');120	t.is(typeof err.stderr, 'string');121});122123test('execa.shellSync()', t => {124	const {stdout} = execa.shellSync('node fixtures/noop foo');125	t.is(stdout, 'foo');126});127128test('execa.shellSync() includes stdout and stderr in errors for improved debugging', t => {129	t.throws(() => execa.shellSync('node fixtures/error-message.js'), {message: STDERR_STDOUT_REGEXP, code: 1});130});131132test('skip throwing when using reject option in execa.shellSync()', t => {133	const err = execa.shellSync('node fixtures/error-message.js', {reject: false});134	t.is(typeof err.stdout, 'string');135	t.is(typeof err.stderr, 'string');136});137138test('stripEof option (legacy)', async t => {139	const {stdout} = await execa('noop', ['foo'], {stripEof: false});140	t.is(stdout, 'foo\n');141});142143test('stripFinalNewline option', async t => {144	const {stdout} = await execa('noop', ['foo'], {stripFinalNewline: false});145	t.is(stdout, 'foo\n');146});147148test.serial('preferLocal option', async t => {149	t.true((await execa('cat-names')).stdout.length > 2);150151	if (process.platform === 'win32') {152		// TODO: figure out how to make the below not hang on Windows153		return;154	}155156	// Account for npm adding local binaries to the PATH157	const _path = process.env.PATH;158	process.env.PATH = '';159	await t.throwsAsync(execa('cat-names', {preferLocal: false}), /spawn .* ENOENT/);160	process.env.PATH = _path;161});162163test.serial('localDir option', async t => {164	const cwd = 'fixtures/local-dir';165	const bin = path.resolve(cwd, 'node_modules/.bin/self-path');166167	await execa('npm', ['install', '--no-package-lock'], {cwd});168169	const {stdout} = await execa(bin, {localDir: cwd});170171	t.is(path.relative(cwd, stdout), path.normalize('node_modules/self-path'));172});173174test('input option can be a String', async t => {175	const {stdout} = await execa('stdin', {input: 'foobar'});176	t.is(stdout, 'foobar');177});178179test('input option can be a Buffer', async t => {180	const {stdout} = await execa('stdin', {input: 'testing12'});181	t.is(stdout, 'testing12');182});183184test('input can be a Stream', async t => {185	const s = new stream.PassThrough();186	s.write('howdy');187	s.end();188	const {stdout} = await execa('stdin', {input: s});189	t.is(stdout, 'howdy');190});191192test('you can write to child.stdin', async t => {193	const child = execa('stdin');194	child.stdin.end('unicorns');195	t.is((await child).stdout, 'unicorns');196});197198test('input option can be a String - sync', t => {199	const {stdout} = execa.sync('stdin', {input: 'foobar'});200	t.is(stdout, 'foobar');201});202203test('input option can be a Buffer - sync', t => {204	const {stdout} = execa.sync('stdin', {input: Buffer.from('testing12', 'utf8')});205	t.is(stdout, 'testing12');206});207208test('opts.stdout:ignore - stdout will not collect data', async t => {209	const {stdout} = await execa('stdin', {210		input: 'hello',211		stdio: [null, 'ignore', null]212	});213	t.is(stdout, undefined);214});215216test('helpful error trying to provide an input stream in sync mode', t => {217	t.throws(218		() => execa.sync('stdin', {input: new stream.PassThrough()}),219		/The `input` option cannot be a stream in sync mode/220	);221});222223test('execa() returns a promise with kill() and pid', t => {224	const promise = execa('noop', ['foo']);225	t.is(typeof promise.kill, 'function');226	t.is(typeof promise.pid, 'number');227});228229test('maxBuffer affects stdout', async t => {230	await t.throwsAsync(execa('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /stdout maxBuffer exceeded/);231	await t.notThrowsAsync(execa('max-buffer', ['stdout', '10'], {maxBuffer: 10}));232});233234test('maxBuffer affects stderr', async t => {235	await t.throwsAsync(execa('max-buffer', ['stderr', '13'], {maxBuffer: 12}), /stderr maxBuffer exceeded/);236	await t.notThrowsAsync(execa('max-buffer', ['stderr', '12'], {maxBuffer: 12}));237});238239test('do not buffer stdout when `buffer` set to `false`', async t => {240	const promise = execa('max-buffer', ['stdout', '10'], {buffer: false});241	const [result, stdout] = await Promise.all([242		promise,243		getStream(promise.stdout),244		getStream(promise.all)245	]);246247	t.is(result.stdout, undefined);248	t.is(stdout, '.........\n');249});250251test('do not buffer stderr when `buffer` set to `false`', async t => {252	const promise = execa('max-buffer', ['stderr', '10'], {buffer: false});253	const [result, stderr] = await Promise.all([254		promise,255		getStream(promise.stderr),256		getStream(promise.all)257	]);258259	t.is(result.stderr, undefined);260	t.is(stderr, '.........\n');261});262263test('skip throwing when using reject option', async t => {264	const error = await execa('exit', ['2'], {reject: false});265	t.is(typeof error.stdout, 'string');266	t.is(typeof error.stderr, 'string');267});268269test('allow unknown exit code', async t => {270	const {exitCode, exitCodeName} = await t.throwsAsync(execa('exit', ['255']), {message: /exit code 255 \(Unknown system error -255\)/});271	t.is(exitCode, 255);272	t.is(exitCodeName, 'Unknown system error -255');273});274275test('execa() returns code and failed properties', async t => {276	const {code, exitCode, exitCodeName, failed} = await execa('noop', ['foo']);277	t.is(code, 0);278	t.is(exitCode, 0);279	t.is(exitCodeName, 'SUCCESS');280	t.false(failed);281282	const error = await t.throwsAsync(execa('exit', ['2']), {code: 2, message: getExitRegExp('2')});283	t.is(error.exitCode, 2);284	const expectedName = process.platform === 'win32' ? 'Unknown system error -2' : 'ENOENT';285	t.is(error.exitCodeName, expectedName);286	t.true(error.failed);287});288289test('use relative path with \'..\' chars', async t => {290	const pathViaParentDir = path.join('..', path.basename(__dirname), 'fixtures', 'noop');291	const {stdout} = await execa(pathViaParentDir, ['foo']);292	t.is(stdout, 'foo');293});294295if (process.platform !== 'win32') {296	test('execa() rejects if running non-executable', async t => {297		const cp = execa('non-executable');298		await t.throwsAsync(cp);299	});300}301302test('error.killed is true if process was killed directly', async t => {303	const cp = execa('forever');304305	setTimeout(() => {306		cp.kill();307	}, 100);308309	const error = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});310	t.true(error.killed);311});312313// TODO: Should this really be the case, or should we improve on child_process?314test('error.killed is false if process was killed indirectly', async t => {315	const cp = execa('forever');316317	setTimeout(() => {318		process.kill(cp.pid, 'SIGINT');319	}, 100);320321	// `process.kill()` is emulated by Node.js on Windows322	const message = process.platform === 'win32' ? /failed with exit code 1/ : /was killed with SIGINT/;323	const error = await t.throwsAsync(cp, {message});324	t.false(error.killed);325});326327if (process.platform === 'darwin') {328	test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {329		const cp = childProcess.exec('forever', error => {330			t.truthy(error);331			t.false(error.killed);332			t.end();333		});334335		setTimeout(() => {336			process.kill(cp.pid, 'SIGINT');337		}, 100);338	});339}340341if (process.platform !== 'win32') {342	test('error.signal is SIGINT', async t => {343		const cp = execa('forever');344345		setTimeout(() => {346			process.kill(cp.pid, 'SIGINT');347		}, 100);348349		const error = await t.throwsAsync(cp, {message: /was killed with SIGINT/});350		t.is(error.signal, 'SIGINT');351	});352353	test('error.signal is SIGTERM', async t => {354		const cp = execa('forever');355356		setTimeout(() => {357			process.kill(cp.pid, 'SIGTERM');358		}, 100);359360		const error = await t.throwsAsync(cp, {message: /was killed with SIGTERM/});361		t.is(error.signal, 'SIGTERM');362	});363364	test('custom error.signal', async t => {365		const error = await t.throwsAsync(execa('delay', ['3000', '0'], {killSignal: 'SIGHUP', timeout: 1500, message: TIMEOUT_REGEXP}));366		t.is(error.signal, 'SIGHUP');367	});368}369370test('result.signal is undefined for successful execution', async t => {371	t.is((await execa('noop')).signal, undefined);372});373374test('result.signal is undefined if process failed, but was not killed', async t => {375	const error = await t.throwsAsync(execa('exit', [2]), {message: getExitRegExp('2')});376	t.is(error.signal, undefined);377});378379async function code(t, num) {380	const error = await t.throwsAsync(execa('exit', [`${num}`]), {code: num, message: getExitRegExp(num)});381	t.is(error.exitCode, num);382}383384test('error.code is 2', code, 2);385test('error.code is 3', code, 3);386test('error.code is 4', code, 4);387388test('timeout will kill the process early', async t => {389	const error = await t.throwsAsync(execa('delay', ['60000', '0'], {timeout: 1500, message: TIMEOUT_REGEXP}));390391	t.true(error.timedOut);392	t.not(error.exitCode, 22);393});394395test('timeout will not kill the process early', async t => {396	const error = await t.throwsAsync(execa('delay', ['3000', '22'], {timeout: 30000}), {code: 22, message: getExitRegExp('22')});397	t.false(error.timedOut);398});399400test('timedOut will be false if no timeout was set and zero exit code', async t => {401	const result = await execa('delay', ['1000', '0']);402	t.false(result.timedOut);403});404405test('timedOut will be false if no timeout was set and non-zero exit code', async t => {406	const error = await t.throwsAsync(execa('delay', ['1000', '3']), {message: getExitRegExp('3')});407	t.false(error.timedOut);408});409410async function errorMessage(t, expected, ...args) {411	await t.throwsAsync(execa('exit', args), {message: expected});412}413414errorMessage.title = (message, expected) => `error.message matches: ${expected}`;415416test(errorMessage, /Command failed with exit code 2.*: exit 2 foo bar/, 2, 'foo', 'bar');417test(errorMessage, /Command failed with exit code 3.*: exit 3 baz quz/, 3, 'baz', 'quz');418419async function cmd(t, expected, ...args) {420	const error = await t.throwsAsync(execa('fail', args));421	t.is(error.cmd, `fail${expected}`);422423	const result = await execa('noop', args);424	t.is(result.cmd, `noop${expected}`);425}426427cmd.title = (message, expected) => `cmd is: ${JSON.stringify(expected)}`;428429test(cmd, ' foo bar', 'foo', 'bar');430test(cmd, ' baz quz', 'baz', 'quz');431test(cmd, '');432433async function spawnAndKill(t, signal, cleanup) {434	const name = cleanup ? 'sub-process' : 'sub-process-false';435	const cp = execa(name);436	let pid;437438	cp.stdout.setEncoding('utf8');439	cp.stdout.on('data', chunk => {440		pid = parseInt(chunk, 10);441		t.is(typeof pid, 'number');442443		setTimeout(() => {444			process.kill(cp.pid, signal);445		}, 100);446	});447448	await t.throwsAsync(cp);449450	// Give everybody some time to breath and kill things451	await delay(200);452453	t.false(isRunning(cp.pid));454	t.is(isRunning(pid), !cleanup);455}456457test('cleanup - SIGINT', spawnAndKill, 'SIGINT', true);458test('cleanup - SIGKILL', spawnAndKill, 'SIGTERM', true);459460if (process.platform !== 'win32') {461	// On Windows the subprocesses are actually always killed462	test('cleanup false - SIGINT', spawnAndKill, 'SIGTERM', false);463	test('cleanup false - SIGKILL', spawnAndKill, 'SIGKILL', false);464}465466test('execa.shell() supports the `shell` option', async t => {467	const {stdout} = await execa.shell('node fixtures/noop foo', {468		shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/bash'469	});470	t.is(stdout, 'foo');471});472473if (process.platform !== 'win32') {474	test('write to fast-exit process', async t => {475		// Try-catch here is necessary, because this test is not 100% accurate476		// Sometimes process can manage to accept input before exiting477		try {478			await execa(`fast-exit-${process.platform}`, [], {input: 'data'});479			t.pass();480		} catch (error) {481			t.is(error.exitCode, 32);482		}483	});484}485486test('use environment variables by default', async t => {487	const result = await execa.stdout('environment');488489	t.deepEqual(result.split('\n'), [490		'foo',491		'undefined'492	]);493});494495test('extend environment variables by default', async t => {496	const result = await execa.stdout('environment', [], {env: {BAR: 'bar'}});497498	t.deepEqual(result.split('\n'), [499		'foo',500		'bar'501	]);502});503504test('do not extend environment with `extendEnv: false`', async t => {505	const result = await execa.stdout('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});506507	t.deepEqual(result.split('\n'), [508		'undefined',509		'bar'510	]);511});512513test('use extend environment with `extendEnv: true` and `shell: true`', async t => {514	process.env.TEST = 'test';515	const command = process.platform === 'win32' ? 'echo %TEST%' : 'echo $TEST';516	const stdout = await execa.stdout(command, {shell: true, env: {}, extendEnv: true});517	t.is(stdout, 'test');518	delete process.env.TEST;519});520521test('do not buffer when streaming', async t => {522	const result = await getStream(execa('max-buffer', ['stdout', '21'], {maxBuffer: 10}).stdout);523524	t.is(result, '....................\n');525});526527test('detach child process', async t => {528	const file = tempfile('.txt');529530	await execa('detach', [file]);531532	await delay(5000);533534	t.is(fs.readFileSync(file, 'utf8'), 'foo\n');535});536537// See #128538test('removes exit handler on exit', async t => {539	// FIXME: This relies on `signal-exit` internals540	const ee = process.__signal_exit_emitter__;541542	const child = execa('noop');543	const listener = ee.listeners('exit').pop();544545	await new Promise((resolve, reject) => {546		child.on('error', reject);547		child.on('exit', resolve);548	});549550	const included = ee.listeners('exit').includes(listener);551	t.false(included);552});553554// TOOD: Remove the `if`-guard when targeting Node.js 10555if (Promise.prototype.finally) {556	test('finally function is executed on success', async t => {557		let called = false;558		const {stdout} = await execa('noop', ['foo']).finally(() => {559			called = true;560		});561		t.is(called, true);562		t.is(stdout, 'foo');563	});564565	test('finally function is executed on failure', async t => {566		let called = false;567		const err = await t.throwsAsync(execa('exit', ['2']).finally(() => {568			called = true;569		}));570		t.is(called, true);571		t.is(typeof err.stdout, 'string');572		t.is(typeof err.stderr, 'string');573	});574575	test('throw in finally function bubbles up on success', async t => {576		const result = await t.throwsAsync(execa('noop', ['foo']).finally(() => {577			throw new Error('called');578		}));579		t.is(result.message, 'called');580	});581582	test('throw in finally bubbles up on error', async t => {583		const result = await t.throwsAsync(execa('exit', ['2']).finally(() => {584			throw new Error('called');585		}));586		t.is(result.message, 'called');587	});588}589590test('cancel method kills the subprocess', t => {591	const subprocess = execa('node');592	subprocess.cancel();593	t.true(subprocess.killed);594});595596test('result.isCanceled is false when spawned.cancel isn\'t called', async t => {597	const result = await execa('noop');598	t.false(result.isCanceled);599});600601test('calling cancel method throws an error with message "Command was canceled"', async t => {602	const subprocess = execa('noop');603	subprocess.cancel();604	await t.throwsAsync(subprocess, {message: /Command was canceled/});605});606607test('error.isCanceled is true when cancel method is used', async t => {608	const subprocess = execa('noop');609	subprocess.cancel();610	const error = await t.throwsAsync(subprocess);611	t.true(error.isCanceled);612});613614test('error.isCanceled is false when kill method is used', async t => {615	const subprocess = execa('noop');616	subprocess.kill();617	const error = await t.throwsAsync(subprocess);618	t.false(error.isCanceled);619});620621test('calling cancel method twice should show the same behaviour as calling it once', async t => {622	const subprocess = execa('noop');623	subprocess.cancel();624	subprocess.cancel();625	const error = await t.throwsAsync(subprocess);626	t.true(error.isCanceled);627	t.true(subprocess.killed);628});629630test('calling cancel method on a successfuly completed process does not make result.isCanceled true', async t => {631	const subprocess = execa('noop');632	const result = await subprocess;633	subprocess.cancel();634	t.false(result.isCanceled);635});636637test('calling cancel method on a process which has been killed does not make error.isCanceled true', async t => {638	const subprocess = execa('noop');639	subprocess.kill();640	const error = await t.throwsAsync(subprocess);641	t.false(error.isCanceled);642});