Skip to content
Myr

test.js

This file

Path

test.js

548 lines · 15.0 KiB · JavaScript

Last changed by

Add `buffer` option to be able to disable buffering (#133)Spencerbefore adoption50384aa

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 m from '.';1112process.env.PATH = path.join(__dirname, 'fixtures') + path.delimiter + process.env.PATH;13process.env.FOO = 'foo';1415test('execa()', async t => {16	const {stdout} = await m('noop', ['foo']);17	t.is(stdout, 'foo');18});1920if (process.platform === 'win32') {21	test('execa() - cmd file', async t => {22		const {stdout} = await m('hello.cmd');2324		t.is(stdout, 'Hello World');25	});26}2728test('buffer', async t => {29	const {stdout} = await m('noop', ['foo'], {encoding: null});30	t.true(Buffer.isBuffer(stdout));31	t.is(stdout.toString(), 'foo');32});3334test('execa.stdout()', async t => {35	const stdout = await m.stdout('noop', ['foo']);36	t.is(stdout, 'foo');37});3839test('execa.stderr()', async t => {40	const stderr = await m.stderr('noop-err', ['foo']);41	t.is(stderr, 'foo');42});4344test('stdout/stderr available on errors', async t => {45	const err = await t.throws(m('exit', ['2']));46	t.is(typeof err.stdout, 'string');47	t.is(typeof err.stderr, 'string');48});4950test('include stdout and stderr in errors for improved debugging', async t => {51	const err = await t.throws(m('fixtures/error-message.js'));52	t.regex(err.message, /stdout/);53	t.regex(err.message, /stderr/);54	t.is(err.code, 1);55});5657test('do not include in errors when `stdio` is set to `inherit`', async t => {58	const err = await t.throws(m('fixtures/error-message.js', {stdio: 'inherit'}));59	t.notRegex(err.message, /\n/);60});6162test('do not include `stderr` and `stdout` in errors when set to `inherit`', async t => {63	const err = await t.throws(m('fixtures/error-message.js', {stdout: 'inherit', stderr: 'inherit'}));64	t.notRegex(err.message, /\n/);65});6667test('do not include `stderr` and `stdout` in errors when `stdio` is set to `inherit`', async t => {68	const err = await t.throws(m('fixtures/error-message.js', {stdio: [null, 'inherit', 'inherit']}));69	t.notRegex(err.message, /\n/);70});7172test('do not include `stdout` in errors when set to `inherit`', async t => {73	const err = await t.throws(m('fixtures/error-message.js', {stdout: 'inherit'}));74	t.notRegex(err.message, /stdout/);75	t.regex(err.message, /stderr/);76});7778test('do not include `stderr` in errors when set to `inherit`', async t => {79	const err = await t.throws(m('fixtures/error-message.js', {stderr: 'inherit'}));80	t.regex(err.message, /stdout/);81	t.notRegex(err.message, /stderr/);82});8384test('pass `stdout` to a file descriptor', async t => {85	const file = tempfile('.txt');86	await m('fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});87	t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');88});8990test('pass `stderr` to a file descriptor', async t => {91	const file = tempfile('.txt');92	await m('fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});93	t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');94});9596test('execa.shell()', async t => {97	const {stdout} = await m.shell('node fixtures/noop foo');98	t.is(stdout, 'foo');99});100101test('execa.spawn()', async t => {102	t.is(typeof m.spawn('noop').pid, 'number');103	t.is((await getStream(m.spawn('noop', ['foo']).stdout)).trim(), 'foo');104});105106test('execa.sync()', t => {107	const {stdout} = m.sync('noop', ['foo']);108	t.is(stdout, 'foo');109});110111test('execa.sync() throws error if written to stderr', t => {112	t.throws(() => m.sync('foo'), process.platform === 'win32' ? /'foo' is not recognized as an internal or external command/ : 'spawnSync foo ENOENT');113});114115test('execa.sync() includes stdout and stderr in errors for improved debugging', t => {116	const err = t.throws(() => m.sync('node', ['fixtures/error-message.js']));117	t.regex(err.message, /stdout/);118	t.regex(err.message, /stderr/);119	t.is(err.code, 1);120});121122test('skip throwing when using reject option in execa.sync()', t => {123	const err = m.sync('node', ['fixtures/error-message.js'], {reject: false});124	t.is(typeof err.stdout, 'string');125	t.is(typeof err.stderr, 'string');126});127128test('execa.shellSync()', t => {129	const {stdout} = m.shellSync('node fixtures/noop foo');130	t.is(stdout, 'foo');131});132133test('execa.shellSync() includes stdout and stderr in errors for improved debugging', t => {134	const err = t.throws(() => m.shellSync('node fixtures/error-message.js'));135	t.regex(err.message, /stdout/);136	t.regex(err.message, /stderr/);137	t.is(err.code, 1);138});139140test('skip throwing when using reject option in execa.shellSync()', t => {141	const err = m.shellSync('node fixtures/error-message.js', {reject: false});142	t.is(typeof err.stdout, 'string');143	t.is(typeof err.stderr, 'string');144});145146test('stripEof option', async t => {147	const {stdout} = await m('noop', ['foo'], {stripEof: false});148	t.is(stdout, 'foo\n');149});150151test.serial('preferLocal option', async t => {152	t.true((await m('cat-names')).stdout.length > 2);153154	if (process.platform === 'win32') {155		// TODO: figure out how to make the below not hang on Windows156		return;157	}158159	// Account for npm adding local binaries to the PATH160	const _path = process.env.PATH;161	process.env.PATH = '';162	await t.throws(m('cat-names', {preferLocal: false}), /spawn .* ENOENT/);163	process.env.PATH = _path;164});165166test.serial('localDir option', async t => {167	const cwd = 'fixtures/local-dir';168	const bin = path.resolve(cwd, 'node_modules/.bin/self-path');169170	await m('npm', ['install', '--no-package-lock'], {cwd});171172	const {stdout} = await m(bin, {localDir: cwd});173174	t.is(path.relative(cwd, stdout), path.normalize('node_modules/self-path'));175});176177test('input option can be a String', async t => {178	const {stdout} = await m('stdin', {input: 'foobar'});179	t.is(stdout, 'foobar');180});181182test('input option can be a Buffer', async t => {183	const {stdout} = await m('stdin', {input: 'testing12'});184	t.is(stdout, 'testing12');185});186187test('input can be a Stream', async t => {188	const s = new stream.PassThrough();189	s.write('howdy');190	s.end();191	const {stdout} = await m('stdin', {input: s});192	t.is(stdout, 'howdy');193});194195test('you can write to child.stdin', async t => {196	const child = m('stdin');197	child.stdin.end('unicorns');198	t.is((await child).stdout, 'unicorns');199});200201test('input option can be a String - sync', t => {202	const {stdout} = m.sync('stdin', {input: 'foobar'});203	t.is(stdout, 'foobar');204});205206test('input option can be a Buffer - sync', t => {207	const {stdout} = m.sync('stdin', {input: Buffer.from('testing12', 'utf8')});208	t.is(stdout, 'testing12');209});210211test('opts.stdout:ignore - stdout will not collect data', async t => {212	const {stdout} = await m('stdin', {213		input: 'hello',214		stdio: [null, 'ignore', null]215	});216	t.is(stdout, null);217});218219test('helpful error trying to provide an input stream in sync mode', t => {220	t.throws(221		() => m.sync('stdin', {input: new stream.PassThrough()}),222		/The `input` option cannot be a stream in sync mode/223	);224});225226test('execa() returns a promise with kill() and pid', t => {227	const promise = m('noop', ['foo']);228	t.is(typeof promise.kill, 'function');229	t.is(typeof promise.pid, 'number');230});231232test('maxBuffer affects stdout', async t => {233	await t.throws(m('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /stdout maxBuffer exceeded/);234	await t.notThrows(m('max-buffer', ['stdout', '10'], {maxBuffer: 10}));235});236237test('maxBuffer affects stderr', async t => {238	await t.throws(m('max-buffer', ['stderr', '13'], {maxBuffer: 12}), /stderr maxBuffer exceeded/);239	await t.notThrows(m('max-buffer', ['stderr', '12'], {maxBuffer: 12}));240});241242test('do not buffer stdout when `buffer` set to `false`', async t => {243	const promise = m('max-buffer', ['stdout', '10'], {buffer: false});244	const [result, stdout] = await Promise.all([245		promise,246		getStream(promise.stdout)247	]);248249	t.is(result.stdout, undefined);250	t.is(stdout, '.........\n');251});252253test('do not buffer stderr when `buffer` set to `false`', async t => {254	const promise = m('max-buffer', ['stderr', '10'], {buffer: false});255	const [result, stderr] = await Promise.all([256		promise,257		getStream(promise.stderr)258	]);259260	t.is(result.stderr, undefined);261	t.is(stderr, '.........\n');262});263264test('skip throwing when using reject option', async t => {265	const err = await m('exit', ['2'], {reject: false});266	t.is(typeof err.stdout, 'string');267	t.is(typeof err.stderr, 'string');268});269270test('execa() returns code and failed properties', async t => {271	const {code, failed} = await m('noop', ['foo']);272	const err = await t.throws(m('exit', ['2']));273	t.is(code, 0);274	t.false(failed);275	t.is(err.code, 2);276	t.true(err.failed);277});278279test(`use relative path with '..' chars`, async t => {280	const pathViaParentDir = path.join('..', path.basename(__dirname), 'fixtures', 'noop');281	const {stdout} = await m(pathViaParentDir, ['foo']);282	t.is(stdout, 'foo');283});284285if (process.platform !== 'win32') {286	test('execa() rejects if running non-executable', async t => {287		const cp = m('non-executable');288		await t.throws(cp);289	});290}291292test('err.killed is true if process was killed directly', async t => {293	const cp = m('forever');294295	setTimeout(() => {296		cp.kill();297	}, 100);298299	const err = await t.throws(cp);300301	t.true(err.killed);302});303304// TODO: Should this really be the case, or should we improve on child_process?305test('err.killed is false if process was killed indirectly', async t => {306	const cp = m('forever');307308	setTimeout(() => {309		process.kill(cp.pid, 'SIGINT');310	}, 100);311312	const err = await t.throws(cp);313314	t.false(err.killed);315});316317if (process.platform === 'darwin') {318	test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {319		const cp = childProcess.exec('forever', err => {320			t.truthy(err);321			t.false(err.killed);322			t.end();323		});324325		setTimeout(() => {326			process.kill(cp.pid, 'SIGINT');327		}, 100);328	});329}330331if (process.platform !== 'win32') {332	test('err.signal is SIGINT', async t => {333		const cp = m('forever');334335		setTimeout(() => {336			process.kill(cp.pid, 'SIGINT');337		}, 100);338339		const err = await t.throws(cp);340341		t.is(err.signal, 'SIGINT');342	});343344	test('err.signal is SIGTERM', async t => {345		const cp = m('forever');346347		setTimeout(() => {348			process.kill(cp.pid, 'SIGTERM');349		}, 100);350351		const err = await t.throws(cp);352353		t.is(err.signal, 'SIGTERM');354	});355356	test('custom err.signal', async t => {357		const err = await t.throws(m('delay', ['3000', '0'], {killSignal: 'SIGHUP', timeout: 1500}));358359		t.is(err.signal, 'SIGHUP');360	});361}362363test('result.signal is null for successful execution', async t => {364	t.is((await m('noop')).signal, null);365});366367test('result.signal is null if process failed, but was not killed', async t => {368	const err = await t.throws(m('exit', [2]));369	t.is(err.signal, null);370});371372async function code(t, num) {373	const err = await t.throws(m('exit', [`${num}`]));374375	t.is(err.code, num);376}377378test('err.code is 2', code, 2);379test('err.code is 3', code, 3);380test('err.code is 4', code, 4);381382test('timeout will kill the process early', async t => {383	const err = await t.throws(m('delay', ['60000', '0'], {timeout: 1500}));384385	t.true(err.timedOut);386	t.not(err.code, 22);387});388389test('timeout will not kill the process early', async t => {390	const err = await t.throws(m('delay', ['3000', '22'], {timeout: 30000}));391392	t.false(err.timedOut);393	t.is(err.code, 22);394});395396test('timedOut will be false if no timeout was set and zero exit code', async t => {397	const result = await m('delay', ['1000', '0']);398399	t.false(result.timedOut);400});401402test('timedOut will be false if no timeout was set and non-zero exit code', async t => {403	const err = await t.throws(m('delay', ['1000', '3']));404405	t.false(err.timedOut);406});407408async function errorMessage(t, expected, ...args) {409	const err = await t.throws(m('exit', args));410411	t.regex(err.message, expected);412}413414errorMessage.title = (message, expected) => `err.message matches: ${expected}`;415416test(errorMessage, /Command failed: exit 2 foo bar/, 2, 'foo', 'bar');417test(errorMessage, /Command failed: exit 3 baz quz/, 3, 'baz', 'quz');418419async function cmd(t, expected, ...args) {420	const err = await t.throws(m('fail', args));421422	t.is(err.cmd, `fail${expected}`);423424	const result = await m('noop', args);425426	t.is(result.cmd, `noop${expected}`);427}428429cmd.title = (message, expected) => `cmd is: ${JSON.stringify(expected)}`;430431test(cmd, ' foo bar', 'foo', 'bar');432test(cmd, ' baz quz', 'baz', 'quz');433test(cmd, '');434435async function spawnAndKill(t, signal, cleanup) {436	const name = cleanup ? 'sub-process' : 'sub-process-false';437	const cp = m(name);438	let pid;439440	cp.stdout.setEncoding('utf8');441	cp.stdout.on('data', chunk => {442		pid = parseInt(chunk, 10);443		t.is(typeof pid, 'number');444445		setTimeout(() => {446			process.kill(cp.pid, signal);447		}, 100);448	});449450	await t.throws(cp);451452	// Give everybody some time to breath and kill things453	await delay(200);454455	t.false(isRunning(cp.pid));456	t.is(isRunning(pid), !cleanup);457}458459test('cleanup - SIGINT', spawnAndKill, 'SIGINT', true);460test('cleanup - SIGKILL', spawnAndKill, 'SIGTERM', true);461462if (process.platform !== 'win32') {463	// On Windows the subprocesses are actually always killed464	test('cleanup false - SIGINT', spawnAndKill, 'SIGTERM', false);465	test('cleanup false - SIGKILL', spawnAndKill, 'SIGKILL', false);466}467468// See: https://github.com/sindresorhus/execa/issues/56469const onlyWinFailing = test[process.platform === 'win32' ? 'failing' : 'serial'];470onlyWinFailing('execa.shell() supports the `shell` option', async t => {471	const {stdout} = await m.shell('noop foo', {472		shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/bash'473	});474	t.is(stdout, 'foo');475});476477if (process.platform !== 'win32') {478	test('write to fast-exit process', async t => {479		// Try-catch here is necessary, because this test is not 100% accurate480		// Sometimes process can manage to accept input before exiting481		try {482			await m(`fast-exit-${process.platform}`, [], {input: 'data'});483			t.pass();484		} catch (err) {485			t.is(err.code, 'EPIPE');486		}487	});488}489490test('use environment variables by default', async t => {491	const result = await m.stdout('environment');492493	t.deepEqual(result.split('\n'), [494		'foo',495		'undefined'496	]);497});498499test('extend environment variables by default', async t => {500	const result = await m.stdout('environment', [], {env: {BAR: 'bar'}});501502	t.deepEqual(result.split('\n'), [503		'foo',504		'bar'505	]);506});507508test('do not extend environment with `extendEnv` option', async t => {509	const result = await m.stdout('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});510511	t.deepEqual(result.split('\n'), [512		'undefined',513		'bar'514	]);515});516517test('do not buffer when streaming', async t => {518	const result = await getStream(m('max-buffer', ['stdout', '21'], {maxBuffer: 10}).stdout);519520	t.is(result, '....................\n');521});522523test('detach child process', async t => {524	const file = tempfile('.txt');525526	await m('detach', [file]);527528	await delay(5000);529530	t.is(fs.readFileSync(file, 'utf8'), 'foo\n');531});532533// See #128534test('removes exit handler on exit', async t => {535	// FIXME: This relies on `signal-exit` internals536	const ee = process.__signal_exit_emitter__;537538	const child = m('noop');539	const listener = ee.listeners('exit').pop();540541	await new Promise((resolve, reject) => {542		child.on('error', reject);543		child.on('exit', resolve);544	});545546	const included = ee.listeners('exit').indexOf(listener) !== -1;547	t.false(included);548});