Skip to content
Myr

test.js

This file

Path

test.js

450 lines · 12.3 KiB · JavaScript

Last changed by

Meta tweaksSindre Sorhusbefore adoptionc0fc20c

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});1920test('buffer', async t => {21	const {stdout} = await m('noop', ['foo'], {encoding: null});22	t.true(Buffer.isBuffer(stdout));23	t.is(stdout.toString(), 'foo');24});2526test('execa.stdout()', async t => {27	const stdout = await m.stdout('noop', ['foo']);28	t.is(stdout, 'foo');29});3031test('execa.stderr()', async t => {32	const stderr = await m.stderr('noop-err', ['foo']);33	t.is(stderr, 'foo');34});3536test('stdout/stderr available on errors', async t => {37	const err = await t.throws(m('exit', ['2']));38	t.is(typeof err.stdout, 'string');39	t.is(typeof err.stderr, 'string');40});4142test('include stdout and stderr in errors for improved debugging', async t => {43	const err = await t.throws(m('fixtures/error-message.js'));44	t.regex(err.message, /stdout/);45	t.regex(err.message, /stderr/);46	t.is(err.code, 1);47});4849test('do not include in errors when `stdio` is set to `inherit`', async t => {50	const err = await t.throws(m('fixtures/error-message.js', {stdio: 'inherit'}));51	t.notRegex(err.message, /\n/);52});5354test('do not include `stderr` and `stdout` in errors when set to `inherit`', async t => {55	const err = await t.throws(m('fixtures/error-message.js', {stdout: 'inherit', stderr: 'inherit'}));56	t.notRegex(err.message, /\n/);57});5859test('do not include `stderr` and `stdout` in errors when `stdio` is set to `inherit`', async t => {60	const err = await t.throws(m('fixtures/error-message.js', {stdio: [null, 'inherit', 'inherit']}));61	t.notRegex(err.message, /\n/);62});6364test('do not include `stdout` in errors when set to `inherit`', async t => {65	const err = await t.throws(m('fixtures/error-message.js', {stdout: 'inherit'}));66	t.notRegex(err.message, /stdout/);67	t.regex(err.message, /stderr/);68});6970test('do not include `stderr` in errors when set to `inherit`', async t => {71	const err = await t.throws(m('fixtures/error-message.js', {stderr: 'inherit'}));72	t.regex(err.message, /stdout/);73	t.notRegex(err.message, /stderr/);74});7576test('pass `stdout` to a file descriptor', async t => {77	const file = tempfile('.txt');78	await m('fixtures/noop', ['foo bar'], {stdout: fs.openSync(file, 'w')});79	t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');80});8182test('pass `stderr` to a file descriptor', async t => {83	const file = tempfile('.txt');84	await m('fixtures/noop-err', ['foo bar'], {stderr: fs.openSync(file, 'w')});85	t.is(fs.readFileSync(file, 'utf8'), 'foo bar\n');86});8788test('execa.shell()', async t => {89	const {stdout} = await m.shell('node fixtures/noop foo');90	t.is(stdout, 'foo');91});9293test('execa.spawn()', async t => {94	t.is(typeof m.spawn('noop').pid, 'number');95	t.is((await getStream(m.spawn('noop', ['foo']).stdout)).trim(), 'foo');96});9798test('execa.sync()', t => {99	const {stdout} = m.sync('noop', ['foo']);100	t.is(stdout, 'foo');101});102103test('execa.sync() throws error if written to stderr', t => {104	t.throws(() => m.sync('foo'), process.platform === 'win32' ? /'foo' is not recognized as an internal or external command/ : 'spawnSync foo ENOENT');105});106107test('execa.shellSync()', t => {108	const {stdout} = m.shellSync('node fixtures/noop foo');109	t.is(stdout, 'foo');110});111112test('stripEof option', async t => {113	const {stdout} = await m('noop', ['foo'], {stripEof: false});114	t.is(stdout, 'foo\n');115});116117test.serial('preferLocal option', async t => {118	t.true((await m('cat-names')).stdout.length > 2);119120	if (process.platform === 'win32') {121		// TODO: figure out how to make the below not hang on Windows122		return;123	}124125	// Account for npm adding local binaries to the PATH126	const _path = process.env.PATH;127	process.env.PATH = '';128	await t.throws(m('cat-names', {preferLocal: false}), /spawn .* ENOENT/);129	process.env.PATH = _path;130});131132test('localDir option', async t => {133	const cwd = 'fixtures/local-dir';134	const bin = path.resolve(cwd, 'node_modules/.bin/self-path');135136	await m('npm', ['install', '--no-package-lock'], {cwd});137138	const {stdout} = await m(bin, {localDir: cwd});139140	t.is(path.relative(cwd, stdout), path.normalize('node_modules/self-path'));141});142143test('input option can be a String', async t => {144	const {stdout} = await m('stdin', {input: 'foobar'});145	t.is(stdout, 'foobar');146});147148test('input option can be a Buffer', async t => {149	const {stdout} = await m('stdin', {input: 'testing12'});150	t.is(stdout, 'testing12');151});152153test('input can be a Stream', async t => {154	const s = new stream.PassThrough();155	s.write('howdy');156	s.end();157	const {stdout} = await m('stdin', {input: s});158	t.is(stdout, 'howdy');159});160161test('you can write to child.stdin', async t => {162	const child = m('stdin');163	child.stdin.end('unicorns');164	t.is((await child).stdout, 'unicorns');165});166167test('input option can be a String - sync', t => {168	const {stdout} = m.sync('stdin', {input: 'foobar'});169	t.is(stdout, 'foobar');170});171172test('input option can be a Buffer - sync', t => {173	const {stdout} = m.sync('stdin', {input: Buffer.from('testing12', 'utf8')});174	t.is(stdout, 'testing12');175});176177test('opts.stdout:ignore - stdout will not collect data', async t => {178	const {stdout} = await m('stdin', {179		input: 'hello',180		stdio: [null, 'ignore', null]181	});182	t.is(stdout, null);183});184185test('helpful error trying to provide an input stream in sync mode', t => {186	t.throws(187		() => m.sync('stdin', {input: new stream.PassThrough()}),188		/The `input` option cannot be a stream in sync mode/189	);190});191192test('execa() returns a promise with kill() and pid', t => {193	const promise = m('noop', ['foo']);194	t.is(typeof promise.kill, 'function');195	t.is(typeof promise.pid, 'number');196});197198test('maxBuffer affects stdout', async t => {199	await t.throws(m('max-buffer', ['stdout', '11'], {maxBuffer: 10}), /stdout maxBuffer exceeded/);200	await t.notThrows(m('max-buffer', ['stdout', '10'], {maxBuffer: 10}));201});202203test('maxBuffer affects stderr', async t => {204	await t.throws(m('max-buffer', ['stderr', '13'], {maxBuffer: 12}), /stderr maxBuffer exceeded/);205	await t.notThrows(m('max-buffer', ['stderr', '12'], {maxBuffer: 12}));206});207208test('skip throwing when using reject option', async t => {209	const err = await m('exit', ['2'], {reject: false});210	t.is(typeof err.stdout, 'string');211	t.is(typeof err.stderr, 'string');212});213214test('execa() returns code and failed properties', async t => {215	const {code, failed} = await m('noop', ['foo']);216	const err = await t.throws(m('exit', ['2']));217	t.is(code, 0);218	t.false(failed);219	t.is(err.code, 2);220	t.true(err.failed);221});222223test(`use relative path with '..' chars`, async t => {224	const pathViaParentDir = path.join('..', path.basename(__dirname), 'fixtures', 'noop');225	const {stdout} = await m(pathViaParentDir, ['foo']);226	t.is(stdout, 'foo');227});228229if (process.platform !== 'win32') {230	test('execa() rejects if running non-executable', async t => {231		const cp = m('non-executable');232		await t.throws(cp);233	});234}235236test('err.killed is true if process was killed directly', async t => {237	const cp = m('forever');238239	setTimeout(() => {240		cp.kill();241	}, 100);242243	const err = await t.throws(cp);244245	t.true(err.killed);246});247248// TODO: Should this really be the case, or should we improve on child_process?249test('err.killed is false if process was killed indirectly', async t => {250	const cp = m('forever');251252	setTimeout(() => {253		process.kill(cp.pid, 'SIGINT');254	}, 100);255256	const err = await t.throws(cp);257258	t.false(err.killed);259});260261if (process.platform === 'darwin') {262	test.cb('sanity check: child_process.exec also has killed.false if killed indirectly', t => {263		const cp = childProcess.exec('forever', err => {264			t.truthy(err);265			t.false(err.killed);266			t.end();267		});268269		setTimeout(() => {270			process.kill(cp.pid, 'SIGINT');271		}, 100);272	});273}274275if (process.platform !== 'win32') {276	test('err.signal is SIGINT', async t => {277		const cp = m('forever');278279		setTimeout(() => {280			process.kill(cp.pid, 'SIGINT');281		}, 100);282283		const err = await t.throws(cp);284285		t.is(err.signal, 'SIGINT');286	});287288	test('err.signal is SIGTERM', async t => {289		const cp = m('forever');290291		setTimeout(() => {292			process.kill(cp.pid, 'SIGTERM');293		}, 100);294295		const err = await t.throws(cp);296297		t.is(err.signal, 'SIGTERM');298	});299300	test('custom err.signal', async t => {301		const err = await t.throws(m('delay', ['3000', '0'], {killSignal: 'SIGHUP', timeout: 1500}));302303		t.is(err.signal, 'SIGHUP');304	});305}306307test('result.signal is null for successful execution', async t => {308	t.is((await m('noop')).signal, null);309});310311test('result.signal is null if process failed, but was not killed', async t => {312	const err = await t.throws(m('exit', [2]));313	t.is(err.signal, null);314});315316async function code(t, num) {317	const err = await t.throws(m('exit', [`${num}`]));318319	t.is(err.code, num);320}321322test('err.code is 2', code, 2);323test('err.code is 3', code, 3);324test('err.code is 4', code, 4);325326test('timeout will kill the process early', async t => {327	const err = await t.throws(m('delay', ['3000', '0'], {timeout: 1500}));328329	t.true(err.timedOut);330	t.not(err.code, 22);331});332333test('timeout will not kill the process early', async t => {334	const err = await t.throws(m('delay', ['3000', '22'], {timeout: 9000}));335336	t.false(err.timedOut);337	t.is(err.code, 22);338});339340test('timedOut will be false if no timeout was set and zero exit code', async t => {341	const result = await m('delay', ['1000', '0']);342343	t.false(result.timedOut);344});345346test('timedOut will be false if no timeout was set and non-zero exit code', async t => {347	const err = await t.throws(m('delay', ['1000', '3']));348349	t.false(err.timedOut);350});351352async function errorMessage(t, expected, ...args) {353	const err = await t.throws(m('exit', args));354355	t.regex(err.message, expected);356}357358errorMessage.title = (message, expected) => `err.message matches: ${expected}`;359360test(errorMessage, /Command failed: exit 2 foo bar/, 2, 'foo', 'bar');361test(errorMessage, /Command failed: exit 3 baz quz/, 3, 'baz', 'quz');362363async function cmd(t, expected, ...args) {364	const err = await t.throws(m('fail', args));365366	t.is(err.cmd, `fail${expected}`);367368	const result = await m('noop', args);369370	t.is(result.cmd, `noop${expected}`);371}372373cmd.title = (message, expected) => `cmd is: ${JSON.stringify(expected)}`;374375test(cmd, ' foo bar', 'foo', 'bar');376test(cmd, ' baz quz', 'baz', 'quz');377test(cmd, '');378379async function spawnAndKill(t, signal, cleanup) {380	const name = cleanup ? 'sub-process' : 'sub-process-false';381	const cp = m(name);382	let pid;383384	cp.stdout.setEncoding('utf8');385	cp.stdout.on('data', chunk => {386		pid = parseInt(chunk, 10);387		t.is(typeof pid, 'number');388389		setTimeout(() => {390			process.kill(cp.pid, signal);391		}, 100);392	});393394	await t.throws(cp);395396	// Give everybody some time to breath and kill things397	await delay(200);398399	t.false(isRunning(cp.pid));400	t.is(isRunning(pid), !cleanup);401}402403test('cleanup - SIGINT', spawnAndKill, 'SIGINT', true);404test('cleanup - SIGKILL', spawnAndKill, 'SIGTERM', true);405406if (process.platform !== 'win32') {407	// On Windows the subprocesses are actually always killed408	test('cleanup false - SIGINT', spawnAndKill, 'SIGTERM', false);409	test('cleanup false - SIGKILL', spawnAndKill, 'SIGKILL', false);410}411412// See: https://github.com/sindresorhus/execa/issues/56413const onlyWinFailing = test[process.platform === 'win32' ? 'failing' : 'serial'];414onlyWinFailing('execa.shell() supports the `shell` option', async t => {415	const {stdout} = await m.shell('noop foo', {416		shell: process.platform === 'win32' ? 'cmd.exe' : '/bin/bash'417	});418	t.is(stdout, 'foo');419});420421if (process.platform !== 'win32') {422	test('write to fast-exit process', async t => {423		// Try-catch here is necessary, because this test is not 100% accurate424		// Sometimes process can manage to accept input before exiting425		try {426			await m(`fast-exit-${process.platform}`, [], {input: 'data'});427			t.pass();428		} catch (err) {429			t.is(err.code, 'EPIPE');430		}431	});432}433434test('extend environment variables by default', async t => {435	const result = await m.stdout('environment', [], {env: {BAR: 'bar'}});436437	t.deepEqual(result.split('\n'), [438		'foo',439		'bar'440	]);441});442443test('do not extend environment with `envExtend` option', async t => {444	const result = await m.stdout('environment', [], {env: {BAR: 'bar', PATH: process.env.PATH}, extendEnv: false});445446	t.deepEqual(result.split('\n'), [447		'undefined',448		'bar'449	]);450});