Skip to content
Myr

Fix errors, early errors and `result.all` edge cases

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

authored by Sindre Sorhus · committed by Sindre Sorhus · parent 63ddae6 · Browse files · 15 files+293 added−21 removed
This commit

State

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

Diff stats

15 files+293 added−21 removed

  • tests:+227 added−8 removed
  • other:+66 added−13 removed

15 files+293 added−21 removed

modified:docs/errors.md+1 added-1 removed
modified:lib/methods/main-sync.js+7 added-1 removed
1import {spawnSync} from 'node:child_process';2import {handleCommand} from '../arguments/command.js';3import {normalizeOptions} from '../arguments/options.js';4import {concatenateShell} from '../arguments/shell.js';5import {makeError, makeEarlyError, makeSuccessResult} from '../return/result.js';5import {6 makeError,7 makeEarlyError,8 makeSuccessResult,9 getEarlyErrorOutput,10} from '../return/result.js';11import {handleResult} from '../return/reject.js';12import {handleStdioSync} from '../stdio/handle-sync.js';13import {stripNewline} from '../io/strip-newline.js';14import {addInputOptionsSync} from '../io/input-sync.js';
121 unmodified lines
136 fileDescriptors,137 options,138 startTime,139 isSync: true,140 ...getEarlyErrorOutput(fileDescriptors, options),141 });142 }143};144
31 unmodified lines
modified:lib/resolve/all-sync.js+14 added-3 removed
modified:lib/return/early-error.js+5 added-1 removed
5 unmodified lines
6 Writable,7 Duplex,8} from 'node:stream';9import {cleanupCustomStreams} from '../stdio/handle.js';10import {makeEarlyError} from './result.js';10import {makeEarlyError, getEarlyErrorOutput} from './result.js';11import {handleResult} from './reject.js';1213// When the subprocess fails to spawn.14// We ensure the returned error is always both a promise and a subprocess.
38 unmodified lines
53 });54 return all;55};5657// Writing to an ended stream emits an error, which would crash the current process when the user writes to `subprocess.stdin`.58// Like when the subprocess exits before reading its input, that input is discarded instead.59const createDummyStream = () => {60 const stream = new PassThrough();61 stream.on('error', () => {});62 stream.end();63 return stream;64};65
45 unmodified lines
111 fileDescriptors,112 options,113 startTime,114 isSync: false,115 ...getEarlyErrorOutput(fileDescriptors, options),116 });117 return handleResult(earlyError, verboseInfo, options);118};
modified:lib/return/final-error.js+2 added-1 removed
30 unmodified lines
31export const isExecaError = error => isErrorInstance(error) && execaErrorSymbol in error;3233const execaErrorSymbol = Symbol('isExecaError');3435// `instanceof` handles `DOMException` and subclasses with a custom `Symbol.toStringTag`, `Object.prototype.toString()` handles other realms35export const isErrorInstance = value => Object.prototype.toString.call(value) === '[object Error]';36export const isErrorInstance = value => value instanceof Error || Object.prototype.toString.call(value) === '[object Error]';3738// We use two different Error classes for async/sync methods since they have slightly different shape and types39export class ExecaError extends Error {}40// eslint-disable-next-line unicorn/no-top-level-side-effects -- `error.name` must be set as soon as the class is defined
5 unmodified lines
modified:lib/return/message.js+10 added-3 removed
26 unmodified lines
27 maxBuffer,28 timeout,29 cwd,30}) => {31 const errorCode = originalError?.code;31 const errorCode = getErrorCode(originalError);32 const prefix = getErrorPrefix({33 originalError,34 timedOut,35 timeout,
24 unmodified lines
60 .join('\n\n');61 return {originalMessage, shortMessage, message};62};6364// `DOMException`, e.g. the default `cancelSignal` reason, has a legacy numeric `code`, which is not an error code like `ENOENT`65export const getErrorCode = error => typeof error?.code === 'string' ? error.code : undefined;6667const getErrorPrefix = ({68 originalError,69 timedOut,70 timeout,
56 unmodified lines
127 if (originalError instanceof DiscardedError) {128 return;129 }130131 // An `ExecaError` has no `originalMessage` when it was not caused by another error, e.g. with a non-zero exit code132 const originalMessage = isExecaError(originalError)129 ? originalError.originalMessage133 ? originalError.originalMessage ?? ''134 : String(originalError?.message ?? originalError);135 const escapedOriginalMessage = escapeLines(fixCwdError(originalMessage, cwd));136 return escapedOriginalMessage === '' ? undefined : escapedOriginalMessage;137};
1 unmodified line
139const serializeIpcMessage = ipcMessage => typeof ipcMessage === 'string'140 ? ipcMessage141 : inspect(ipcMessage);142143// With the `lines` option, empty lines are kept. Only objects are omitted.144const serializeMessagePart = messagePart => Array.isArray(messagePart)140 ? messagePart.map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).filter(Boolean).join('\n')145 ? messagePart.filter(messageItem => isTextItem(messageItem)).map(messageItem => stripFinalNewline(serializeMessageItem(messageItem))).join('\n')146 : serializeMessageItem(messagePart);147148const isTextItem = messageItem => typeof messageItem === 'string' || isUint8Array(messageItem);149150const serializeMessageItem = messageItem => {151 if (typeof messageItem === 'string') {152 return messageItem;153 }
3 unmodified lines
modified:lib/return/result.js+27 added-3 removed
1import {getSignalDescription} from '../terminate/signal.js';2import {getAllSync, getAllSyncFds} from '../resolve/all-sync.js';3import {getDurationMs} from './duration.js';4import {getFinalError} from './final-error.js';4import {createMessages} from './message.js';5import {createMessages, getErrorCode} from './message.js';67// Object returned on subprocess success8export const makeSuccessResult = ({9 command,
32 unmodified lines
42 fileDescriptors,43 options,44 startTime,45 isSync,46 stdio = Array.from({length: fileDescriptors.length}),47 all,48}) => makeError({49 error,50 command,51 escapedCommand,
2 unmodified lines
54 isCanceled: false,55 isGracefullyCanceled: false,56 isMaxBuffer: false,57 isForcefullyTerminated: false,55 stdio: Array.from({length: fileDescriptors.length}),58 stdio,59 all,60 ipcOutput: [],61 options,62 isSync,63});6465// When the subprocess fails to spawn, its output is empty, with the same shape as when it spawns but prints nothing66export const getEarlyErrorOutput = (fileDescriptors, options) => {67 const stdio = fileDescriptors.map((fileDescriptor, fdNumber) => getEmptyOutput(fileDescriptor, fdNumber, options));68 return {stdio, all: getAllSync(stdio, getAllSyncFds(stdio), options)};69};7071const getEmptyOutput = ({direction, objectMode}, fdNumber, {stdio, buffer, lines, encoding}) => {72 if (direction === 'input' || !PIPED_STDIO.has(stdio[fdNumber]) || !buffer[fdNumber]) {73 return;74 }7576 if (objectMode || lines[fdNumber]) {77 return [];78 }7980 return encoding === 'buffer' ? new Uint8Array() : '';81};8283const PIPED_STDIO = new Set(['pipe', 'overlapped']);8485// Object returned on subprocess failure86export const makeError = ({87 error: originalError,88 command,
99 unmodified lines
188 isForcefullyTerminated,189 exitCode,190 signal,191 signalDescription,168 code: error.cause?.code,192 code: getErrorCode(error.cause),193 stdout: stdio[1],194 stderr: stdio[2],195 all,196 stdio,
14 unmodified lines
modified:test/resolve/all.js+42 added-1 removed
1import {Buffer} from 'node:buffer';2import assert from 'node:assert/strict';3import test from 'node:test';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {defaultHighWaterMark} from '../helpers/stream.js';6import {foobarString} from '../helpers/input.js';7import {foobarString, foobarObject} from '../helpers/input.js';8import {outputObjectGenerator} from '../helpers/generator.js';910setFixtureDirectory();1112const textEncoder = new TextEncoder();
18 unmodified lines
31 assert.equal(exitCode, isFailure ? 1 : 0);32 assert.deepEqual(all, expectedOutput);33};3435// With encodings like base64, the bytes must be merged before being encoded, otherwise the padding of the first output would end up in the middle36const testAllBinaryEncoding = (encoding, execaMethod) => testAllBoth(Buffer.from(doubleFoobarStringFull).toString(encoding), encoding, false, false, false, execaMethod);3738test('result.all is defined, encoding "base64"', () => testAllBinaryEncoding('base64', execa));39test('result.all is defined, encoding "base64url"', () => testAllBinaryEncoding('base64url', execa));40test('result.all is defined, encoding "hex"', () => testAllBinaryEncoding('hex', execa));41test('result.all is defined, encoding "latin1"', () => testAllBinaryEncoding('latin1', execa));42test('result.all is defined, encoding "base64", sync', () => testAllBinaryEncoding('base64', execaSync));43test('result.all is defined, encoding "base64url", sync', () => testAllBinaryEncoding('base64url', execaSync));44test('result.all is defined, encoding "hex", sync', () => testAllBinaryEncoding('hex', execaSync));45test('result.all is defined, encoding "latin1", sync', () => testAllBinaryEncoding('latin1', execaSync));4647// An empty output is not interleaved with the objects of the other file descriptor48const testAllObjectModeEmpty = async (fixtureName, commandArguments, options, expectedAll) => {49 const {all} = await execa(fixtureName, commandArguments, {...options, all: true});50 assert.deepEqual(all, expectedAll);51 const {all: allSync} = execaSync(fixtureName, commandArguments, {...options, all: true});52 assert.deepEqual(allSync, expectedAll);53};5455test('result.all omits empty stderr with objectMode stdout', () => testAllObjectModeEmpty('noop.js', [foobarString], {stdout: outputObjectGenerator()}, [foobarObject]));56test('result.all omits empty stdout with objectMode stderr', () => testAllObjectModeEmpty('noop-fd.js', ['2', foobarString], {stderr: outputObjectGenerator()}, [foobarObject]));57test('result.all omits empty stderr with objectMode stdout, encoding "buffer"', () => testAllObjectModeEmpty('noop.js', [foobarString], {stdout: outputObjectGenerator(), encoding: 'buffer'}, [foobarObject]));58test('result.all keeps non-empty stderr with objectMode stdout', () => testAllObjectModeEmpty('noop-both.js', [foobarString], {stdout: outputObjectGenerator()}, [foobarObject, `${foobarString}\n`]));5960const fdOne = {stderr: true};61const fdBoth = {stdout: true, stderr: true};6263test('result.all is defined', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, false, execa));
203 unmodified lines
267test('result.all is undefined when no file descriptor is buffered', () => testAllNoFd(false, execa));268test('result.all is undefined when no file descriptor is buffered, lines', () => testAllNoFd(true, execa));269test('result.all is undefined when no file descriptor is buffered, sync', () => testAllNoFd(false, execaSync));270test('result.all is undefined when no file descriptor is buffered, lines, sync', () => testAllNoFd(true, execaSync));271272const testUtf16LinesAll = async execaMethod => {273 const script = 'process.stdout.write(Buffer.from(\'a\\r\\nb\\n\', \'utf16le\')); process.stderr.write(Buffer.from(\'c\\n\', \'utf16le\'))';274 const {all} = await execaMethod('node', ['-e', script], {275 all: true,276 lines: true,277 encoding: 'utf16le',278 stripFinalNewline: false,279 });280 assert.deepEqual(all, ['a\r\n', 'b\n', 'c\n']);281};282283test('result.all splits lines with utf16le encoding', () => testUtf16LinesAll(execa));284test('result.all splits lines with utf16le encoding, sync', () => testUtf16LinesAll(execaSync));
modified:test/return/early-error.js+62 added-1 removed
1 unmodified line
2import {arch} from 'node:os';3import process from 'node:process';4import {once} from 'node:events';5import {finished} from 'node:stream/promises';6import {setImmediate} from 'node:timers/promises';7import test from 'node:test';8import {assertThrows, assertRejects} from '../helpers/assert.js';9import {10 execa,
4 unmodified lines
15} from '../../index.js';16import {setFixtureDirectory} from '../helpers/fixtures-directory.js';17import {foobarString, foobarUint8Array} from '../helpers/input.js';18import {fullStdio} from '../helpers/stdio.js';18import {getOutputGenerator, convertTransformToFinal} from '../helpers/generator.js';19import {getOutputGenerator, convertTransformToFinal, noopGenerator} from '../helpers/generator.js';20import {21 earlyErrorOptions,22 getEarlyErrorSubprocess,23 getEarlyErrorSubprocessSync,
39 unmodified lines
63test('execaSync() output is undefined when the command does not exist, with buffer: false', () => testSpawnFailureOutput({buffer: false}));64test('execaSync() output is empty when the cwd does not exist', () => testSpawnFailureOutput({cwd: '/nonexistent-directory-for-execa'}));65test('execaSync() output runs the final of transforms when the command does not exist', () => testSpawnFailureOutput({stdout: convertTransformToFinal(getOutputGenerator(foobarString)(), true)}));6667// When `child_process.spawn()` throws, the output must be the same as when the subprocess spawns and fails right away68const testEarlyErrorOutput = async options => {69 const {stdio, all} = await execa('nonexistent-command-for-execa', {...options, reject: false});70 const earlyError = await getEarlyErrorSubprocess({...options, reject: false});71 assert.deepEqual(earlyError.stdio, stdio);72 assert.deepEqual(earlyError.all, all);73 assert.deepEqual(earlyError.stdout, stdio[1]);74 assert.deepEqual(earlyError.stderr, stdio[2]);75 const earlyErrorSync = getEarlyErrorSubprocessSync({...options, reject: false});76 assert.deepEqual(earlyErrorSync.stdio, stdio);77 assert.deepEqual(earlyErrorSync.all, all);78};7980test('Early errors output is empty', () => testEarlyErrorOutput({}));81test('Early errors output is empty, with encoding: buffer', () => testEarlyErrorOutput({encoding: 'buffer'}));82test('Early errors output is empty, with encoding: hex', () => testEarlyErrorOutput({encoding: 'hex'}));83test('Early errors output is empty, with lines: true', () => testEarlyErrorOutput({lines: true}));84test('Early errors output is empty, with lines: true and encoding: buffer', () => testEarlyErrorOutput({lines: true, encoding: 'buffer'}));85test('Early errors output is empty, with all: true', () => testEarlyErrorOutput({all: true}));86test('Early errors output is empty, with all: true and lines: true', () => testEarlyErrorOutput({all: true, lines: true}));87test('Early errors output is empty, with all: true and encoding: buffer', () => testEarlyErrorOutput({all: true, encoding: 'buffer'}));88test('Early errors output is empty, with an additional file descriptor', () => testEarlyErrorOutput(fullStdio));89test('Early errors output is empty, with an object mode transform', () => testEarlyErrorOutput({stdout: noopGenerator(true)}));90test('Early errors output is empty, with an object mode transform and all: true', () => testEarlyErrorOutput({stdout: noopGenerator(true), all: true}));91test('Early errors output is undefined, with stdout: ignore', () => testEarlyErrorOutput({stdout: 'ignore'}));92test('Early errors output is undefined, with stdout: inherit', () => testEarlyErrorOutput({stdout: 'inherit', all: true}));93test('Early errors output is undefined, with buffer: false', () => testEarlyErrorOutput({buffer: false}));94test('Early errors output is undefined, with buffer.stdout: false', () => testEarlyErrorOutput({buffer: {stdout: false}, all: true}));9596test('Early errors output is empty, with inputFile, sync', () => {97 const {stdout, stderr, stdio} = execaSync('stdin.js', {inputFile: 'does_not_exist', reject: false});98 assert.equal(stdout, '');99 assert.equal(stderr, '');100 assert.deepEqual(stdio, [undefined, '', '']);101});102103const testEarlyErrorShape = async reject => {104 const subprocess = getEarlyErrorSubprocess({reject});105 assert.doesNotThrow(() => {106 subprocess.catch(() => {});
215 unmodified lines
322test('child_process.spawn() early errors can use .stdio[1]', () => testEarlyErrorStream(({stdio}) => stdio[1]));323test('child_process.spawn() early errors can use .stdio[3]', () => testEarlyErrorStream(({stdio}) => stdio[3], fullStdio));324test('child_process.spawn() early errors can use .all', () => testEarlyErrorStream(({all}) => all, {all: true}));325326// The subprocess never spawned, so the input is discarded, like when the subprocess exits before reading it327const testEarlyErrorWrite = async (getStreamProperty, options) => {328 const subprocess = getEarlyErrorSubprocess(options);329 const stream = getStreamProperty(subprocess);330 stream.write(foobarString);331 stream.end(foobarString);332 await assertRejects(subprocess, expectedEarlyError);333 // Write errors are emitted asynchronously334 await setImmediate();335};336337test('child_process.spawn() early errors can write to .stdin', () => testEarlyErrorWrite(({stdin}) => stdin));338test('child_process.spawn() early errors can write to .stdio[0]', () => testEarlyErrorWrite(({stdio}) => stdio[0]));339test('child_process.spawn() early errors can write to .stdio[3]', () => testEarlyErrorWrite(({stdio}) => stdio[3], {stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}]}));340341test('child_process.spawn() early errors call the .stdin write callback', async () => {342 const subprocess = getEarlyErrorSubprocess();343 const {promise, resolve} = Promise.withResolvers();344 subprocess.stdin.write(foobarString, resolve);345 const error = await promise;346 assert.equal(error.code, 'ERR_STREAM_WRITE_AFTER_END');347 await assertRejects(subprocess, expectedEarlyError);348});349350// Reading the `inputFile` happens after the file descriptors are set up, so a missing file is reported as an early error, like with asynchronous methods351test('inputFile which does not exist is an early error', async () => {352 const error = await assertRejects(execa('stdin.js', {inputFile: 'does_not_exist'}));353 assert.ok(error instanceof ExecaError);
10 unmodified lines
modified:test/return/final-error.js+49 added
108 unmodified lines
109 assert.equal(error.signal, 'SIGTERM');110 assert.equal(error.cause, cause);111});112113// An `ExecaError` from a non-zero exit code has no `error.originalMessage`114test('error.cause can be an ExecaError without originalMessage, with .kill(error)', async () => {115 const previousError = await assertRejects(execa('fail.js'));116 assert.equal(previousError.originalMessage, undefined);117 const subprocess = execa('forever.js');118 subprocess.kill(previousError);119 const error = await assertRejects(subprocess);120 assert.equal(error.cause, previousError);121 assert.equal(error.isTerminated, true);122 assert.equal(error.originalMessage, undefined);123 assert.equal(error.shortMessage, 'Command was killed with SIGTERM (Termination): forever.js');124});125126test('error.cause can be an ExecaError without originalMessage, with cancelSignal', async () => {127 const previousError = await assertRejects(execa('fail.js'));128 const controller = new AbortController();129 const subprocess = execa('forever.js', {cancelSignal: controller.signal});130 controller.abort(previousError);131 const error = await assertRejects(subprocess);132 assert.equal(error.cause, previousError);133 assert.equal(error.isCanceled, true);134 assert.equal(error.originalMessage, undefined);135 assert.equal(error.shortMessage, 'Command was canceled: forever.js');136});137138const testExecaErrorTransform = async execaMethod => {139 const transform = function * (line) {140 execaSync('fail.js');141 yield line;142 };143144 const error = await execaMethod('noop.js', [foobarString], {stdout: transform, reject: false});145 assert.ok(error.cause instanceof ExecaSyncError);146 assert.equal(error.originalMessage, undefined);147 assert.ok(error.shortMessage.endsWith(`: noop.js ${foobarString}`));148};149150test('error.cause can be an ExecaError without originalMessage, thrown by a transform', () => testExecaErrorTransform(execa));151test('error.cause can be an ExecaError without originalMessage, thrown by a transform, sync', () => testExecaErrorTransform(execaSync));152153test('error.code is not set to the numeric code of the default cancelSignal reason', async () => {154 const controller = new AbortController();155 const subprocess = execa('forever.js', {cancelSignal: controller.signal});156 controller.abort();157 const error = await assertRejects(subprocess);158 assert.equal(error.cause.name, 'AbortError');159 assert.equal(error.code, undefined);160});161162test('error.cause is not set if error.isTerminated with .kill(error)', async () => {163 const subprocess = execa('forever.js');164 const error = new Error('test');165 subprocess.kill(error);
50 unmodified lines
modified:test/return/message.js+15 added
61 unmodified lines
62test('error.message handles "lines: true", stripFinalNewline, sync', () => testLinesMessage('utf8', true, execaSync));63test('error.message handles "lines: true", buffer, sync', () => testLinesMessage('buffer', false, execaSync));64test('error.message handles "lines: true", buffer, stripFinalNewline, sync', () => testLinesMessage('buffer', true, execaSync));6566// `lines: true` must not change `error.message`, including its empty lines67const testLinesMessageEmptyLines = async (output, stripFinalNewline, execaMethod) => {68 const options = {stripFinalNewline, reject: false};69 const {message} = await execaMethod('noop-fail.js', ['1', output], options);70 const {message: linesMessage} = await execaMethod('noop-fail.js', ['1', output], {...options, lines: true});71 assert.equal(linesMessage, message);72};7374test('error.message keeps empty lines with "lines: true"', () => testLinesMessageEmptyLines(`${foobarString}\n\n${foobarString}\n`, true, execa));75test('error.message keeps empty lines with "lines: true", stripFinalNewline false', () => testLinesMessageEmptyLines(`${foobarString}\n\n${foobarString}\n`, false, execa));76test('error.message keeps several empty lines with "lines: true"', () => testLinesMessageEmptyLines(`${foobarString}\n\n\n\n${foobarString}`, true, execa));77test('error.message keeps leading empty lines with "lines: true"', () => testLinesMessageEmptyLines(`\n\n${foobarString}`, true, execa));78test('error.message keeps empty lines with "lines: true", sync', () => testLinesMessageEmptyLines(`${foobarString}\n\n${foobarString}\n`, true, execaSync));79test('error.message keeps empty lines with "lines: true", stripFinalNewline false, sync', () => testLinesMessageEmptyLines(`${foobarString}\n\n${foobarString}\n`, false, execaSync));8081const testPartialIgnoreMessage = async (fdNumber, stdioOption, output) => {82 const {message} = await assertRejects(execa('echo-fail.js', getStdio(fdNumber, stdioOption, 4)));83 assert.ok(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));84};
51 unmodified lines
modified:test/return/output.js+5 added-4 removed
89 unmodified lines
90 const {stdio} = await assertRejects(execa('fail.js', {input: 'test'}));91 assert.equal(stdio[0], undefined);92});9394// The subprocess never spawned, so its output is empty95const validateSpawnErrorStdio = ({stdout, stderr, stdio, all}) => {95 assert.equal(stdout, undefined);96 assert.equal(stderr, undefined);97 assert.equal(all, undefined);98 assert.deepEqual(stdio, [undefined, undefined, undefined]);96 assert.equal(stdout, '');97 assert.equal(stderr, '');98 assert.equal(all, '');99 assert.deepEqual(stdio, [undefined, '', '']);100};101102test('stdout/stderr/all/stdio on subprocess spawning errors', async () => {103 const error = await assertRejects(getEarlyErrorSubprocess({all: true}));
35 unmodified lines
modified:test/stdio/lines-main.js+5 added
106 unmodified lines
107 const error = await assertRejects(subprocess);108 assert.equal(error.cause, cause);109 assert.deepEqual(error.stdout, []);110});111112test('"lines: true" keeps the trailing carriage return of an unterminated final line', () => testStreamLines(1, 'a\r\nb\r', ['a', 'b\r'], true, true, execa));113test('"lines: true" keeps the trailing carriage return of an unterminated final line, sync', () => testStreamLines(1, 'a\r\nb\r', ['a', 'b\r'], true, true, execaSync));114test('"lines: true" keeps newlines of an unterminated final line', () => testStreamLines(1, 'a\r\nb\r', ['a\r\n', 'b\r'], true, false, execa));115test('"lines: true" keeps newlines of an unterminated final line, sync', () => testStreamLines(1, 'a\r\nb\r', ['a\r\n', 'b\r'], true, false, execaSync));
modified:test/terminate/kill-error.js+46 added
4 unmodified lines
5import isRunning from 'is-running';6import {assertRejects} from '../helpers/assert.js';7import {execa} from '../../index.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9import {foobarString} from '../helpers/input.js';1011setFixtureDirectory();1213test('.kill(error) propagates error', async () => {
29 unmodified lines
43 assert.equal(error.cause, cause);44 assert.equal(error.signal, 'SIGINT');45});4647// Their `Object.prototype.toString()` is not `[object Error]`48class TaggedError extends Error {49 get [Symbol.toStringTag]() {50 return 'TaggedError';51 }52}5354const testKillErrorSubclass = async cause => {55 const subprocess = execa('forever.js');56 assert.ok(subprocess.kill(cause));57 const error = await assertRejects(subprocess);58 assert.equal(error.cause, cause);59 assert.equal(error.signal, 'SIGTERM');60 assert.equal(error.originalMessage, cause.message);61 assert.ok(error.shortMessage.startsWith('Command was killed with SIGTERM'));62 return error;63};6465test('.kill(error) works with DOMException', async () => {66 const error = await testKillErrorSubclass(AbortSignal.abort().reason);67 // `DOMException` has a legacy numeric `code`, which is not an error code like `ENOENT`68 assert.equal(error.code, undefined);69});7071test('.kill(error) works with Error subclasses with a custom Symbol.toStringTag', () => testKillErrorSubclass(new TaggedError('test')));7273test('.kill(error) ignores numeric error codes', async () => {74 const error = await testKillErrorSubclass(Object.assign(new Error('test'), {code: 42}));75 assert.equal(error.code, undefined);76 assert.ok(!error.shortMessage.includes('42'));77});7879test('.kill(error) keeps string error codes', async () => {80 const subprocess = execa('forever.js');81 subprocess.kill(Object.assign(new Error('test'), {code: 'ECUSTOM'}));82 const error = await assertRejects(subprocess);83 assert.equal(error.code, 'ECUSTOM');84});8586test('.kill(error) is a noop if subprocess already exited', async () => {87 const subprocess = execa('empty.js');88 await subprocess;89 assert.ok(!isRunning(subprocess.pid));
32 unmodified lines
122 subprocess.kill(cause);123 const error = await Promise.race([assertRejects(subprocess), once(subprocess.nodeChildProcess, 'error')]);124 assert.equal(error.cause, cause);125});126127test('.kill(error) returns false once the subprocess has settled', async () => {128 const subprocess = execa('noop.js', [foobarString]);129 await subprocess;130 assert.ok(!subprocess.kill(new Error('test')));131});
modified:test/verbose/custom-result.js+3 added-2 removed
42 unmodified lines
43 const result = JSON.parse(lastLine);44 assertLike(result, expectedOutput);45 assert.equal(result.failed, true);46 assert.equal(result.exitCode, undefined);47 assert.equal(result.stdout, undefined);48 assert.equal(result.stderr, undefined);47 // The subprocess never spawned, so its output is empty48 assert.equal(result.stdout, '');49 assert.equal(result.stderr, '');50 assert.equal(typeof result.durationMs, 'number');51 assert.deepEqual(result.ipcOutput, []);52};53
25 unmodified lines