Skip to content
Myr

Tweaks

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 8d3f0a9 · Browse files · 208 files+7971 added−7569 removed
This commit

State

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

Diff stats

208 files+7971 added−7569 removed

  • tests:+7797 added−7331 removed
  • other:+174 added−238 removed

208 files+7971 added−7569 removed

This commit is too large to show whole: its files are listed by path, without their changes.

modified:docs/api.md+2 added-2 removed
890 unmodified lines
891_Type:_ `boolean`\892_Default:_ `true`893894If `true`, the subprocess uses both the [`env`](#optionsenv) option and the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).895If `false`, only the `env` option is used, not `process.env`.895If `false`, only the `env` option is used, not `process.env`. However, when `env` has no `PATH`, the [`preferLocal`](#optionspreferlocal) and [`node`](#optionsnode) options still add their directories to `process.env.PATH`.896897[More info.](input.md#environment-variables)898899### options.input
282 unmodified lines
1182This is useful when the subprocess spawns its own processes, such as when using the [`shell`](#optionsshell) option.11831184On Unix, this spawns the subprocess in its own [process group](https://en.wikipedia.org/wiki/Process_group). On Windows, this uses [`taskkill`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill).11851186This is best-effort: descendant processes that create their own process group or session are not terminated. Also, descendants are not terminated once Execa is done with the subprocess, or on Windows once the subprocess exited, since its PID might then belong to an unrelated process.1186This is best-effort: descendant processes that create their own process group or session are not terminated. Also, on Windows, descendants are not terminated once the subprocess exited, since its PID might then belong to an unrelated process.11871188[More info.](termination.md#killing-descendant-processes)11891190### options.uid
175 unmodified lines
modified:docs/debugging.md+1 added-1 removed
114 unmodified lines
115It is called once per log line. The first argument is the default log line string. The second argument is the same information but as an object instead (documented [here](api.md#verbose-object)).116117If a string is returned, it is printed on `stderr`. If `undefined` is returned, nothing is printed.118119If the function throws, the subprocess fails with that error as [`error.cause`](api.md#errorcause). If it threw while logging the output of [`stdout`](api.md#resultstdout), [`stderr`](api.md#resultstderr) or another file descriptor, that file descriptor's output is then not kept.119If the function throws, the subprocess fails with that error as [`error.cause`](api.md#errorcause). If it threw while logging the output of [`stdout`](api.md#resultstdout), [`stderr`](api.md#resultstderr) or another file descriptor, that file descriptor's output is then not kept, except with [synchronous methods](execution.md#synchronous-execution).120121### Filter logs122123```js
81 unmodified lines
modified:docs/execution.md+1 added-1 removed
157 unmodified lines
158- Signal termination: [`subprocess.kill()`](api.md#subprocesskillerror), [`subprocess.pid`](api.md#subprocesspid), [`cleanup`](api.md#optionscleanup) option, [`cancelSignal`](api.md#optionscancelsignal) option, [`forceKillAfterDelay`](api.md#optionsforcekillafterdelay) option.159- Piping multiple subprocesses: [`subprocess.pipe()`](api.md#subprocesspipefile-arguments-options).160- [`subprocess.iterable()`](lines.md#progressive-splitting).161- [IPC](ipc.md): [`sendMessage()`](api.md#sendmessagemessage-sendmessageoptions), [`getOneMessage()`](api.md#getonemessagegetonemessageoptions), [`getEachMessage()`](api.md#geteachmessagegeteachmessageoptions), [`result.ipcOutput`](output.md#any-output-type), [`ipc`](api.md#optionsipc) option, [`serialization`](api.md#optionsserialization) option, [`ipcInput`](input.md#any-input-type) option.162- [`result.all`](api.md#resultall) is not interleaved.162- [`result.all`](api.md#resultall) is not interleaved. Also, with the [`lines`](api.md#optionslines) option, a file descriptor that uses it keeps its own [`stripFinalNewline`](api.md#optionsstripfinalnewline) value in `result.all`.163- [`detached`](api.md#optionsdetached) option.164- The [`maxBuffer`](api.md#optionsmaxbuffer) option is always measured in bytes, not in characters, [lines](api.md#optionslines) nor [objects](transform.md#object-mode). Also, it ignores transforms and the [`encoding`](api.md#optionsencoding) option, and the `maxBuffer.stdout` value limits the total output of all file descriptors.165166<hr>
3 unmodified lines
modified:docs/termination.md+1 added-1 removed
207 unmodified lines
208```209210On Unix, this spawns the subprocess in its own [process group](https://en.wikipedia.org/wiki/Process_group), then sends the signal to that group. On Windows, this uses [`taskkill`](https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/taskkill), which terminates the process tree tracked by the OS.211212This is best-effort. On Unix, descendant processes that create their own process group or session (for example, daemons calling [`setsid()`](https://man7.org/linux/man-pages/man2/setsid.2.html)) escape termination. On Unix, because the subprocess runs in its own process group, it is also detached from the terminal, so pressing `CTRL-C` no longer forwards [`SIGINT`](#sigint) to it. Finally, the OS can re-assign the subprocess' PID to an unrelated process once it exited. So, descendants are not signaled anymore once Execa is done with the subprocess, i.e. once its promise has settled. On Windows, this applies as soon as the subprocess exited, which also prevents the [`forceKillAfterDelay`](#forceful-termination) escalation from terminating its descendants.212This is best-effort. On Unix, descendant processes that create their own process group or session (for example, daemons calling [`setsid()`](https://man7.org/linux/man-pages/man2/setsid.2.html)) escape termination. On Unix, because the subprocess runs in its own process group, it is also detached from the terminal, so pressing `CTRL-C` no longer forwards [`SIGINT`](#sigint) to it. Finally, the OS can re-assign the subprocess' PID to an unrelated process once it is not used anymore. On Unix, this only happens once every process in its group exited, so calling [`subprocess.kill()`](api.md#subprocesskillsignal-error) at that point might, in rare cases, signal an unrelated process group. On Windows, this happens as soon as the subprocess exited, so descendants are not signaled anymore at that point, which also prevents the [`forceKillAfterDelay`](#forceful-termination) escalation from terminating them.213214This option cannot be used with [synchronous methods](execution.md#synchronous-execution).215216## Signal termination
163 unmodified lines
modified:lib/arguments/command-file.js+2 added-6 removed
10 unmodified lines
11 // The arguments are cloned since a shebang interpreter might be prepended below, which must not mutate the caller's array12 const parsed = {file, commandArguments: [...commandArguments], options};1314 // Under a shell, or on Unix, the OS resolves the file and escapes the arguments itself15 if (options.shell || process.platform !== 'win32') {16 return parsed;17 }1819 return escapeWindowsCommand(parsed);15 return options.shell || process.platform !== 'win32' ? parsed : escapeWindowsCommand(parsed);16};1718// Only `.exe` and `.com` files can be spawned directly; anything else needs `cmd.exe`19const directlyExecutableRegExp = /\.(?:com|exe)$/i;
131 unmodified lines
151 if (!shebangLine) {152 return undefined;153 }154159 const [interpreterPath, argument] = shebangLine.split(' ');155 const [interpreterPath, argument] = shebangLine.split(' ', 2);156 const interpreter = interpreterPath.split('/').at(-1);157 if (interpreter === 'env') {158 return argument;159 }
41 unmodified lines
modified:lib/arguments/cwd.js+1 added-5 removed
37 unmodified lines
38 } catch (error) {39 return `The "cwd" option is invalid: ${cwd}.\n${error.message}\n${originalMessage}`;40 }4142 if (!cwdStat.isDirectory()) {43 return `The "cwd" option is not a directory: ${cwd}.\n${originalMessage}`;42 return cwdStat.isDirectory() ? originalMessage : `The "cwd" option is not a directory: ${cwd}.\n${originalMessage}`;44 }4546 return originalMessage;43};
modified:lib/arguments/fd-options.js+3 added-7 removed
56 unmodified lines
57 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.58Please set the "stdio" option to ensure that file descriptor exists.`);59 }6061 if (fileDescriptor.direction === 'input' && !isWritable) {61 if (!isWritable && fileDescriptor.direction === 'input') {62 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a readable stream, not writable.`);63 }6465 if (fileDescriptor.direction !== 'input' && isWritable) {65 if (isWritable && fileDescriptor.direction !== 'input') {66 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. It must be a writable stream, not readable.67If you meant to use it as input, please set its "stdio" option to \`{value: 'pipe', input: true}\`.`);68 }69};
18 unmodified lines
88 if (usedDescriptor === 1 && stdout !== undefined) {89 return {optionName: 'stdout', optionValue: stdout};90 }9192 if (usedDescriptor === 2 && stderr !== undefined) {93 return {optionName: 'stderr', optionValue: stderr};94 }9596 return {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};92 return usedDescriptor === 2 && stderr !== undefined ? {optionName: 'stderr', optionValue: stderr} : {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};93};9495const getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;96
9 unmodified lines
modified:lib/arguments/options.js+1 added
110 unmodified lines
111 }112113 return env;114};115
modified:lib/convert/duplex.js+2 added-2 removed
1import {Duplex} from 'node:stream';2import {callbackify} from 'node:util';3import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4import {copyOptions} from '../utils/options.js';5import {6 getSubprocessStdout,7 getReadableOptions,8 getReadableMethods,
8 unmodified lines
17} from './writable.js';1819// Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`20export const createDuplex = ({subprocess, concurrentStreams, encoding}, options) => {20 // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values21 const {from, to, binary: binaryOption = true, preserveNewlines = true} = {__proto__: null, ...options};21 const {from, to, binary: binaryOption = true, preserveNewlines = true} = copyOptions(options);22 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);23 const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);24 const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);25 const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);
46 unmodified lines
modified:lib/convert/iterable.js+2 added-2 removed
1import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';2import {getFromStream} from '../arguments/fd-options.js';3import {iterateOnSubprocessStream} from '../io/iterate.js';4import {copyOptions} from '../utils/options.js';56// Convert the subprocess to an async iterable7export const createIterable = (subprocess, encoding, options) => {7 // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values8 const {from, binary: binaryOption = false, preserveNewlines = false} = {__proto__: null, ...options};8 const {from, binary: binaryOption = false, preserveNewlines = false} = copyOptions(options);9 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);10 const subprocessStdout = getFromStream(subprocess, from);11 const onStdoutData = iterateOnSubprocessStream({12 subprocessStdout,
20 unmodified lines
modified:lib/convert/readable.js+2 added-2 removed
2 unmodified lines
3import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4import {getFromStream} from '../arguments/fd-options.js';5import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from '../io/iterate.js';6import {createDeferred} from '../utils/deferred.js';7import {copyOptions} from '../utils/options.js';8import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';9import {10 safeWaitForSubprocessStdin,11 waitForSubprocessStdout,
2 unmodified lines
14} from './shared.js';1516// Create a `Readable` stream that forwards from `stdout` and awaits the subprocess17export const createReadable = ({subprocess, concurrentStreams, encoding}, options) => {17 // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values18 const {from, binary: binaryOption = true, preserveNewlines = true} = {__proto__: null, ...options};18 const {from, binary: binaryOption = true, preserveNewlines = true} = copyOptions(options);19 const binary = binaryOption || BINARY_ENCODINGS.has(encoding);20 const {subprocessStdout, waitReadableDestroy} = getSubprocessStdout(subprocess, from, concurrentStreams);21 const {readableEncoding, readableObjectMode, readableHighWaterMark} = getReadableOptions(subprocessStdout, binary);22 const {read, onStdoutDataDone} = getReadableMethods({
109 unmodified lines
modified:lib/convert/writable.js+7 added-5 removed
1import {Writable} from 'node:stream';2import {callbackify} from 'node:util';3import {getToStream} from '../arguments/fd-options.js';4import {isStreamAbort} from '../resolve/wait-stream.js';5import {copyOptions} from '../utils/options.js';6import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';7import {8 safeWaitForSubprocessStdout,9 waitForSubprocessStdin,
2 unmodified lines
12} from './shared.js';1314// Create a `Writable` stream that forwards to `stdin` and awaits the subprocess15export const createWritable = ({subprocess, concurrentStreams}, options) => {15 // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values16 const {to} = {__proto__: null, ...options};16 const {to} = copyOptions(options);17 const {subprocessStdin, waitWritableFinal, waitWritableDestroy} = getSubprocessStdin(subprocess, to, concurrentStreams);18 const writable = new Writable({19 ...getWritableMethods(subprocessStdin, subprocess, waitWritableFinal),20 destroy: callbackify(onWritableDestroy.bind(undefined, {
80 unmodified lines
101102// When `writable` aborts/errors, do the same on `subprocess.stdin`103export const onWritableDestroy = async ({subprocessStdin, subprocess, waitWritableFinal, waitWritableDestroy}, error) => {104 await waitForConcurrentStreams(waitWritableFinal, subprocess);105 if (await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {106 destroyOtherWritable(subprocessStdin, error);107 await waitForSubprocess(subprocess, error);105 if (!await waitForConcurrentStreams(waitWritableDestroy, subprocess)) {106 return;107 }108109 destroyOtherWritable(subprocessStdin, error);110 await waitForSubprocess(subprocess, error);111};112113const destroyOtherWritable = (stream, error) => {114 destroyOtherStream(stream, stream.writable, error);
1 unmodified line
modified:lib/io/contents.js+1 added-5 removed
80 unmodified lines
81 if (readableObjectMode || lines) {82 return await getStreamAsArray(iterable, {maxBuffer});83 }8485 if (encoding === 'buffer') {86 return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));87 }8889 return await getStream(iterable, {maxBuffer});85 return encoding === 'buffer' ? new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer})) : (await getStream(iterable, {maxBuffer}));86 } catch (error) {87 return handleBufferedData(handleMaxBuffer({88 error,89 stream,
24 unmodified lines
modified:lib/io/max-buffer.js+2 added-10 removed
26 unmodified lines
27 if (lines) {28 return 'lines';29 }3031 if (encoding === 'buffer') {32 return 'bytes';33 }3435 return 'characters';31 return encoding === 'buffer' ? 'bytes' : 'characters';32};3334// Check the `maxBuffer` option with `result.ipcOutput`, before buffering one more message.35// Like the stream-based `maxBuffer`, the threshold is hit when the buffered amount would exceed it, which also applies to non-integer values.
20 unmodified lines
5657 const {maxBufferInfo: {fdNumber, unit, threshold = getFdSpecificValue(maxBuffer, fdNumber)}} = error;58 delete error.maxBufferInfo;5964 if (fdNumber === 'ipc') {65 return {streamName: 'IPC output', threshold, unit: 'messages'};66 }6768 return {streamName: getStreamName(fdNumber), threshold, unit};60 return fdNumber === 'ipc' ? {streamName: 'IPC output', threshold, unit: 'messages'} : {streamName: getStreamName(fdNumber), threshold, unit};61};6263// The native `maxBuffer` option passed to `spawnSync()` does not allow differentiating values per file descriptor, so we use `stdout`'s.64// Since each other file descriptor's own limit is capped by `stdout`'s, this is also the highest one.
38 unmodified lines
modified:lib/io/output-sync.js+2 added-6 removed
8 unmodified lines
910// Apply `stdout`/`stderr` options, after spawning, in sync mode11export const transformOutputSync = ({fileDescriptors, syncResult: {output}, options, verboseInfo}) => {12 if (output === null) {13 return {output: Array.from({length: 3})};13 return {output: Array.from({length: fileDescriptors.length}), error: undefined};14 }1516 const outputFiles = new Set();17 // Transforms, `verbose` and file writes apply to a single file descriptor each, so their errors must not affect the other ones
79 unmodified lines
97 return {serializedResult: joinToUint8Array(chunks)};98 }99100 const serializedResult = joinToString(chunks, encoding);101 if (lines[fdNumber]) {102 return {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)};103 }104105 return {serializedResult};101 return lines[fdNumber] ? {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)} : {serializedResult};102};103104const logOutputSync = ({serializedResult, fdNumber, verboseInfo, encoding, stdioItems, objectMode}) => {105 if (!shouldLogOutput({
44 unmodified lines
modified:lib/io/strip-newline.js+1 added-1 removed
1import stripFinalNewlineFunction from 'strip-final-newline';23// Apply `stripFinalNewline` option, which applies to `result.stdout|stderr|all|stdio[*]`.4// If the `lines` option is used, it is applied on each line, but using a different function.5export const stripNewline = (value, {stripFinalNewline}, fdNumber, allFds) => getStripFinalNewline(stripFinalNewline, fdNumber, allFds) && value !== undefined && !Array.isArray(value)5export const stripNewline = (value, {stripFinalNewline}, fdNumber, allFds) => value !== undefined && !Array.isArray(value) && getStripFinalNewline(stripFinalNewline, fdNumber, allFds)6 ? stripFinalNewlineFunction(value)7 : value;89// Retrieve `stripFinalNewline` option value, including with `subprocess.all`
4 unmodified lines
modified:lib/ipc/get-each.js+2 added-2 removed
1import {once, on} from 'node:events';2import {copyOptions} from '../utils/options.js';3import {4 validateIpcMethod,5 disconnect,6 getStrictResponseError,6 getIpcOptions,7} from './validation.js';8import {getIpcEmitter, isConnected} from './forward.js';9import {addReference, removeReference} from './reference.js';1011export const internalGetEachMessageOptions = Symbol('internalGetEachMessageOptions');1213// Like `[sub]process.on('message')` but promise-based14export const getEachMessage = (subprocessInfo, rawOptions) => {15 const options = getIpcOptions(rawOptions);15 const options = copyOptions(rawOptions);16 const {reference = true} = options;17 // Internal callers can stop the IPC listener without exposing cancellation or pipe-awaiting options as public API.18 const {signal, shouldAwait = !subprocessInfo.isSubprocess} = options[internalGetEachMessageOptions] ?? {};19
100 unmodified lines
modified:lib/ipc/get-one.js+2 added-2 removed
1import {once, on} from 'node:events';2import {copyOptions} from '../utils/options.js';3import {4 validateIpcMethod,5 throwOnEarlyDisconnect,6 disconnect,7 getStrictResponseError,7 getIpcOptions,8} from './validation.js';9import {getIpcEmitter, isConnected} from './forward.js';10import {addReference, removeReference} from './reference.js';1112export const internalGetOneMessageOptions = Symbol('internalGetOneMessageOptions');1314// Like `[sub]process.once('message')` but promise-based15export const getOneMessage = ({anyProcess, channel, isSubprocess, ipc}, rawOptions) => {16 const options = getIpcOptions(rawOptions);16 const options = copyOptions(rawOptions);17 const {reference = true, filter} = options;18 const {signal} = options[internalGetOneMessageOptions] ?? {};1920 validateIpcMethod({
74 unmodified lines
modified:lib/ipc/incoming.js+1 added-1 removed
24 unmodified lines
25// The `message` event so it is emitted at most once per macrotask.26export const onMessage = async ({anyProcess, channel, isSubprocess, ipcEmitter}, wrappedMessage) => {27 // `gracefulCancel` messages are only ever sent by the current process to its subprocess.28 // Only the subprocess must interpret them, otherwise a subprocess could abort its parent's own `cancelSignal`, or make it silently drop a message.29 if (handleStrictResponse(wrappedMessage) || (isSubprocess && handleAbort(wrappedMessage))) {29 if (handleStrictResponse(wrappedMessage, anyProcess) || (isSubprocess && handleAbort(wrappedMessage))) {30 return;31 }3233 if (!INCOMING_MESSAGES.has(anyProcess)) {
53 unmodified lines
modified:lib/ipc/send.js+2 added-2 removed
1import {promisify} from 'node:util';2import {copyOptions} from '../utils/options.js';3import {4 validateIpcMethod,5 handleEpipeError,6 handleSerializationError,7 disconnect,7 getIpcOptions,8} from './validation.js';9import {startSendMessage, endSendMessage} from './outgoing.js';10import {handleSendStrict, waitForStrictResponse} from './strict.js';11
1 unmodified line
13// We do not `await subprocess` during `.sendMessage()` nor `.getOneMessage()` since those methods are transient.14// Users would still need to `await subprocess` after the method is done.15// Also, this would prevent `unhandledRejection` event from being emitted, making it silent.16export const sendMessage = ({anyProcess, channel, isSubprocess, ipc}, message, options) => {17 const {strict = false} = getIpcOptions(options);17 const {strict = false} = copyOptions(options);18 const methodName = 'sendMessage';19 validateIpcMethod({20 methodName,21 isSubprocess,
72 unmodified lines
modified:lib/ipc/strict.js+10 added-5 removed
32 unmodified lines
33 }3435 for (const {id} of outgoingMessages) {36 if (id !== undefined) {37 STRICT_RESPONSES[id].resolve({isDeadlock: true, hasListeners: false});37 STRICT_RESPONSES[id].deferred.resolve({isDeadlock: true, hasListeners: false});38 }39 }40};41
19 unmodified lines
6162 return message;63};6465// Reception of the acknowledgment response66export const handleStrictResponse = wrappedMessage => {65// Reception of the acknowledgment response.66// Ids are shared by all processes, so the response must come from the process the message was sent to. Otherwise, a subprocess could acknowledge a message sent to another one.67export const handleStrictResponse = (wrappedMessage, anyProcess) => {68 if (wrappedMessage?.type !== RESPONSE_TYPE) {69 return false;70 }7172 const {id, message: hasListeners} = wrappedMessage;73 const strictResponse = STRICT_RESPONSES[id];74 if (strictResponse?.anyProcess === anyProcess) {72 STRICT_RESPONSES[id]?.resolve({isDeadlock: false, hasListeners});75 strictResponse.deferred.resolve({isDeadlock: false, hasListeners});76 }7778 return true;79};8081// Wait for the other process to receive the message from `sendMessage()`
2 unmodified lines
84 return;85 }8687 const deferred = createDeferred();83 STRICT_RESPONSES[wrappedMessage.id] = deferred;88 STRICT_RESPONSES[wrappedMessage.id] = {deferred, anyProcess};89 const controller = new AbortController();9091 try {92 const {isDeadlock, hasListeners} = await Promise.race([
27 unmodified lines
modified:lib/ipc/validation.js-10 removed
107 unmodified lines
108 if (anyProcess.connected) {109 anyProcess.disconnect();110 }111};112113// The options are kept on a null-prototype object, otherwise a polluted `Object.prototype` would inject option values.114// Like destructuring them, `null` throws.115export const getIpcOptions = (options = {}) => {116 if (options === null) {117 throw new TypeError('The options must be an object, not `null`.');118 }119120 return {__proto__: null, ...options};121};
modified:lib/methods/bind.js+1 added-7 removed
10 unmodified lines
11 ]));12 return {__proto__: null, ...safeBoundOptions, ...mergedOptions};13};1415const mergeOption = (optionName, boundOptionValue, optionValue) => {16 if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {17 return {...boundOptionValue, ...optionValue};18 }15const mergeOption = (optionName, boundOptionValue, optionValue) => DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue) ? {...boundOptionValue, ...optionValue} : optionValue;1620 return optionValue;21};2217const DEEP_OPTIONS = new Set(['env', ...FD_SPECIFIC_OPTIONS]);
modified:lib/methods/main-async.js+2 added-2 removed
102 unmodified lines
103104 const context = {};105 const onInternalError = createDeferred();106 const kill = subprocessKill.bind(undefined, {107 kill: getKillFunction(subprocess, options, controller),107 kill: getKillFunction(subprocess, options),108 options,109 onInternalError,110 context,111 controller,
88 unmodified lines
200 });201 return handleResult(result, verboseInfo, options);202};203204const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo204const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options, command, escapedCommand, startTime}) => Object.hasOwn(errorInfo, 'error')205 ? makeError({206 error: errorInfo.error,207 command,208 escapedCommand,
23 unmodified lines
modified:lib/methods/main-sync.js+2 added-1 removed
119 unmodified lines
120const runSubprocessSync = ({file, commandArguments, options, command, escapedCommand, fileDescriptors, startTime}) => {121 try {122 addInputOptionsSync(fileDescriptors, options);123 const normalizedOptions = normalizeSpawnSyncOptions(options);124 return spawnSync(...concatenateShell(file, commandArguments, normalizedOptions));124 // Keep the null prototype, otherwise a polluted `Object.prototype.failed` would make the result look like an early error125 return {__proto__: null, ...spawnSync(...concatenateShell(file, commandArguments, normalizedOptions))};126 } catch (error) {127 return makeEarlyError({128 error,129 command,
40 unmodified lines
modified:lib/pipe/pipe-arguments.js+4 added-4 removed
1import {normalizeParameters} from '../methods/parameters.js';2import {getStartTime} from '../return/duration.js';3import {SUBPROCESS_OPTIONS, getToStream, getFromStream} from '../arguments/fd-options.js';4import {isDenoExecPath} from '../arguments/file-url.js';5import {copyOptions} from '../utils/options.js';67// Normalize and validate arguments passed to `source.pipe(destination)`8export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...pipeArguments) => {9 const startTime = getStartTime();
29 unmodified lines
39 return {destinationError: error};40 }4142 const {destination, pipeOptions} = destinationInfo;42 // Keep the null prototype, otherwise a polluted `Object.prototype` would inject option values43 const {from, to, unpipeSignal} = {__proto__: null, ...pipeOptions};43 const {from, to, unpipeSignal} = copyOptions(pipeOptions);4445 try {46 const destinationStream = getToStream(destination, to);47 return {
10 unmodified lines
5859/*60The destination has already been spawned at that point, since the `to` option is validated afterwards.61When Execa spawned it, nothing else can end it, so it is terminated. Otherwise, it would keep running, e.g. waiting for its `stdin` forever, which also prevents the current process from exiting. A destination passed by the user is left to them.62In both cases, its error must be handled, otherwise it becomes an unhandled rejection which crashes the current process.62In both cases, its error must be handled, otherwise it becomes an unhandled rejection which crashes the current process, e.g. with `source.pipe(execa('command'), {to: 'fd9'})`. This does not prevent the user from awaiting it.63*/64const abortDestination = (destination, firstArgument) => {65 if (destination !== firstArgument) {66 destination.kill();
39 unmodified lines
106 __proto__: null,107 ...options,108 // Piping writes to the destination's `stdin`, which is forced even if the user set another value.109 // However, `stdin` cannot be combined with `stdio`, which is needed for `to: 'fd3'` and higher.110 ...(options.stdio === undefined ? {stdin: 'pipe'} : {}),110 ...((options.stdio === undefined) && {stdin: 'pipe'}),111 piped: true,112 },113});114
8 unmodified lines
modified:lib/pipe/throw.js+5 added-3 removed
36 unmodified lines
37 abortSourceStream(sourceStream);38 return destinationError;39 }4041 if (sourceError !== undefined) {42 endDestinationStream(destinationStream);43 return sourceError;41 if (sourceError === undefined) {42 return;43 }4445 endDestinationStream(destinationStream);46 return sourceError;47};4849// Specific error return value when passing invalid arguments to `subprocess.pipe()` or when using `unpipeSignal`50export const createNonCommandError = ({error, fileDescriptors, sourceOptions, startTime}) => makeEarlyError({
10 unmodified lines
modified:lib/resolve/all-async.js+2 added-10 removed
8 unmodified lines
9 return;10 }1112 const fileDescriptors = [[stdout, 1], [stderr, 2]].filter(([stream]) => stream);13 if (fileDescriptors.length === 0) {14 return;15 }1617 return setAllStream(mergeStreams(fileDescriptors.map(([stream]) => stream)));13 return fileDescriptors.length === 0 ? undefined : setAllStream(mergeStreams(fileDescriptors.map(([stream]) => stream)));14};1516// The file descriptors which `result.all` contains, which the `all` options must follow17// Unlike `subprocess.all`, this excludes the file descriptors which are not buffered, since their output is not included
38 unmodified lines
56 if (!bufferStdout) {57 return {stream: stderr, buffer, drainedStream: all};58 }5964 if (!bufferStderr) {65 return {stream: stdout, buffer, drainedStream: all};60 return bufferStderr ? {stream: all, buffer} : {stream: stdout, buffer, drainedStream: all};66 }6768 return {stream: all, buffer};61};6263// When `subprocess.stdout` is in objectMode but not `subprocess.stderr` (or the opposite), we need to use both:64// - `getStreamAsArray()` for the chunks in objectMode, to return as an array without changing each chunk
6 unmodified lines
modified:lib/resolve/all-sync.js+2 added-6 removed
32 unmodified lines
33 if (Array.isArray(stdout) || Array.isArray(stderr)) {34 return [stdout, stderr].flat();35 }3637 if (isUint8Array(stdout) && isUint8Array(stderr)) {38 return concatUint8Arrays([stdout, stderr]);39 }4041 return `${stdout}${stderr}`;37 return isUint8Array(stdout) && isUint8Array(stderr) ? concatUint8Arrays([stdout, stderr]) : `${stdout}${stderr}`;38};3940const hasLines = ({lines}) => Boolean(lines[1] || lines[2]);4142// Each file descriptor is either already split into lines, or is a string which still needs to be split47const splitAllLines = (value, allFds, options) => Array.isArray(value) || !hasLines(options)43const splitAllLines = (value, allFds, options) => value === undefined || Array.isArray(value) || !hasLines(options)44 ? value45 : splitLinesSync(value, !getStripFinalNewline(options.stripFinalNewline, 'all', allFds), false);
modified:lib/return/message.js+2 added-10 removed
111 unmodified lines
112 if (signal !== undefined) {113 return `Command was killed with ${signal} (${signalDescription})`;114 }115116 if (exitCode !== undefined) {117 return `Command failed with exit code ${exitCode}`;116 return exitCode === undefined ? 'Command failed' : `Command failed with exit code ${exitCode}`;118 }119120 return 'Command failed';117};118119const getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated120 ? ` and was forcefully terminated after ${forceKillAfterDelay} milliseconds`
23 unmodified lines
144 if (typeof messageItem === 'string') {145 return messageItem;146 }147152 if (isUint8Array(messageItem)) {153 return uint8ArrayToString(messageItem);154 }155156 return '';148 return isUint8Array(messageItem) ? uint8ArrayToString(messageItem) : '';149};
modified:lib/return/reject.js+1 added-1 removed
3 unmodified lines
4// Also print the final log line with `verbose`.5export const handleResult = (result, verboseInfo, {reject}) => {6 logResult(result, verboseInfo);78 if (result.failed && reject) {8 if (reject && result.failed) {9 throw result;10 }1112 return result;
1 unmodified line
modified:lib/stdio/direction.js+12 added-9 removed
8 unmodified lines
9// For `stdio[fdNumber]` beyond stdin/stdout/stderr, we need to guess whether the value passed is intended for inputs or outputs.10// This allows us to know whether to pipe _into_ or _from_ the stream.11// When `stdio[fdNumber]` is a single value, this guess is fairly straightforward.12// However, when it is an array instead, we also need to make sure the different values are not incompatible with each other.13export const getStreamDirection = (stdioItems, fdNumber, optionName) => {14 const directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber));13export const getStreamDirection = ({stdioItems, isStdioArray, fdNumber, optionName}) => {14 const directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber, isStdioArray));1516 if (directions.includes('input') && directions.includes('output')) {17 throw new TypeError(`The \`${optionName}\` option must not be an array of both readable and writable values.`);18 }1920 return directions.find(Boolean) ?? DEFAULT_DIRECTION;21};2223const getStdioItemDirection = (stdioItem, fdNumber) => {23const getStdioItemDirection = (stdioItem, fdNumber, isStdioArray) => {24 const knownDirection = KNOWN_DIRECTIONS[fdNumber];25 const direction = getRequestedDirection(stdioItem);26 if (knownDirection === undefined) {27 return direction;28 }2930 validateKnownDirection(stdioItem, knownDirection);30 validateKnownDirection(stdioItem, knownDirection, isStdioArray);31 return knownDirection;32};3334// `direction` is set when the user explicitly requests it, e.g. `{value: 'pipe', input: true}`.
12 unmodified lines
47// `stdin`/`stdout`/`stderr` have a fixed direction, which each value must not contradict.48// Otherwise, asynchronous methods pipe in the wrong direction and crash, e.g. with `dest.end is not a function`.49// Only values whose direction is intrinsic to a stream are checked: other values (e.g. `Uint8Array`) are already50// rejected in the wrong direction when their stream properties are added.51// A single file descriptor 0, 1 or 2, e.g. `stdin: 1`, is passed as is to `child_process.spawn()` instead of being piped by Execa, so it is not checked. Those are often the same terminal, which is both readable and writable.51const validateKnownDirection = ({type, value, optionName}, knownDirection) => {52 if (!STREAM_TYPES.has(type)) {52const validateKnownDirection = ({type, value, optionName}, knownDirection, isStdioArray) => {53 if (!STREAM_TYPES.has(type) || (!isStdioArray && getStandardStreamDirection(value) !== undefined)) {54 return;55 }5657 const guessedDirection = guessStreamDirection[type](value);57 if (guessedDirection !== undefined && guessedDirection !== knownDirection) {58 const valueName = guessedDirection === 'input' ? 'readable' : 'writable';59 throw new TypeError(`The \`${optionName}\` option is invalid: a ${valueName} value is always an ${guessedDirection}, but \`${optionName}\` is an ${knownDirection}.`);58 if (guessedDirection === undefined || guessedDirection === knownDirection) {59 return;60 }6162 const valueName = guessedDirection === 'input' ? 'readable' : 'writable';63 throw new TypeError(`The \`${optionName}\` option is invalid: a ${valueName} value is always an ${guessedDirection}, but \`${optionName}\` is an ${knownDirection}.`);64};6566const STREAM_TYPES = new Set(['native', 'nodeStream', 'webStream']);67
53 unmodified lines
modified:lib/stdio/duplicate.js+2 added-2 removed
1import {resolve} from 'node:path';1import path from 'node:path';2import {fileURLToPath} from 'node:url';3import {4 SPECIAL_DUPLICATE_TYPES_SYNC,5 SPECIAL_DUPLICATE_TYPES,
5 unmodified lines
11const isFileType = type => SPECIAL_DUPLICATE_TYPES_SYNC.has(type);1213// The file that a `filePath` or `fileUrl` stdio item targets, as an absolute path14export const getFileTarget = ({type, value}) => type === 'filePath'15 ? resolve(value.file)15 ? path.resolve(value.file)16 : fileURLToPath(value);1718// Duplicates in the same file descriptor is most likely an error.19// However, this can be useful with generators.
110 unmodified lines
modified:lib/stdio/handle.js+7 added-2 removed
42 unmodified lines
43 fdNumber,44 options,45 optionName,46 });47 const direction = getStreamDirection(initialStdioItems, fdNumber, optionName);47 const direction = getStreamDirection({48 stdioItems: initialStdioItems,49 isStdioArray,50 fdNumber,51 optionName,52 });53 const stdioItems = initialStdioItems.map(stdioItem => handleNativeStream({54 stdioItem,55 isStdioArray,56 fdNumber,
90 unmodified lines
147 }148};149150// `node:child_process` converts file descriptors to a 32-bit signed integer, and aborts the process when it cannot146const MAX_FILE_DESCRIPTOR = 2 ** 31 - 1;151const MAX_FILE_DESCRIPTOR = (2 ** 31) - 1;152153const validateFileStdio = ({type, value, optionName}) => {154 if (isRegularUrl(value)) {155 throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.
108 unmodified lines
modified:lib/stdio/native.js+1 added-5 removed
82 unmodified lines
83 if (typeof value === 'number') {84 return {type: 'nodeStream', value: getStandardStream(value, value, optionName), optionName};85 }8687 if (isNodeStream(value, {checkOpen: false})) {88 return {type: 'nodeStream', value, optionName};89 }9091 return stdioItem;87 return isNodeStream(value, {checkOpen: false}) ? {type: 'nodeStream', value, optionName} : stdioItem;88};8990// Node.js does not allow to easily retrieve file descriptors beyond stdin/stdout/stderr as streams.91// - `fs.createReadStream()`/`fs.createWriteStream()` with the `fd` option do not work with character devices that use blocking reads/writes (such as interactive TTYs).
12 unmodified lines
modified:lib/stdio/stdio-option.js+2 added-14 removed
20 unmodified lines
21 throw new Error('The `ipc: true` option must be used instead of `stdio: \'ipc\'`.');22 }23};2425const hasIpcStdioOption = stdioOption => {26 if (Array.isArray(stdioOption)) {27 return stdioOption.some(item => hasIpcStdioItem(item));28 }25const hasIpcStdioOption = stdioOption => Array.isArray(stdioOption) ? stdioOption.some(item => hasIpcStdioItem(item)) : hasIpcStdioItem(stdioOption);2630 return hasIpcStdioItem(stdioOption);31};27const hasIpcStdioItem = stdioOption => isStdioValueObject(stdioOption) ? stdioOption.value === 'ipc' : stdioOption === 'ipc';2833const hasIpcStdioItem = stdioOption => {34 if (isStdioValueObject(stdioOption)) {35 return stdioOption.value === 'ipc';36 }3738 return stdioOption === 'ipc';39};4029const getStdioArray = (stdio, options) => {30 if (stdio === undefined) {31 return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);32 }
58 unmodified lines
modified:lib/stdio/type.js+2 added-10 removed
42 unmodified lines
43 if (isTransformStream(value)) {44 return getTransformStreamType({transform: value}, optionName);45 }4647 if (isTransformOptions(value)) {48 return getTransformObjectType(value, optionName);49 }5051 return 'native';47 return isTransformOptions(value) ? getTransformObjectType(value, optionName) : 'native';48};4950const getTransformObjectType = (value, optionName) => {51 if (isDuplexStream(value.transform, {checkOpen: false})) {52 return getDuplexType(value, optionName);53 }5459 if (isTransformStream(value.transform)) {60 return getTransformStreamType(value, optionName);61 }6263 return getGeneratorObjectType(value, optionName);55 return isTransformStream(value.transform) ? getTransformStreamType(value, optionName) : getGeneratorObjectType(value, optionName);56};5758const getDuplexType = (value, optionName) => {59 validateNonGeneratorType(value, optionName, 'Duplex stream');
114 unmodified lines
modified:lib/terminate/kill-descendants.js+16 added-17 removed
7 unmodified lines
8// On Unix, this requires spawning the subprocess in its own process group, so we override the9// `detached` argument passed to `child_process.spawn()`.10// This is kept separate from the user-facing `detached` option, which must keep its own value,11// so the `cleanup` behavior is not affected.12export const getSpawnOptions = options => options.killDescendants && !isWindows12export const getSpawnOptions = options => !isWindows && options.killDescendants13 ? {...options, detached: true}14 : options;1516/*17`subprocess.pid` is `undefined` when the subprocess failed to spawn, e.g. with `ENOENT`.18`ChildProcess.prototype.kill()` then signals the current process group, since its process id is `0`.19So, like `ChildProcess.prototype.kill()` does for a subprocess which already exited, nothing is signaled and `false` is returned.20*/2116// Returns the low-level function used to send a signal to the subprocess.17// With the `killDescendants` option, the signal is sent to the whole process tree.24export const getKillFunction = (subprocess, {killDescendants}, {signal: controllerSignal}) => {18export const getKillFunction = (subprocess, {killDescendants}) => {19 if (!killDescendants) {20 /*21 `subprocess.pid` is `undefined` when the subprocess failed to spawn, e.g. with `ENOENT`.22 `ChildProcess.prototype.kill()` then signals the current process group, since its process id is `0`.23 So, like `ChildProcess.prototype.kill()` does for a subprocess which already exited, nothing is signaled and `false` is returned.24 */25 const killSubprocess = subprocess.kill.bind(subprocess);26 return (...arguments_) => (subprocess.pid === undefined ? false : killSubprocess(...arguments_));27 }2829 const killDescendantsFunction = isWindows ? killDescendantsWindows : killDescendantsUnix;31 return killDescendantsFunction.bind(undefined, subprocess, controllerSignal);30 return killDescendantsFunction.bind(undefined, subprocess);31};3233/*35Unlike `subprocess.kill()`, signaling a process group or a process tree uses the PID directly, without going through the subprocess' handle. The OS can re-assign that PID once the tree is gone, and signaling it then would terminate an unrelated process, and on Windows its own descendants too.36On Unix, a PID stays reserved as long as it is the process group ID of a running process, so it can only be re-assigned once every descendant exited too. While Execa is still waiting on the subprocess, the signal is still useful, e.g. for the `forceKillAfterDelay` escalation, which happens after the subprocess exited but while a descendant might still be running. Once Execa is done with the subprocess, no internal logic sends signals anymore, so only `subprocess.kill()` can. Like `ChildProcess.kill()`, it then becomes a noop returning `false`. This narrows the window during which a re-assigned PID could be signaled, without removing it, e.g. when Execa is still waiting on a slow transform after the whole process group exited.34Unlike `subprocess.kill()`, signaling a process group or a process tree uses the PID directly, without going through the subprocess' handle. The OS can re-assign that PID once it is not used anymore, and signaling it then would terminate an unrelated process, and on Windows its own descendants too.35On Unix, a PID stays reserved as long as it is the process group ID of a running process, i.e. as long as any descendant in that group is still running. So signaling the process group after the subprocess exited is still useful, e.g. for the `forceKillAfterDelay` escalation while Execa is waiting on a descendant, or with `subprocess.kill()` to terminate background descendants once the subprocess has settled. Once the whole group exited, the PID can only be signaled if the OS re-assigned it to a new process group leader, which is unlikely, so this is a documented limitation.36On Windows, there are no process groups: a PID is only reserved while a handle to the process is open, which Node.js closes once the subprocess exits. `taskkill /T` also cannot find the descendants of a process which exited. So the process tree is never signaled once the subprocess exited.37*/39const isAbandoned = (subprocess, controllerSignal) => subprocess.pid === undefined40 || (hasExited(subprocess) && (isWindows || controllerSignal.aborted));38const isAbandoned = subprocess => subprocess.pid === undefined39 || (isWindows && hasExited(subprocess));4041const hasExited = ({exitCode, signalCode}) => exitCode !== null || signalCode !== null;4243// On Unix, the subprocess is its own process group leader (its PGID equals its PID), since it44// was spawned with `detached: true`. Sending the signal to `-pid` targets the whole group.46const killDescendantsUnix = (subprocess, controllerSignal, signal) => {47 if (isAbandoned(subprocess, controllerSignal)) {45const killDescendantsUnix = (subprocess, signal) => {46 if (isAbandoned(subprocess)) {47 return false;48 }4950 try {
9 unmodified lines
60// It must run while the tree is still intact, so direct subprocess termination is only used as a61// fallback: killing the direct subprocess first would orphan its descendants before `taskkill` could enumerate them.62// If `taskkill` is unavailable or fails, the fallback only terminates the direct subprocess.63// `taskkill` ignores the signal (`/F` terminates the tree).65const killDescendantsWindows = (subprocess, controllerSignal, signal) => {66 if (isAbandoned(subprocess, controllerSignal)) {64const killDescendantsWindows = (subprocess, signal) => {65 if (isAbandoned(subprocess)) {66 return false;67 }6869 const taskkillFile = getTaskkillFile();
26 unmodified lines
added:lib/utils/options.js+9 added
1// The options of methods like `subprocess.pipe()`, `subprocess.readable()` or `sendMessage()` are kept on a null-prototype object, otherwise a polluted `Object.prototype` would inject option values.2// Like destructuring them, `null` throws.3export const copyOptions = (options = {}) => {4 if (options === null) {5 throw new TypeError('The options must be an object, not `null`.');6 }78 return {__proto__: null, ...options};9};
modified:lib/utils/uint-array.js+1 added-7 removed
33 unmodified lines
34 const finalString = decoder.end();35 return finalString === '' ? strings : [...strings, finalString];36};3738export const joinToUint8Array = uint8ArraysOrStrings => {39 if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {40 return uint8ArraysOrStrings[0];41 }38export const joinToUint8Array = uint8ArraysOrStrings => uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0]) ? uint8ArraysOrStrings[0] : concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));3943 return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));44};4540const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'41 ? stringToUint8Array(uint8ArrayOrString)42 : uint8ArrayOrString);43
20 unmodified lines
modified:lib/verbose/output.js+2 added-2 removed
44 unmodified lines
45// - `.pipe()` achieves the same result as using `stdout: 'inherit'`, `stdout: stream`, etc. which also make `verbose` a noop.46// For example, `subprocess.stdout.pipe(process.stdin)` would print each line twice.47// - When chaining subprocesses with `subprocess.pipe(otherSubprocess)`, only the last one should print its output.48// Detecting whether `.pipe()` is impossible without monkey-patching it, so we use the following undocumented property.49// The pipe into `subprocess.all` is done by Execa itself, so it is excluded.49// The pipe into `subprocess.all` is done by Execa itself, so it only counts when `subprocess.all` is itself piped, e.g. `subprocess.all.pipe(process.stdout)`.50// This is not a critical behavior since changes of the following property would only make `verbose` more verbose.51const isPipingStream = stream => stream._readableState.pipes.some(pipe => !isAllStream(pipe));51const isPipingStream = stream => stream._readableState.pipes.some(pipe => !isAllStream(pipe) || isPipingStream(pipe));5253// When `verbose` is `full`, print stdout|stderr54const logLine = (line, fdNumber, verboseInfo) => {55 const verboseMessage = serializeVerboseMessage(line);
7 unmodified lines
modified:test/arguments/command-resolution.js+128 added-126 removed
1import assert from 'node:assert/strict';2import path from 'node:path';3import process from 'node:process';4import test from 'node:test';5import {6 cp,7 mkdir,8 unlink,9 writeFile,10} from 'node:fs/promises';7import path from 'node:path';8import process from 'node:process';9import test from 'ava';11import {assertThrows, assertRejects} from '../helpers/assert.js';12import {execa, execaSync} from '../../index.js';13import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';1415setFixtureDirectory();
8 unmodified lines
24// back byte-identical. This exercises the escaping logic on whichever OS runs the25// test, so Windows escaping is genuinely validated on CI.2627// `echo.js` prints `process.argv.slice(2).join('\n')`26const testRoundtrip = async (t, commandArguments) => {28const testRoundtrip = async commandArguments => {29 const expectedStdout = commandArguments.map(String).join('\n');3031 const {stdout} = await execa('echo.js', commandArguments);30 t.is(stdout, expectedStdout);32 assert.equal(stdout, expectedStdout);3334 const {stdout: stdoutSync} = execaSync('echo.js', commandArguments);33 t.is(stdoutSync, expectedStdout);35 assert.equal(stdoutSync, expectedStdout);36};3736test('Empty arguments and arguments with spaces', testRoundtrip, ['foo', '', 'bar', 'André Cruz']);37test('Non-string arguments are coerced', testRoundtrip, [1234]);38test('Arguments with shell special characters', testRoundtrip, [38test('Empty arguments and arguments with spaces', () => testRoundtrip(['foo', '', 'bar', 'André Cruz']));39test('Non-string arguments are coerced', () => testRoundtrip([1234]));40test('Arguments with shell special characters', () => testRoundtrip([41 'foo',42 '()',43 'foo',44 '[]',
23 unmodified lines
68 '\\"',69 'bar\\',70 '"foo|bar>baz"',71 '"(foo|bar>baz|foz)"',70]);72]));73// Backslashes and double quotes need specific escaping on Windows, so their combinations are the trickiest.72test('Arguments with backslashes', testRoundtrip, ['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']);73test('Arguments with backslashes and double quotes', testRoundtrip, ['a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);74test('Arguments with backslashes', () => testRoundtrip(['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']));75test('Arguments with backslashes and double quotes', () => testRoundtrip(['a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']));76// Backslashes, double quotes and shell metacharacters combined in a single argument are the trickiest to escape on Windows.75test('Arguments combining backslashes, quotes and metacharacters', testRoundtrip, ['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']);76test('Arguments with tabs and whitespace', testRoundtrip, ['a\tb', '\t', ' spaces ', ' ']);77test('Arguments combining backslashes, quotes and metacharacters', () => testRoundtrip(['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']));78test('Arguments with tabs and whitespace', () => testRoundtrip(['a\tb', '\t', ' spaces ', ' ']));79// Several consecutive empty and whitespace-only arguments must each be preserved as a distinct argument.78test('Arguments that are empty or whitespace-only', testRoundtrip, ['', '', 'a', '', ' ', '\t', '']);79test('Arguments that look like flags', testRoundtrip, ['-e', '--foo=bar', '--', '-']);80test('Arguments with Unicode characters', testRoundtrip, ['café', '🎉', '日本語', 'naïve']);80test('Arguments that are empty or whitespace-only', () => testRoundtrip(['', '', 'a', '', ' ', '\t', '']));81test('Arguments that look like flags', () => testRoundtrip(['-e', '--foo=bar', '--', '-']));82test('Arguments with Unicode characters', () => testRoundtrip(['café', '🎉', '日本語', 'naïve']));83// eslint-disable-next-line no-template-curly-in-string82test('Arguments with shell variable syntax', testRoundtrip, ['$HOME', '${x}', '~', 'a=b,c', '`whoami`']);84test('Arguments with shell variable syntax', () => testRoundtrip(['$HOME', '${x}', '~', 'a=b,c', '`whoami`']));85// Very long arguments must not be truncated nor corrupted by the escaping.84test('Very long arguments', testRoundtrip, ['a'.repeat(10_000), `${'b'.repeat(1000)}\\"${'c'.repeat(1000)}`]);86test('Very long arguments', () => testRoundtrip(['a'.repeat(10_000), `${'b'.repeat(1000)}\\"${'c'.repeat(1000)}`]));87// A long run of consecutive backslashes right before a double quote (or the end of the88// argument) must be doubled as a whole. This is both the input a length-dependent escaping89// bug corrupts and the one a naive regex backtracks quadratically over, so a correct90// roundtrip here guards correctness and the single-pass linear escaping at once.89test('Arguments with long runs of backslashes before quotes', testRoundtrip, [91test('Arguments with long runs of backslashes before quotes', () => testRoundtrip([92 `${'\\'.repeat(1000)}"`,93 '\\'.repeat(1000),94 `a${'\\'.repeat(500)}"b${'\\'.repeat(500)}`,93]);95]));96// Runs of backslashes of every length from 1 to 6, each right before a double quote, then97// each at the very end of the argument. The bug this guards against doubled only the last98// backslash of a run instead of the whole run, so it corrupted every length above 1.99// Passing each length as its own argument pins down exactly which lengths would break.100const backslashRunArguments = [101 ...Array.from({length: 6}, (_, index) => `${'\\'.repeat(index + 1)}"x`),102 ...Array.from({length: 6}, (_, index) => `end${'\\'.repeat(index + 1)}`),103];102test('Arguments with backslash runs of every length', testRoundtrip, backslashRunArguments);104test('Arguments with backslash runs of every length', () => testRoundtrip(backslashRunArguments));105// Consecutive double quotes must each be escaped independently, not collapsed nor paired.104test('Arguments with consecutive double quotes', testRoundtrip, ['""', '"""', 'a""b', '""""']);106test('Arguments with consecutive double quotes', () => testRoundtrip(['""', '"""', 'a""b', '""""']));107// A line break can be passed as an argument to a directly executable file (unlike a `.cmd`108// on Windows, see below). `echo-argv.js` prints its arguments as JSON, so this verifies the109// line break stays within a single argument rather than splitting it in two.108test('Line breaks are kept within a single argument for executables', async t => {110test('Line breaks are kept within a single argument for executables', async () => {111 const commandArguments = ['a\nb', 'a\r\nb', 'c'];112 const {stdout} = await execa('echo-argv.js', commandArguments);111 t.deepEqual(JSON.parse(stdout), commandArguments);113 assert.deepEqual(JSON.parse(stdout), commandArguments);114115 const {stdout: stdoutSync} = execaSync('echo-argv.js', commandArguments);114 t.deepEqual(JSON.parse(stdoutSync), commandArguments);116 assert.deepEqual(JSON.parse(stdoutSync), commandArguments);117});118119// A command can be resolved from different kinds of file paths. Forward slashes120// work even on Windows, where they are normalized to backslashes.119const testResolvesCommand = async (t, file, options) => {121const testResolvesCommand = async (file, options) => {122 const {stdout} = await execa(file, ['foo'], options);121 t.is(stdout, 'foo');123 assert.equal(stdout, 'foo');124125 const {stdout: stdoutSync} = execaSync(file, ['foo'], options);124 t.is(stdoutSync, 'foo');126 assert.equal(stdoutSync, 'foo');127};128127test('Runs a command given as an absolute path', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'echo.js'));128test('Runs a command given as a relative path with a custom cwd', testResolvesCommand, './echo.js', {cwd: FIXTURES_DIRECTORY});129test('Runs a command given as a relative POSIX-style subpath', testResolvesCommand, 'test/fixtures/echo.js');130test('Runs a command whose path contains a space', testResolvesCommand, 'command with space.js');131test('Runs a command whose absolute path contains a space', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'command with space.js'));129test('Runs a command given as an absolute path', () => testResolvesCommand(path.join(FIXTURES_DIRECTORY, 'echo.js')));130test('Runs a command given as a relative path with a custom cwd', () => testResolvesCommand('./echo.js', {cwd: FIXTURES_DIRECTORY}));131test('Runs a command given as a relative POSIX-style subpath', () => testResolvesCommand('test/fixtures/echo.js'));132test('Runs a command whose path contains a space', () => testResolvesCommand('command with space.js'));133test('Runs a command whose absolute path contains a space', () => testResolvesCommand(path.join(FIXTURES_DIRECTORY, 'command with space.js')));134135// A shebang script can be run without explicitly prepending its interpreter.136// This is emulated on Windows, where shebangs are not natively supported.137// The whole test suite implicitly relies on this (e.g. `echo.js`), so we assert it explicitly.136test('Runs a shebang script without specifying its interpreter', async t => {138test('Runs a shebang script without specifying its interpreter', async () => {139 const {stdout} = await execa('echo.js', ['foo']);138 t.is(stdout, 'foo');140 assert.equal(stdout, 'foo');141142 const {stdout: stdoutSync} = execaSync('echo.js', ['foo']);141 t.is(stdoutSync, 'foo');143 assert.equal(stdoutSync, 'foo');144});145146// A space between `#!` and the interpreter path (e.g. `#! /usr/bin/env node`) is a valid,147// real-world shebang variation. The reimplemented shebang parser must trim it, otherwise148// on Windows the interpreter would resolve as ` /usr/bin/env` and fail with ENOENT.147test('Runs a shebang script with a space after the "#!"', async t => {149test('Runs a shebang script with a space after the "#!"', async () => {150 const {stdout} = await execa('echo-space-shebang.js', ['foo']);149 t.is(stdout, 'foo');151 assert.equal(stdout, 'foo');152153 const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']);152 t.is(stdoutSync, 'foo');154 assert.equal(stdoutSync, 'foo');155});156157/*158Windows does not support shebangs natively, so Execa parses them itself, by reading the file's first bytes into a fixed-size buffer.
4 unmodified lines
163if (isWindows) {164 test('Runs a shebang script shorter than the shebang buffer', async t => {165 const filePath = path.join(FIXTURES_DIRECTORY, 'shebang-only.js');166 await writeFile(filePath, '#!/usr/bin/env node');165 t.teardown(() => unlink(filePath));167 t.after(() => unlink(filePath));168169 const {exitCode, stdout} = await execa('shebang-only.js');168 t.is(exitCode, 0);169 t.is(stdout, '');170 assert.equal(exitCode, 0);171 assert.equal(stdout, '');172 });173}174175// Neither the caller's arguments array nor its options object should be mutated,176// whether or not a shell is used (each path clones the arguments internally).175const testNoMutation = async (t, options) => {177const testNoMutation = async options => {178 const commandArguments = ['foo', 'bar'];179 const optionsCopy = {...options};180181 await execa('echo.js', commandArguments, options);180 t.deepEqual(commandArguments, ['foo', 'bar']);181 t.deepEqual(options, optionsCopy);182 assert.deepEqual(commandArguments, ['foo', 'bar']);183 assert.deepEqual(options, optionsCopy);184185 execaSync('echo.js', commandArguments, options);184 t.deepEqual(commandArguments, ['foo', 'bar']);185 t.deepEqual(options, optionsCopy);186 assert.deepEqual(commandArguments, ['foo', 'bar']);187 assert.deepEqual(options, optionsCopy);188};189188test('Does not mutate arguments nor options', testNoMutation, {});189test('Does not mutate arguments nor options with a shell', testNoMutation, {shell: true});190test('Does not mutate arguments nor options', () => testNoMutation({}));191test('Does not mutate arguments nor options with a shell', () => testNoMutation({shell: true}));192193if (isWindows) {194 const nodeOnlyOptions = {195 extendEnv: false,
3 unmodified lines
199 },200 };201202 // A bare command name without an extension is resolved using `PATHEXT`.201 test('Resolves command extension using PATHEXT (sync)', t => {203 test('Resolves command extension using PATHEXT (sync)', () => {204 const {stdout} = execaSync('hello');203 t.is(stdout, 'Hello World');205 assert.equal(stdout, 'Hello World');206 });207208 test('Uses PATHEXT extension order for direct executables', async t => {209 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');
4 unmodified lines
214 await Promise.all([215 cp(process.execPath, executablePath),216 cp(process.execPath, comPath),217 ]);216 t.teardown(async () => {218 t.after(async () => {219 await Promise.all([unlink(executablePath), unlink(comPath)]);220 });221 const options = {222 preferLocal: true,
6 unmodified lines
229 };230 const nodeExpression = 'JSON.stringify({executablePath: process.execPath, argv0: process.argv0})';231 const {stdout} = await execa(command, ['--print', nodeExpression], options);232 const {executablePath: actualExecutablePath, argv0} = JSON.parse(stdout);231 t.is(actualExecutablePath.toLowerCase(), executablePath.toLowerCase());232 t.is(argv0, command);233 assert.equal(actualExecutablePath.toLowerCase(), executablePath.toLowerCase());234 assert.equal(argv0, command);235236 const {stdout: stdoutSync} = execaSync(command, ['--print', nodeExpression], options);237 const {executablePath: actualExecutablePathSync, argv0: argv0Sync} = JSON.parse(stdoutSync);236 t.is(actualExecutablePathSync.toLowerCase(), executablePath.toLowerCase());237 t.is(argv0Sync, command);238 assert.equal(actualExecutablePathSync.toLowerCase(), executablePath.toLowerCase());239 assert.equal(argv0Sync, command);240 });241240 test.serial('Respects NoDefaultCurrentDirectoryInExePath', async t => {242 test('Respects NoDefaultCurrentDirectoryInExePath', async t => {243 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');244 await mkdir(binaryDirectory, {recursive: true});245 const command = 'node-current-directory';246 const currentDirectoryExecutable = path.join(FIXTURES_DIRECTORY, `${command}.exe`);
5 unmodified lines
252253 const environmentName = 'NoDefaultCurrentDirectoryInExePath';254 const originalValue = process.env[environmentName];255 delete process.env[environmentName];254 t.teardown(async () => {256 t.after(async () => {257 if (originalValue === undefined) {258 delete process.env[environmentName];259 } else {260 process.env[environmentName] = originalValue;
10 unmodified lines
271 PathExt: '.EXE',272 },273 };274 const {stdout: currentDirectoryStdout} = await execa(command, ['--print', 'process.execPath'], options);273 t.is(currentDirectoryStdout.toLowerCase(), currentDirectoryExecutable.toLowerCase());275 assert.equal(currentDirectoryStdout.toLowerCase(), currentDirectoryExecutable.toLowerCase());276277 const {stdout: currentDirectoryStdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);276 t.is(currentDirectoryStdoutSync.toLowerCase(), currentDirectoryExecutable.toLowerCase());278 assert.equal(currentDirectoryStdoutSync.toLowerCase(), currentDirectoryExecutable.toLowerCase());279280 process.env[environmentName] = '1';281 const {stdout} = await execa(command, ['--print', 'process.execPath'], options);280 t.is(stdout.toLowerCase(), pathExecutable.toLowerCase());282 assert.equal(stdout.toLowerCase(), pathExecutable.toLowerCase());283284 const {stdout: stdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);283 t.is(stdoutSync.toLowerCase(), pathExecutable.toLowerCase());285 assert.equal(stdoutSync.toLowerCase(), pathExecutable.toLowerCase());286 });287286 test.serial('Uses the resolved batch file when current-directory search is disabled', async t => {288 test('Uses the resolved batch file when current-directory search is disabled', async t => {289 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');290 await mkdir(binaryDirectory, {recursive: true});291 const command = 'batch-current-directory';292 const currentDirectoryBatchFile = path.join(FIXTURES_DIRECTORY, `${command}.cmd`);
5 unmodified lines
298299 const environmentName = 'NoDefaultCurrentDirectoryInExePath';300 const originalValue = process.env[environmentName];301 delete process.env[environmentName];300 t.teardown(async () => {302 t.after(async () => {303 if (originalValue === undefined) {304 delete process.env[environmentName];305 } else {306 process.env[environmentName] = originalValue;
11 unmodified lines
318 [environmentName]: '',319 },320 };321 const {stdout} = await execa(command, options);320 t.is(stdout, 'PATH');322 assert.equal(stdout, 'PATH');323324 const {stdout: stdoutSync} = execaSync(command, options);323 t.is(stdoutSync, 'PATH');325 assert.equal(stdoutSync, 'PATH');326327 delete options.env[environmentName];328 process.env[environmentName] = '';329 const {stdout: parentEnvironmentStdout} = await execa(command, options);328 t.is(parentEnvironmentStdout, 'PATH');330 assert.equal(parentEnvironmentStdout, 'PATH');331332 const {stdout: parentEnvironmentStdoutSync} = execaSync(command, options);331 t.is(parentEnvironmentStdoutSync, 'PATH');333 assert.equal(parentEnvironmentStdoutSync, 'PATH');334 });335336 test('Does not search PATH for drive-relative commands', async t => {337 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');338 await mkdir(binaryDirectory, {recursive: true});339 const commandName = 'node-drive-relative';340 const pathExecutable = path.join(binaryDirectory, `${commandName}.exe`);341 await cp(process.execPath, pathExecutable);340 t.teardown(async () => {342 t.after(async () => {343 await unlink(pathExecutable);344 });345 const drive = path.parse(FIXTURES_DIRECTORY).root.slice(0, 2);346 const command = `${drive}${commandName}`;
4 unmodified lines
351 Path: binaryDirectory,352 PathExt: '.EXE',353 },354 };353 await t.throwsAsync(execa(command, [], options));354 t.throws(() => execaSync(command, [], options));355 await assertRejects(execa(command, [], options));356 assertThrows(() => execaSync(command, [], options));357 });358359 // A `.cmd` file needs `cmd.exe`, so its forward-slash path must be normalized to360 // backslashes, otherwise it fails with ENOENT.359 test('Runs a .cmd file given as a relative POSIX-style subpath', async t => {361 test('Runs a .cmd file given as a relative POSIX-style subpath', async () => {362 const {stdout} = await execa('fixtures/hello.cmd', {cwd: path.join(FIXTURES_DIRECTORY, '..')});361 t.is(stdout, 'Hello World');363 assert.equal(stdout, 'Hello World');364 });365366 /*367 Metacharacters are double-escaped for batch files, since `cmd.exe` interprets them once when the batch file is invoked and once when it re-expands the arguments with `%*`.
6 unmodified lines
374 await cp(path.join(FIXTURES_DIRECTORY, 'echo-cmd-shim.cmd'), shimPath);375 return shimPath;376 };377376 test('Double-escapes metacharacters for node_modules/.bin cmd-shims', async t => {378 test('Double-escapes metacharacters for node_modules/.bin cmd-shims', async () => {379 const shimPath = await setupCmdShim();380 const commandArgument = '"(foo|bar>baz|foz)"';381 const {stdout} = await execa(shimPath, [commandArgument]);380 t.is(stdout, commandArgument);382 assert.equal(stdout, commandArgument);383384 const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);383 t.is(stdoutSync, commandArgument);385 assert.equal(stdoutSync, commandArgument);386 });387386 test('Double-escapes explicit batch files excluded from PATHEXT', async t => {388 test('Double-escapes explicit batch files excluded from PATHEXT', async () => {389 const commandArgument = '"& whoami &"';390 const command = path.join(FIXTURES_DIRECTORY, 'echo-shim.cmd');391 const {stdout} = await execa(command, [commandArgument], nodeOnlyOptions);390 t.is(stdout, commandArgument);392 assert.equal(stdout, commandArgument);393394 const {stdout: stdoutSync} = execaSync(command, [commandArgument], nodeOnlyOptions);393 t.is(stdoutSync, commandArgument);395 assert.equal(stdoutSync, commandArgument);396 });397396 test('Runs an explicit shebang script excluded from PATHEXT', async t => {398 test('Runs an explicit shebang script excluded from PATHEXT', async () => {399 const command = path.join(FIXTURES_DIRECTORY, 'echo.js');398 await testResolvesCommand(t, command, nodeOnlyOptions);400 await testResolvesCommand(command, nodeOnlyOptions);401 });402401 test.serial('Double-escapes metacharacters for preferLocal cmd-shims', async t => {403 test('Double-escapes metacharacters for preferLocal cmd-shims', async () => {404 await setupCmdShim();405 const commandArgument = 'a&whoami';406 const originalPathExt = process.env.PATHEXT;407 process.env.PATHEXT = '.EXE';
8 unmodified lines
416 };417418 try {419 const {stdout} = await execa('echo-cmd-shim', [commandArgument], options);418 t.is(stdout, commandArgument);420 assert.equal(stdout, commandArgument);421422 const {stdout: stdoutSync} = execaSync('echo-cmd-shim', [commandArgument], options);421 t.is(stdoutSync, commandArgument);423 assert.equal(stdoutSync, commandArgument);424 } finally {425 if (originalPathExt === undefined) {426 delete process.env.PATHEXT;427 } else {
8 unmodified lines
436// variables or inject commands (the "BatBadBut" class of vulnerabilities). `echo-shim.cmd`437// forwards its arguments to `echo.js`, so the subprocess prints back the exact438// `process.argv` it received: each argument must arrive unchanged and inert.439if (isWindows) {438 const testEscaping = async (t, commandArgument) => {440 const testEscaping = async commandArgument => {441 const {stdout} = await execa('echo-shim.cmd', [commandArgument]);440 t.is(stdout, commandArgument);442 assert.equal(stdout, commandArgument);443444 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', [commandArgument]);443 t.is(stdoutSync, commandArgument);445 assert.equal(stdoutSync, commandArgument);446 };447448 // A `%VAR%` argument must be passed literally, not expanded by `cmd.exe`.447 test('Does not expand environment variables in arguments', testEscaping, '%PATH%');449 test('Does not expand environment variables in arguments', () => testEscaping('%PATH%'));450 // Delayed expansion (`!VAR!`) must not be interpreted either.449 test('Does not expand delayed environment variables in arguments', testEscaping, '!PATH!');451 test('Does not expand delayed environment variables in arguments', () => testEscaping('!PATH!'));452 // An `&` must not be interpreted as a command separator.451 test('Does not allow command injection via `&` in arguments', testEscaping, 'a&b');453 test('Does not allow command injection via `&` in arguments', () => testEscaping('a&b'));454 // A `|` must not be interpreted as a pipe.453 test('Does not allow command injection via `|` in arguments', testEscaping, 'a|whoami');455 test('Does not allow command injection via `|` in arguments', () => testEscaping('a|whoami'));456 // Redirections (`<`, `>`) must not be interpreted.455 test('Does not allow command injection via redirections in arguments', testEscaping, 'a>b<c');457 test('Does not allow command injection via redirections in arguments', () => testEscaping('a>b<c'));458 // Parentheses must not be interpreted as command grouping.457 test('Does not allow command injection via parentheses in arguments', testEscaping, '(whoami)');459 test('Does not allow command injection via parentheses in arguments', () => testEscaping('(whoami)'));460 // A quote followed by an injected command must stay inert.459 test('Does not allow command injection via nested quotes in arguments', testEscaping, '"& whoami &"');461 test('Does not allow command injection via nested quotes in arguments', () => testEscaping('"& whoami &"'));462 // Double quotes must be preserved.461 test('Preserves double quotes in arguments', testEscaping, 'a"b"c');463 test('Preserves double quotes in arguments', () => testEscaping('a"b"c'));464 // Carets are the escape character in `cmd.exe` and must be passed literally.463 test('Preserves carets in arguments', testEscaping, 'a^b^^c');465 test('Preserves carets in arguments', () => testEscaping('a^b^^c'));466 // Backslashes, including trailing ones, must be preserved next to quotes.465 test('Preserves backslashes and double quotes in arguments', testEscaping, 'a\\"b\\\\"c\\');467 test('Preserves backslashes and double quotes in arguments', () => testEscaping('a\\"b\\\\"c\\'));468469 // Every kind of tricky argument must also roundtrip through `cmd.exe` unchanged, not470 // just be inert. Unlike `echo.js` (which resolves to `node.exe` and bypasses `cmd.exe`),471 // `echo-shim.cmd` forces the `cmd.exe` escaping path. This mirrors the roundtrip tests472 // above, but validates the `cmd.exe`-specific escaping rather than Node's native escaping.471 const testCmdRoundtrip = async (t, commandArguments) => {473 const testCmdRoundtrip = async commandArguments => {474 const expectedStdout = commandArguments.join('\n');475476 const {stdout} = await execa('echo-shim.cmd', commandArguments);475 t.is(stdout, expectedStdout);477 assert.equal(stdout, expectedStdout);478479 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', commandArguments);478 t.is(stdoutSync, expectedStdout);480 assert.equal(stdoutSync, expectedStdout);481 };482483 // eslint-disable-next-line no-template-curly-in-string482 test('Roundtrips shell metacharacters through cmd.exe', testCmdRoundtrip, ['()', '[]', '%!', '^', '<', '>', '|', ';', ',', '=', '`', '*', '?', '$HOME', '${x}', '~']);483 test('Roundtrips backslashes and double quotes through cmd.exe', testCmdRoundtrip, ['a\\b', 'a\\\\b', 'a\\', 'a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);484 test('Roundtrips shell metacharacters through cmd.exe', () => testCmdRoundtrip(['()', '[]', '%!', '^', '<', '>', '|', ';', ',', '=', '`', '*', '?', '$HOME', '${x}', '~']));485 test('Roundtrips backslashes and double quotes through cmd.exe', () => testCmdRoundtrip(['a\\b', 'a\\\\b', 'a\\', 'a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']));486 // Long backslash runs must also roundtrip through the `cmd.exe` escaping specifically,487 // which is where the backslash-doubling actually runs. Kept modest to stay under the488 // `cmd.exe` command-line length limit once the backslashes are doubled.487 test('Roundtrips long backslash runs before quotes through cmd.exe', testCmdRoundtrip, [`${'\\'.repeat(200)}"`, '\\'.repeat(200), `a${'\\'.repeat(100)}"b`]);489 test('Roundtrips long backslash runs before quotes through cmd.exe', () => testCmdRoundtrip([`${'\\'.repeat(200)}"`, '\\'.repeat(200), `a${'\\'.repeat(100)}"b`]));490 // The per-length sweep must roundtrip through `cmd.exe` too, since the corrupted doubling491 // is exactly what this escaping path performs.490 test('Roundtrips backslash runs of every length through cmd.exe', testCmdRoundtrip, backslashRunArguments);492 test('Roundtrips backslash runs of every length through cmd.exe', () => testCmdRoundtrip(backslashRunArguments));493 // Consecutive double quotes must survive the `cmd.exe` escaping, each escaped on its own.492 test('Roundtrips consecutive double quotes through cmd.exe', testCmdRoundtrip, ['""', '"""', 'a""b', '""""']);493 test('Roundtrips arguments with spaces through cmd.exe', testCmdRoundtrip, ['a b', ' '.repeat(3), 'foo bar baz', 'André Cruz']);494 test('Roundtrips consecutive double quotes through cmd.exe', () => testCmdRoundtrip(['""', '"""', 'a""b', '""""']));495 test('Roundtrips arguments with spaces through cmd.exe', () => testCmdRoundtrip(['a b', ' '.repeat(3), 'foo bar baz', 'André Cruz']));496497 /*498 `.bat` files re-expand their arguments through `cmd.exe` exactly like `.cmd` files, so they need the same double-escaping.499 `echo-shim.bat` is the `.bat` twin of `echo-shim.cmd`.500 */499 const testBatEscaping = async (t, commandArgument) => {501 const testBatEscaping = async commandArgument => {502 const {stdout} = await execa('echo-shim.bat', [commandArgument]);501 t.is(stdout, commandArgument);503 assert.equal(stdout, commandArgument);504505 const {stdout: stdoutSync} = execaSync('echo-shim.bat', [commandArgument]);504 t.is(stdoutSync, commandArgument);506 assert.equal(stdoutSync, commandArgument);507 };508509 // The same nested-quote injection must stay inert when the batch file is a `.bat`.508 test('Does not allow command injection via nested quotes in `.bat` arguments', testBatEscaping, '"& whoami &"');510 test('Does not allow command injection via nested quotes in `.bat` arguments', () => testBatEscaping('"& whoami &"'));511 // Metacharacters must survive the double `cmd.exe` expansion for `.bat` files too.510 test('Roundtrips shell metacharacters through a `.bat` file', testBatEscaping, '(foo|bar>baz|foz)');512 test('Roundtrips shell metacharacters through a `.bat` file', () => testBatEscaping('(foo|bar>baz|foz)'));513 // A `.bat` file not in `node_modules/.bin/` must still be double-escaped, since the location is irrelevant: any batch file re-expands its arguments.512 test('Does not expand environment variables in `.bat` arguments', testBatEscaping, '%PATH%');514 test('Does not expand environment variables in `.bat` arguments', () => testBatEscaping('%PATH%'));515 // Backslashes, double quotes and metacharacters combined are the trickiest to escape, and must survive the double `cmd.exe` expansion of a `.bat` file intact.514 test('Preserves backslashes, quotes and metacharacters in `.bat` arguments', testBatEscaping, 'a\\"&b\\\\"|c\\');516 test('Preserves backslashes, quotes and metacharacters in `.bat` arguments', () => testBatEscaping('a\\"&b\\\\"|c\\'));517 // Several tricky arguments passed together must each be double-escaped independently and arrive in order, not merged nor reordered.516 test('Roundtrips multiple tricky arguments through a `.bat` file', async t => {518 test('Roundtrips multiple tricky arguments through a `.bat` file', async () => {519 const commandArguments = ['a b', 'c&d', '"e"', 'f\\"g', '%h%'];520 const expectedStdout = commandArguments.join('\n');521522 const {stdout} = await execa('echo-shim.bat', commandArguments);521 t.is(stdout, expectedStdout);523 assert.equal(stdout, expectedStdout);524525 const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments);524 t.is(stdoutSync, expectedStdout);526 assert.equal(stdoutSync, expectedStdout);527 });528529 // `cmd.exe` interprets CR and LF as command separators and provides no way to escape530 // them, so those are rejected to prevent command injection.529 test('Rejects arguments containing a line break', t => {530 t.throws(() => execa('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});531 t.throws(() => execaSync('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});531 test('Rejects arguments containing a line break', () => {532 assertThrows(() => execa('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});533 assertThrows(() => execaSync('echo-shim.cmd', ['a\r\nb']), {instanceOf: TypeError, message: /line break/});534 });535536 // The command itself is validated too, not just its arguments.535 test('Rejects a command containing a line break', t => {536 t.throws(() => execa('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});537 t.throws(() => execaSync('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});537 test('Rejects a command containing a line break', () => {538 assertThrows(() => execa('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});539 assertThrows(() => execaSync('echo\r\nshim.cmd', []), {instanceOf: TypeError, message: /line break/});540 });541542 // A shell escapes the arguments itself, so the line break rejection does not apply.541 test('Does not reject line breaks when using a shell', async t => {542 await t.notThrowsAsync(execa('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));543 t.notThrows(() => execaSync('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));543 test('Does not reject line breaks when using a shell', async () => {544 await assert.doesNotReject(execa('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));545 assert.doesNotThrow(() => execaSync('echo-shim.cmd', ['a\r\nb'], {shell: true, reject: false}));546 });547}
modified:test/arguments/cwd.js+49 added-47 removed
1import assert from 'node:assert/strict';2import {mkdir, rmdir} from 'node:fs/promises';3import path from 'node:path';4import process from 'node:process';5import {pathToFileURL, fileURLToPath} from 'node:url';6import test from 'node:test';7import tempfile from 'tempfile';6import test from 'ava';8import {assertThrows} from '../helpers/assert.js';9import {execa, execaSync} from '../../index.js';10import {FIXTURES_DIRECTORY, setFixtureDirectory} from '../helpers/fixtures-directory.js';11import {majorNodeVersion} from '../helpers/node-version.js';1213setFixtureDirectory();1415const isWindows = process.platform === 'win32';1615const testOptionCwdString = async (t, execaMethod) => {17const testOptionCwdString = async execaMethod => {18 const cwd = '/';19 const {stdout} = await execaMethod('node', ['-p', 'process.cwd()'], {cwd});18 t.is(path.toNamespacedPath(stdout), path.toNamespacedPath(cwd));20 assert.equal(path.toNamespacedPath(stdout), path.toNamespacedPath(cwd));21};2221test('The "cwd" option can be a string', testOptionCwdString, execa);22test('The "cwd" option can be a string - sync', testOptionCwdString, execaSync);23test('The "cwd" option can be a string', () => testOptionCwdString(execa));24test('The "cwd" option can be a string - sync', () => testOptionCwdString(execaSync));2524const testOptionCwdUrl = async (t, execaMethod) => {26const testOptionCwdUrl = async execaMethod => {27 const cwd = '/';28 const cwdUrl = pathToFileURL(cwd);29 const {stdout} = await execaMethod('node', ['-p', 'process.cwd()'], {cwd: cwdUrl});28 t.is(path.toNamespacedPath(stdout), path.toNamespacedPath(cwd));30 assert.equal(path.toNamespacedPath(stdout), path.toNamespacedPath(cwd));31};3231test('The "cwd" option can be a URL', testOptionCwdUrl, execa);32test('The "cwd" option can be a URL - sync', testOptionCwdUrl, execaSync);33test('The "cwd" option can be a URL', () => testOptionCwdUrl(execa));34test('The "cwd" option can be a URL - sync', () => testOptionCwdUrl(execaSync));3534const testOptionCwdInvalid = (t, execaMethod) => {35 t.throws(() => {36const testOptionCwdInvalid = execaMethod => {37 assertThrows(() => {38 execaMethod('empty.js', {cwd: true});39 }, {message: /The "cwd" option must be a string or a file URL: true/});40};4140test('The "cwd" option cannot be an invalid type', testOptionCwdInvalid, execa);41test('The "cwd" option cannot be an invalid type - sync', testOptionCwdInvalid, execaSync);42test('The "cwd" option cannot be an invalid type', () => testOptionCwdInvalid(execa));43test('The "cwd" option cannot be an invalid type - sync', () => testOptionCwdInvalid(execaSync));4443const testErrorCwdDefault = async (t, execaMethod) => {45const testErrorCwdDefault = async execaMethod => {46 const {cwd} = await execaMethod('empty.js');45 t.is(cwd, process.cwd());47 assert.equal(cwd, process.cwd());48};4948test('The "cwd" option defaults to process.cwd()', testErrorCwdDefault, execa);49test('The "cwd" option defaults to process.cwd() - sync', testErrorCwdDefault, execaSync);50test('The "cwd" option defaults to process.cwd()', () => testErrorCwdDefault(execa));51test('The "cwd" option defaults to process.cwd() - sync', () => testErrorCwdDefault(execaSync));5253// Windows does not allow removing a directory used as `cwd` of a running subprocess54if (!isWindows) {55 // Deletes the current directory, which makes `process.cwd()` throw56 const chdirToMissingDirectory = async t => {57 const currentCwd = process.cwd();56 t.teardown(() => {58 t.after(() => {59 process.chdir(currentCwd);60 });6162 const filePath = tempfile();
4 unmodified lines
6768 const testCwdPreSpawn = async (t, execaMethod) => {69 await chdirToMissingDirectory(t);7069 t.throws(() => {71 assertThrows(() => {72 execaMethod('empty.js');73 }, {message: /The current directory does not exist/});74 };7574 test.serial('The "cwd" option default fails if current cwd is missing', testCwdPreSpawn, execa);75 test.serial('The "cwd" option default fails if current cwd is missing - sync', testCwdPreSpawn, execaSync);76 test('The "cwd" option default fails if current cwd is missing', t => testCwdPreSpawn(t, execa));77 test('The "cwd" option default fails if current cwd is missing - sync', t => testCwdPreSpawn(t, execaSync));7879 // The error message mentions the current directory, but computing it must not fail when it has been deleted.80 // Otherwise, this would hide the subprocess' own error, and would throw even with the `reject: false` option.81 const testCwdMissingError = async (t, execaMethod) => {82 await chdirToMissingDirectory(t);8384 const {failed, code, message} = await execaMethod('does_not_exist', {cwd: FIXTURES_DIRECTORY, reject: false});83 t.true(failed);84 t.is(code, 'ENOENT');85 t.true(message.includes('does_not_exist'));85 assert.equal(failed, true);86 assert.equal(code, 'ENOENT');87 assert.ok(message.includes('does_not_exist'));88 };8988 test.serial('The subprocess error is kept if current cwd is missing', testCwdMissingError, execa);89 test.serial('The subprocess error is kept if current cwd is missing - sync', testCwdMissingError, execaSync);90 test('The subprocess error is kept if current cwd is missing', t => testCwdMissingError(t, execa));91 test('The subprocess error is kept if current cwd is missing - sync', t => testCwdMissingError(t, execaSync));9293 // The `cwd` option is valid, so the error message must not mention it at all94 const testCwdMissingValidOption = async (t, execaMethod) => {95 await chdirToMissingDirectory(t);9697 const {message} = await execaMethod('does_not_exist', {cwd: FIXTURES_DIRECTORY, reject: false});96 t.false(message.includes('The "cwd" option'));98 assert.ok(!message.includes('The "cwd" option'));99 };10099 test.serial('The "cwd" option is not reported as invalid if current cwd is missing', testCwdMissingValidOption, execa);100 test.serial('The "cwd" option is not reported as invalid if current cwd is missing - sync', testCwdMissingValidOption, execaSync);101 test('The "cwd" option is not reported as invalid if current cwd is missing', t => testCwdMissingValidOption(t, execa));102 test('The "cwd" option is not reported as invalid if current cwd is missing - sync', t => testCwdMissingValidOption(t, execaSync));103}104105const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};106const cwdTooLong = {cwd: '.'.repeat(1e5), expectedCode: isWindows && majorNodeVersion >= 20 ? 'ENOENT' : 'ENAMETOOLONG', expectedMessage: 'The "cwd" option is invalid'};107// @todo: use import.meta.dirname after dropping support for Node <20.11.0108const cwdNotDirectory = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};109108const testCwdPostSpawn = async (t, {cwd, expectedCode, expectedMessage}, execaMethod) => {110const testCwdPostSpawn = async ({cwd, expectedCode, expectedMessage}, execaMethod) => {111 const {failed, code, message} = await execaMethod('empty.js', {cwd, reject: false});110 t.true(failed);111 t.is(code, expectedCode);112 t.true(message.includes(expectedMessage));113 t.true(message.includes(cwd));112 assert.equal(failed, true);113 assert.equal(code, expectedCode);114 assert.ok(message.includes(expectedMessage));115 assert.ok(message.includes(cwd));116};117116test('The "cwd" option must be an existing file', testCwdPostSpawn, cwdNotExisting, execa);117test('The "cwd" option must be an existing file - sync', testCwdPostSpawn, cwdNotExisting, execaSync);118test('The "cwd" option must not be too long', testCwdPostSpawn, cwdTooLong, execa);119test('The "cwd" option must not be too long - sync', testCwdPostSpawn, cwdTooLong, execaSync);120test('The "cwd" option must be a directory', testCwdPostSpawn, cwdNotDirectory, execa);121test('The "cwd" option must be a directory - sync', testCwdPostSpawn, cwdNotDirectory, execaSync);118test('The "cwd" option must be an existing file', () => testCwdPostSpawn(cwdNotExisting, execa));119test('The "cwd" option must be an existing file - sync', () => testCwdPostSpawn(cwdNotExisting, execaSync));120test('The "cwd" option must not be too long', () => testCwdPostSpawn(cwdTooLong, execa));121test('The "cwd" option must not be too long - sync', () => testCwdPostSpawn(cwdTooLong, execaSync));122test('The "cwd" option must be a directory', () => testCwdPostSpawn(cwdNotDirectory, execa));123test('The "cwd" option must be a directory - sync', () => testCwdPostSpawn(cwdNotDirectory, execaSync));124125const successProperties = {fixtureName: 'empty.js', expectedFailed: false};126const errorProperties = {fixtureName: 'fail.js', expectedFailed: true};127126const testErrorCwd = async (t, execaMethod, {fixtureName, expectedFailed}) => {128const testErrorCwd = async (execaMethod, {fixtureName, expectedFailed}) => {129 const {failed, cwd} = await execaMethod(fixtureName, {cwd: path.relative('.', FIXTURES_DIRECTORY), reject: false});128 t.is(failed, expectedFailed);129 t.is(cwd, FIXTURES_DIRECTORY);130 assert.equal(failed, expectedFailed);131 assert.equal(cwd, FIXTURES_DIRECTORY);132};133132test('result.cwd is defined', testErrorCwd, execa, successProperties);133test('result.cwd is defined - sync', testErrorCwd, execaSync, successProperties);134test('error.cwd is defined', testErrorCwd, execa, errorProperties);135test('error.cwd is defined - sync', testErrorCwd, execaSync, errorProperties);134test('result.cwd is defined', () => testErrorCwd(execa, successProperties));135test('result.cwd is defined - sync', () => testErrorCwd(execaSync, successProperties));136test('error.cwd is defined', () => testErrorCwd(execa, errorProperties));137test('error.cwd is defined - sync', () => testErrorCwd(execaSync, errorProperties));
modified:test/arguments/encoding-option.js+35 added-33 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';67setFixtureDirectory();87const testInvalidEncoding = (t, encoding, message, execaMethod) => {8 const error = t.throws(() => {9const testInvalidEncoding = (encoding, message, execaMethod) => {10 const error = assertThrows(() => {11 execaMethod('empty.js', {encoding});12 });11 t.true(error.message.includes(message));13 assert.ok(error.message.includes(message));14};1516const UNKNOWN_ENCODING_MESSAGE = 'Please rename it to one of';17const getCorrectEncodingMessage = correctEncoding => `Please rename it to "${correctEncoding}"`;1817test('cannot pass unknown encodings', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execa);18test('cannot pass unknown encodings, sync', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execaSync);19test('cannot pass empty encodings', testInvalidEncoding, '', UNKNOWN_ENCODING_MESSAGE, execa);20test('cannot pass encoding: false', testInvalidEncoding, false, UNKNOWN_ENCODING_MESSAGE, execa);21test('cannot pass encoding: Symbol', testInvalidEncoding, Symbol('test'), UNKNOWN_ENCODING_MESSAGE, execa);22test('cannot pass encoding: null', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execa);23test('cannot pass encoding: null, sync', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execaSync);19test('cannot pass unknown encodings', () => testInvalidEncoding('unknown', UNKNOWN_ENCODING_MESSAGE, execa));20test('cannot pass unknown encodings, sync', () => testInvalidEncoding('unknown', UNKNOWN_ENCODING_MESSAGE, execaSync));21test('cannot pass empty encodings', () => testInvalidEncoding('', UNKNOWN_ENCODING_MESSAGE, execa));22test('cannot pass encoding: false', () => testInvalidEncoding(false, UNKNOWN_ENCODING_MESSAGE, execa));23test('cannot pass encoding: Symbol', () => testInvalidEncoding(Symbol('test'), UNKNOWN_ENCODING_MESSAGE, execa));24test('cannot pass encoding: null', () => testInvalidEncoding(null, getCorrectEncodingMessage('buffer'), execa));25test('cannot pass encoding: null, sync', () => testInvalidEncoding(null, getCorrectEncodingMessage('buffer'), execaSync));26/* eslint-disable unicorn/text-encoding-identifier-case -- intentionally testing invalid encoding casing */25test('cannot pass encoding: utf-8', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execa);26test('cannot pass encoding: utf-8, sync', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execaSync);27test('cannot pass encoding: UTF-8', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execa);28test('cannot pass encoding: UTF-8, sync', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execaSync);29test('cannot pass encoding: UTF8', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execa);30test('cannot pass encoding: UTF8, sync', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execaSync);27test('cannot pass encoding: utf-8', () => testInvalidEncoding('utf-8', getCorrectEncodingMessage('utf8'), execa));28test('cannot pass encoding: utf-8, sync', () => testInvalidEncoding('utf-8', getCorrectEncodingMessage('utf8'), execaSync));29test('cannot pass encoding: UTF-8', () => testInvalidEncoding('UTF-8', getCorrectEncodingMessage('utf8'), execa));30test('cannot pass encoding: UTF-8, sync', () => testInvalidEncoding('UTF-8', getCorrectEncodingMessage('utf8'), execaSync));31test('cannot pass encoding: UTF8', () => testInvalidEncoding('UTF8', getCorrectEncodingMessage('utf8'), execa));32test('cannot pass encoding: UTF8, sync', () => testInvalidEncoding('UTF8', getCorrectEncodingMessage('utf8'), execaSync));33/* eslint-enable unicorn/text-encoding-identifier-case */32test('cannot pass encoding: utf-16le', testInvalidEncoding, 'utf-16le', getCorrectEncodingMessage('utf16le'), execa);33test('cannot pass encoding: UTF-16LE', testInvalidEncoding, 'UTF-16LE', getCorrectEncodingMessage('utf16le'), execa);34test('cannot pass encoding: UTF16LE', testInvalidEncoding, 'UTF16LE', getCorrectEncodingMessage('utf16le'), execa);35test('cannot pass encoding: ucs2', testInvalidEncoding, 'ucs2', getCorrectEncodingMessage('utf16le'), execa);36test('cannot pass encoding: UCS2', testInvalidEncoding, 'UCS2', getCorrectEncodingMessage('utf16le'), execa);37test('cannot pass encoding: ucs-2', testInvalidEncoding, 'ucs-2', getCorrectEncodingMessage('utf16le'), execa);38test('cannot pass encoding: UCS-2', testInvalidEncoding, 'UCS-2', getCorrectEncodingMessage('utf16le'), execa);39test('cannot pass encoding: binary', testInvalidEncoding, 'binary', getCorrectEncodingMessage('latin1'), execa);34test('cannot pass encoding: utf-16le', () => testInvalidEncoding('utf-16le', getCorrectEncodingMessage('utf16le'), execa));35test('cannot pass encoding: UTF-16LE', () => testInvalidEncoding('UTF-16LE', getCorrectEncodingMessage('utf16le'), execa));36test('cannot pass encoding: UTF16LE', () => testInvalidEncoding('UTF16LE', getCorrectEncodingMessage('utf16le'), execa));37test('cannot pass encoding: ucs2', () => testInvalidEncoding('ucs2', getCorrectEncodingMessage('utf16le'), execa));38test('cannot pass encoding: UCS2', () => testInvalidEncoding('UCS2', getCorrectEncodingMessage('utf16le'), execa));39test('cannot pass encoding: ucs-2', () => testInvalidEncoding('ucs-2', getCorrectEncodingMessage('utf16le'), execa));40test('cannot pass encoding: UCS-2', () => testInvalidEncoding('UCS-2', getCorrectEncodingMessage('utf16le'), execa));41test('cannot pass encoding: binary', () => testInvalidEncoding('binary', getCorrectEncodingMessage('latin1'), execa));4241test('cannot pass encoding: constructor', testInvalidEncoding, 'constructor', UNKNOWN_ENCODING_MESSAGE, execa);42test('cannot pass encoding: constructor, sync', testInvalidEncoding, 'constructor', UNKNOWN_ENCODING_MESSAGE, execaSync);43test('cannot pass encoding: __proto__', testInvalidEncoding, '__proto__', UNKNOWN_ENCODING_MESSAGE, execa);44test('cannot pass encoding: __proto__, sync', testInvalidEncoding, '__proto__', UNKNOWN_ENCODING_MESSAGE, execaSync);45test('cannot pass encoding: CONSTRUCTOR', testInvalidEncoding, 'CONSTRUCTOR', UNKNOWN_ENCODING_MESSAGE, execa);46test('cannot pass encoding: toString', testInvalidEncoding, 'toString', UNKNOWN_ENCODING_MESSAGE, execa);47test('cannot pass encoding: valueOf', testInvalidEncoding, 'valueOf', UNKNOWN_ENCODING_MESSAGE, execa);48test('cannot pass encoding: hasOwnProperty', testInvalidEncoding, 'hasOwnProperty', UNKNOWN_ENCODING_MESSAGE, execa);43test('cannot pass encoding: constructor', () => testInvalidEncoding('constructor', UNKNOWN_ENCODING_MESSAGE, execa));44test('cannot pass encoding: constructor, sync', () => testInvalidEncoding('constructor', UNKNOWN_ENCODING_MESSAGE, execaSync));45test('cannot pass encoding: __proto__', () => testInvalidEncoding('__proto__', UNKNOWN_ENCODING_MESSAGE, execa));46test('cannot pass encoding: __proto__, sync', () => testInvalidEncoding('__proto__', UNKNOWN_ENCODING_MESSAGE, execaSync));47test('cannot pass encoding: CONSTRUCTOR', () => testInvalidEncoding('CONSTRUCTOR', UNKNOWN_ENCODING_MESSAGE, execa));48test('cannot pass encoding: toString', () => testInvalidEncoding('toString', UNKNOWN_ENCODING_MESSAGE, execa));49test('cannot pass encoding: valueOf', () => testInvalidEncoding('valueOf', UNKNOWN_ENCODING_MESSAGE, execa));50test('cannot pass encoding: hasOwnProperty', () => testInvalidEncoding('hasOwnProperty', UNKNOWN_ENCODING_MESSAGE, execa));
modified:test/arguments/env.js+26 added-19 removed
1import assert from 'node:assert/strict';2import path from 'node:path';3import process from 'node:process';3import test from 'ava';4import test from 'node:test';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory, PATH_KEY, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';78setFixtureDirectory();9process.env.FOO = 'foo';1011const isWindows = process.platform === 'win32';1212test('use environment variables by default', async t => {13test('use environment variables by default', async () => {14 const {stdout} = await execa('environment.js');14 t.deepEqual(stdout.split('\n'), ['foo', 'undefined']);15 assert.deepEqual(stdout.split('\n'), ['foo', 'undefined']);16});1717test('extend environment variables by default', async t => {18test('extend environment variables by default', async () => {19 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}});19 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);20 assert.deepEqual(stdout.split('\n'), ['foo', 'bar']);21});2222test('do not extend environment with `extendEnv: false`', async t => {23test('do not extend environment with `extendEnv: false`', async () => {24 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}, extendEnv: false});24 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);25 assert.deepEqual(stdout.split('\n'), ['undefined', 'bar']);26});2728// `process.env` must not leak when the `env` option is not set, since `extendEnv: false` means only `env` is used.29// The file is spawned with an absolute path since the environment has no `PATH`.30const environmentFile = path.join(FIXTURES_DIRECTORY, 'environment.js');3131const testNoEnvironment = async (t, execaMethod, options) => {32const testNoEnvironment = async (execaMethod, options) => {33 const {stdout} = await execaMethod(process.execPath, [environmentFile], {extendEnv: false, ...options});33 t.deepEqual(stdout.split('\n'), ['undefined', 'undefined']);34 assert.deepEqual(stdout.split('\n'), ['undefined', 'undefined']);35};3636test('do not use process.env with `extendEnv: false` and no `env`', testNoEnvironment, execa, {});37test('do not use process.env with `extendEnv: false` and no `env`, sync', testNoEnvironment, execaSync, {});38test('do not use process.env with `extendEnv: false` and `env: {}`', testNoEnvironment, execa, {env: {}});39test('do not use process.env with `extendEnv: false`, no `env` and `preferLocal`', testNoEnvironment, execa, {preferLocal: true});37test('do not use process.env with `extendEnv: false` and no `env`', () => testNoEnvironment(execa, {}));38test('do not use process.env with `extendEnv: false` and no `env`, sync', () => testNoEnvironment(execaSync, {}));39test('do not use process.env with `extendEnv: false` and `env: {}`', () => testNoEnvironment(execa, {env: {}}));40test('do not use process.env with `extendEnv: false`, no `env` and `preferLocal`', () => testNoEnvironment(execa, {preferLocal: true}));4142// `preferLocal` adds directories to `process.env.PATH` when `env` has no `PATH`, so system commands still resolve43test('use process.env.PATH with `extendEnv: false`, no `env` and `preferLocal`', async () => {44 const {stdout} = await execa('node', ['-p', '"ok"'], {extendEnv: false, preferLocal: true});45 assert.equal(stdout, 'ok');46});4748// The `env` option is kept on a null-prototype object, so the properties it inherits are not passed to the subprocess42const testInheritedEnv = async (t, execaMethod) => {49const testInheritedEnv = async execaMethod => {50 const env = Object.assign(Object.create({FOO: 'foo'}), {BAR: 'bar'});51 const {stdout} = await execaMethod(process.execPath, [environmentFile], {env, extendEnv: false});45 t.deepEqual(stdout.split('\n'), ['undefined', 'bar']);52 assert.deepEqual(stdout.split('\n'), ['undefined', 'bar']);53};5448test('The "env" option does not pass inherited properties', testInheritedEnv, execa);49test('The "env" option does not pass inherited properties, sync', testInheritedEnv, execaSync);55test('The "env" option does not pass inherited properties', () => testInheritedEnv(execa));56test('The "env" option does not pass inherited properties, sync', () => testInheritedEnv(execaSync));5751test('use extend environment with `extendEnv: true` and `shell: true`', async t => {58test('use extend environment with `extendEnv: true` and `shell: true`', async () => {59 process.env.TEST = 'test';60 const command = isWindows ? 'echo %TEST%' : 'echo $TEST';61 const {stdout} = await execa(command, {shell: true, env: {}, extendEnv: true});55 t.is(stdout, 'test');62 assert.equal(stdout, 'test');63 delete process.env.TEST;64});
modified:test/arguments/escape.js+91 added-87 removed
1import assert from 'node:assert/strict';2import {platform} from 'node:process';2import test from 'ava';3import test from 'node:test';4import {assertThrows, assertRejects, assertLike} from '../helpers/assert.js';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';78setFixtureDirectory();910const isWindows = platform === 'win32';1110const testResultCommand = async (t, expected, ...commandArguments) => {11 const {command: failCommand} = await t.throwsAsync(execa('fail.js', commandArguments));12 t.is(failCommand, `fail.js${expected}`);12const testResultCommand = async (expected, ...commandArguments) => {13 const {command: failCommand} = await assertRejects(execa('fail.js', commandArguments));14 assert.equal(failCommand, `fail.js${expected}`);1516 const {command} = await execa('noop.js', commandArguments);15 t.is(command, `noop.js${expected}`);17 assert.equal(command, `noop.js${expected}`);18};1918testResultCommand.title = (message, expected) => `result.command is: ${JSON.stringify(expected)}`;20test('result.command is: " foo bar"', () => testResultCommand(' foo bar', 'foo', 'bar'));21test('result.command is: " baz quz"', () => testResultCommand(' baz quz', 'baz', 'quz'));22test('result.command is: ""', () => testResultCommand(''));2320test(testResultCommand, ' foo bar', 'foo', 'bar');21test(testResultCommand, ' baz quz', 'baz', 'quz');22test(testResultCommand, '');2324// eslint-disable-next-line max-params25const testEscapedCommand = async (t, commandArguments, expectedUnix, expectedWindows, expectedUnixNoIcu = expectedUnix, expectedWindowsNoIcu = expectedWindows) => {25const testEscapedCommand = async (commandArguments, expectedUnix, expectedWindows, expectedUnixNoIcu = expectedUnix, expectedWindowsNoIcu = expectedWindows) => {26 // eslint-disable-next-line no-use-extend-native/no-use-extend-native, unicorn/no-nonstandard-builtin-properties -- `RegExp.isMocked` is a static property added by `escape-no-icu.js`, not a native extension27 const expected = RegExp.isMocked28 ? (isWindows ? expectedWindowsNoIcu : expectedUnixNoIcu)29 : (isWindows ? expectedWindows : expectedUnix);3031 t.like(32 await t.throwsAsync(execa('fail.js', commandArguments)),31 assertLike(32 await assertRejects(execa('fail.js', commandArguments)),33 {escapedCommand: `fail.js ${expected}`},34 );3536 t.like(t.throws(() => {36 assertLike(assertThrows(() => {37 execaSync('fail.js', commandArguments);38 }), {escapedCommand: `fail.js ${expected}`});3940 t.like(40 assertLike(41 await execa('noop.js', commandArguments),42 {escapedCommand: `noop.js ${expected}`},43 );4445 t.like(45 assertLike(46 execaSync('noop.js', commandArguments),47 {escapedCommand: `noop.js ${expected}`},48 );49};5051test('result.escapedCommand - foo bar', testEscapedCommand, ['foo', 'bar'], 'foo bar', 'foo bar');52test('result.escapedCommand - foo\\ bar', testEscapedCommand, ['foo bar'], '\'foo bar\'', '"foo bar"');53test('result.escapedCommand - "foo"', testEscapedCommand, ['"foo"'], '\'"foo"\'', '"""foo"""');54test('result.escapedCommand - \'foo\'', testEscapedCommand, ['\'foo\''], '\'\'\\\'\'foo\'\\\'\'\'', '"\'foo\'"');55test('result.escapedCommand - "0"', testEscapedCommand, ['0'], '0', '0');56test('result.escapedCommand - 0', testEscapedCommand, [0], '0', '0');57test('result.escapedCommand - *', testEscapedCommand, ['*'], '\'*\'', '"*"');58test('result.escapedCommand - .', testEscapedCommand, ['.'], '.', '.');59test('result.escapedCommand - -', testEscapedCommand, ['-'], '-', '-');60test('result.escapedCommand - _', testEscapedCommand, ['_'], '_', '_');61test('result.escapedCommand - /', testEscapedCommand, ['/'], '/', '/');62test('result.escapedCommand - ,', testEscapedCommand, [','], '\',\'', '","');63test('result.escapedCommand - :', testEscapedCommand, [':'], '\':\'', '":"');64test('result.escapedCommand - ;', testEscapedCommand, [';'], '\';\'', '";"');65test('result.escapedCommand - ~', testEscapedCommand, ['~'], '\'~\'', '"~"');66test('result.escapedCommand - %', testEscapedCommand, ['%'], '\'%\'', '"%"');67test('result.escapedCommand - $', testEscapedCommand, ['$'], '\'$\'', '"$"');68test('result.escapedCommand - !', testEscapedCommand, ['!'], '\'!\'', '"!"');69test('result.escapedCommand - ?', testEscapedCommand, ['?'], '\'?\'', '"?"');70test('result.escapedCommand - #', testEscapedCommand, ['#'], '\'#\'', '"#"');71test('result.escapedCommand - &', testEscapedCommand, ['&'], '\'&\'', '"&"');72test('result.escapedCommand - =', testEscapedCommand, ['='], '\'=\'', '"="');73test('result.escapedCommand - @', testEscapedCommand, ['@'], '\'@\'', '"@"');74test('result.escapedCommand - ^', testEscapedCommand, ['^'], '\'^\'', '"^"');75test('result.escapedCommand - `', testEscapedCommand, ['`'], '\'`\'', '"`"');76test('result.escapedCommand - |', testEscapedCommand, ['|'], '\'|\'', '"|"');77test('result.escapedCommand - +', testEscapedCommand, ['+'], '\'+\'', '"+"');78test('result.escapedCommand - \\', testEscapedCommand, ['\\'], '\'\\\'', '"\\"');79test('result.escapedCommand - ()', testEscapedCommand, ['()'], '\'()\'', '"()"');80test('result.escapedCommand - {}', testEscapedCommand, ['{}'], '\'{}\'', '"{}"');81test('result.escapedCommand - []', testEscapedCommand, ['[]'], '\'[]\'', '"[]"');82test('result.escapedCommand - <>', testEscapedCommand, ['<>'], '\'<>\'', '"<>"');83test('result.escapedCommand - ã', testEscapedCommand, ['ã'], '\'ã\'', '"ã"');84test('result.escapedCommand - \\a', testEscapedCommand, ['\u{7}'], '\'\\u0007\'', '"\\u0007"');85test('result.escapedCommand - \\b', testEscapedCommand, ['\b'], '\'\\b\'', '"\\b"');86test('result.escapedCommand - \\e', testEscapedCommand, ['\u{1B}'], '\'\\u001b\'', '"\\u001b"');87test('result.escapedCommand - \\f', testEscapedCommand, ['\f'], '\'\\f\'', '"\\f"');88test('result.escapedCommand - \\n', testEscapedCommand, ['\n'], '\'\\n\'', '"\\n"');89test('result.escapedCommand - \\r\\n', testEscapedCommand, ['\r\n'], '\'\\r\\n\'', '"\\r\\n"');90test('result.escapedCommand - \\t', testEscapedCommand, ['\t'], '\'\\t\'', '"\\t"');91test('result.escapedCommand - \\v', testEscapedCommand, ['\v'], '\'\\u000b\'', '"\\u000b"');92test('result.escapedCommand - \\x01', testEscapedCommand, ['\u{1}'], '\'\\u0001\'', '"\\u0001"');93test('result.escapedCommand - \\x7f', testEscapedCommand, ['\u{7F}'], '\'\\u007f\'', '"\\u007f"');94test('result.escapedCommand - \\u0085', testEscapedCommand, ['\u{85}'], '\'\\u0085\'', '"\\u0085"');95test('result.escapedCommand - \\u2000', testEscapedCommand, ['\u{2000}'], '\'\\u2000\'', '"\\u2000"');96test('result.escapedCommand - \\u200E', testEscapedCommand, ['\u{200E}'], '\'\\u200e\'', '"\\u200e"', '\'\u{200E}\'', '"\u{200E}"');97test('result.escapedCommand - \\u2028', testEscapedCommand, ['\u{2028}'], '\'\\u2028\'', '"\\u2028"');98test('result.escapedCommand - \\u2029', testEscapedCommand, ['\u{2029}'], '\'\\u2029\'', '"\\u2029"');99test('result.escapedCommand - \\u5555', testEscapedCommand, ['\u{5555}'], '\'\u{5555}\'', '"\u{5555}"');100test('result.escapedCommand - \\uD800', testEscapedCommand, ['\u{D800}'], '\'\\ud800\'', '"\\ud800"', '\'\u{D800}\'', '"\u{D800}"');101test('result.escapedCommand - \\uE000', testEscapedCommand, ['\u{E000}'], '\'\\ue000\'', '"\\ue000"', '\'\u{E000}\'', '"\u{E000}"');102test('result.escapedCommand - \\U1D172', testEscapedCommand, ['\u{1D172}'], '\'\u{1D172}\'', '"\u{1D172}"');103test('result.escapedCommand - \\U1D173', testEscapedCommand, ['\u{1D173}'], '\'\\U1d173\'', '"\\U1d173"', '\'\u{1D173}\'', '"\u{1D173}"');104test('result.escapedCommand - \\U10FFFD', testEscapedCommand, ['\u{10FFFD}'], '\'\\U10fffd\'', '"\\U10fffd"', '\'\u{10FFFD}\'', '"\u{10FFFD}"');51test('result.escapedCommand - foo bar', () => testEscapedCommand(['foo', 'bar'], 'foo bar', 'foo bar'));52test('result.escapedCommand - foo\\ bar', () => testEscapedCommand(['foo bar'], '\'foo bar\'', '"foo bar"'));53test('result.escapedCommand - "foo"', () => testEscapedCommand(['"foo"'], '\'"foo"\'', '"""foo"""'));54test('result.escapedCommand - \'foo\'', () => testEscapedCommand(['\'foo\''], '\'\'\\\'\'foo\'\\\'\'\'', '"\'foo\'"'));55test('result.escapedCommand - "0"', () => testEscapedCommand(['0'], '0', '0'));56test('result.escapedCommand - 0', () => testEscapedCommand([0], '0', '0'));57test('result.escapedCommand - *', () => testEscapedCommand(['*'], '\'*\'', '"*"'));58test('result.escapedCommand - .', () => testEscapedCommand(['.'], '.', '.'));59test('result.escapedCommand - -', () => testEscapedCommand(['-'], '-', '-'));60test('result.escapedCommand - _', () => testEscapedCommand(['_'], '_', '_'));61test('result.escapedCommand - /', () => testEscapedCommand(['/'], '/', '/'));62test('result.escapedCommand - ,', () => testEscapedCommand([','], '\',\'', '","'));63test('result.escapedCommand - :', () => testEscapedCommand([':'], '\':\'', '":"'));64test('result.escapedCommand - ;', () => testEscapedCommand([';'], '\';\'', '";"'));65test('result.escapedCommand - ~', () => testEscapedCommand(['~'], '\'~\'', '"~"'));66test('result.escapedCommand - %', () => testEscapedCommand(['%'], '\'%\'', '"%"'));67test('result.escapedCommand - $', () => testEscapedCommand(['$'], '\'$\'', '"$"'));68test('result.escapedCommand - !', () => testEscapedCommand(['!'], '\'!\'', '"!"'));69test('result.escapedCommand - ?', () => testEscapedCommand(['?'], '\'?\'', '"?"'));70test('result.escapedCommand - #', () => testEscapedCommand(['#'], '\'#\'', '"#"'));71test('result.escapedCommand - &', () => testEscapedCommand(['&'], '\'&\'', '"&"'));72test('result.escapedCommand - =', () => testEscapedCommand(['='], '\'=\'', '"="'));73test('result.escapedCommand - @', () => testEscapedCommand(['@'], '\'@\'', '"@"'));74test('result.escapedCommand - ^', () => testEscapedCommand(['^'], '\'^\'', '"^"'));75test('result.escapedCommand - `', () => testEscapedCommand(['`'], '\'`\'', '"`"'));76test('result.escapedCommand - |', () => testEscapedCommand(['|'], '\'|\'', '"|"'));77test('result.escapedCommand - +', () => testEscapedCommand(['+'], '\'+\'', '"+"'));78test('result.escapedCommand - \\', () => testEscapedCommand(['\\'], '\'\\\'', '"\\"'));79test('result.escapedCommand - ()', () => testEscapedCommand(['()'], '\'()\'', '"()"'));80test('result.escapedCommand - {}', () => testEscapedCommand(['{}'], '\'{}\'', '"{}"'));81test('result.escapedCommand - []', () => testEscapedCommand(['[]'], '\'[]\'', '"[]"'));82test('result.escapedCommand - <>', () => testEscapedCommand(['<>'], '\'<>\'', '"<>"'));83test('result.escapedCommand - ã', () => testEscapedCommand(['ã'], '\'ã\'', '"ã"'));84test('result.escapedCommand - \\a', () => testEscapedCommand(['\u{7}'], '\'\\u0007\'', '"\\u0007"'));85test('result.escapedCommand - \\b', () => testEscapedCommand(['\b'], '\'\\b\'', '"\\b"'));86test('result.escapedCommand - \\e', () => testEscapedCommand(['\u{1B}'], '\'\\u001b\'', '"\\u001b"'));87test('result.escapedCommand - \\f', () => testEscapedCommand(['\f'], '\'\\f\'', '"\\f"'));88test('result.escapedCommand - \\n', () => testEscapedCommand(['\n'], '\'\\n\'', '"\\n"'));89test('result.escapedCommand - \\r\\n', () => testEscapedCommand(['\r\n'], '\'\\r\\n\'', '"\\r\\n"'));90test('result.escapedCommand - \\t', () => testEscapedCommand(['\t'], '\'\\t\'', '"\\t"'));91test('result.escapedCommand - \\v', () => testEscapedCommand(['\v'], '\'\\u000b\'', '"\\u000b"'));92test('result.escapedCommand - \\x01', () => testEscapedCommand(['\u{1}'], '\'\\u0001\'', '"\\u0001"'));93test('result.escapedCommand - \\x7f', () => testEscapedCommand(['\u{7F}'], '\'\\u007f\'', '"\\u007f"'));94test('result.escapedCommand - \\u0085', () => testEscapedCommand(['\u{85}'], '\'\\u0085\'', '"\\u0085"'));95test('result.escapedCommand - \\u2000', () => testEscapedCommand(['\u{2000}'], '\'\\u2000\'', '"\\u2000"'));96test('result.escapedCommand - \\u200E', () => testEscapedCommand(['\u{200E}'], '\'\\u200e\'', '"\\u200e"', '\'\u{200E}\'', '"\u{200E}"'));97test('result.escapedCommand - \\u2028', () => testEscapedCommand(['\u{2028}'], '\'\\u2028\'', '"\\u2028"'));98test('result.escapedCommand - \\u2029', () => testEscapedCommand(['\u{2029}'], '\'\\u2029\'', '"\\u2029"'));99test('result.escapedCommand - \\u5555', () => testEscapedCommand(['\u{5555}'], '\'\u{5555}\'', '"\u{5555}"'));100test('result.escapedCommand - \\uD800', () => testEscapedCommand(['\u{D800}'], '\'\\ud800\'', '"\\ud800"', '\'\u{D800}\'', '"\u{D800}"'));101test('result.escapedCommand - \\uE000', () => testEscapedCommand(['\u{E000}'], '\'\\ue000\'', '"\\ue000"', '\'\u{E000}\'', '"\u{E000}"'));102test('result.escapedCommand - \\U1D172', () => testEscapedCommand(['\u{1D172}'], '\'\u{1D172}\'', '"\u{1D172}"'));103test('result.escapedCommand - \\U1D173', () => testEscapedCommand(['\u{1D173}'], '\'\\U1d173\'', '"\\U1d173"', '\'\u{1D173}\'', '"\u{1D173}"'));104test('result.escapedCommand - \\U10FFFD', () => testEscapedCommand(['\u{10FFFD}'], '\'\\U10fffd\'', '"\\U10fffd"', '\'\u{10FFFD}\'', '"\u{10FFFD}"'));105106/*107`result.escapedCommand` is documented as safe to copy and paste in a terminal, so a shell must parse it back to the exact same arguments.108Control characters are excluded, since those are intentionally escaped with a Bash-specific notation instead.109*/110if (!isWindows) {111 const testShellRoundTrip = async (t, commandArguments) => {111 const testShellRoundTrip = async commandArguments => {112 const {escapedCommand} = await execa('print-arguments.js', commandArguments);113 const {stdout} = await execa('/bin/sh', ['-c', escapedCommand]);114 t.deepEqual(JSON.parse(stdout), commandArguments);114 assert.deepEqual(JSON.parse(stdout), commandArguments);115 };116117 testShellRoundTrip.title = (message, commandArguments) => `result.escapedCommand can be pasted in a shell: ${JSON.stringify(commandArguments)}`;117 const shellRoundTripArguments = [118 ['foo', 'bar'],119 ['foo bar'],120 ['\'foo\'', '"bar"'],121 ['it\'s', 'a\'\'b'],122 ['foo\\bar', '\\', '\\\\'],123 // eslint-disable-next-line no-template-curly-in-string124 ['$FOO', '${FOO}', '$(echo foo)'],125 ['`echo foo`'],126 ['foo;bar', 'foo&&bar', 'foo|bar', 'foo>bar'],127 ['*', '?', '[a-z]', '{a,b}'],128 ['~', '#foo', '!foo', '-foo', '--foo=bar'],129 ['', 'foo'],130 ['ã', '😀'],131 ['\'"`$\\!*&;| '],132 ];133119 test(testShellRoundTrip, ['foo', 'bar']);120 test(testShellRoundTrip, ['foo bar']);121 test(testShellRoundTrip, ['\'foo\'', '"bar"']);122 test(testShellRoundTrip, ['it\'s', 'a\'\'b']);123 test(testShellRoundTrip, ['foo\\bar', '\\', '\\\\']);124 // eslint-disable-next-line no-template-curly-in-string125 test(testShellRoundTrip, ['$FOO', '${FOO}', '$(echo foo)']);126 test(testShellRoundTrip, ['`echo foo`']);127 test(testShellRoundTrip, ['foo;bar', 'foo&&bar', 'foo|bar', 'foo>bar']);128 test(testShellRoundTrip, ['*', '?', '[a-z]', '{a,b}']);129 test(testShellRoundTrip, ['~', '#foo', '!foo', '-foo', '--foo=bar']);130 test(testShellRoundTrip, ['', 'foo']);131 test(testShellRoundTrip, ['ã', '😀']);132 test(testShellRoundTrip, ['\'"`$\\!*&;| ']);134 for (const commandArguments of shellRoundTripArguments) {135 test(`result.escapedCommand can be pasted in a shell: ${JSON.stringify(commandArguments)}`, () => testShellRoundTrip(commandArguments));136 }137}
modified:test/arguments/fd-options.js+299 added-305 removed
1import assert from 'node:assert/strict';2import {PassThrough} from 'node:stream';3import {spawn} from 'node:child_process';4import process from 'node:process';4import test from 'ava';5import test from 'node:test';6import {assertThrows} from '../helpers/assert.js';7import {execa} from '../../index.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9import {fullStdio, getStdio} from '../helpers/stdio.js';10import {getEarlyErrorSubprocess} from '../helpers/early-error.js';
4 unmodified lines
15const getMessage = message => Array.isArray(message)16 ? `"${message[0]}: ${message[1]}" option is incompatible`17 : message;1817const testPipeError = async (t, {19const testPipeError = async ({20 message,21 sourceOptions = {},22 destinationOptions = {},23 getSource = () => execa('empty.js', sourceOptions),
3 unmodified lines
27 to,28}) => {29 const source = getSource();30 const pipePromise = isScript ? source.pipe({from, to})`empty.js` : source.pipe(getDestination(), {from, to});29 await assertPipeError(t, pipePromise, getMessage(message));31 await assertPipeError(pipePromise, getMessage(message));32};3332const testNodeStream = async (t, {34const testNodeStream = async ({35 message,36 sourceOptions = {},37 getSource = () => execa('empty.js', sourceOptions),38 from,39 to,40 writable = to !== undefined,41}) => {42 assertNodeStream({41 t,43 message,44 getSource,45 from,46 to,47 methodName: writable ? 'writable' : 'readable',48 });49 assertNodeStream({49 t,50 message,51 getSource,52 from,53 to,54 methodName: 'duplex',55 });56};5758const assertNodeStream = ({t, message, getSource, from, to, methodName}) => {59 const error = t.throws(() => {58const assertNodeStream = ({message, getSource, from, to, methodName}) => {59 const error = assertThrows(() => {60 getSource()[methodName]({from, to});61 });62 t.true(error.message.includes(getMessage(message)));62 assert.ok(error.message.includes(getMessage(message)));63};6465const testIterable = async (t, {65const testIterable = async ({66 message,67 sourceOptions = {},68 getSource = () => execa('empty.js', sourceOptions),69 from,70}) => {71 const error = t.throws(() => {71 const error = assertThrows(() => {72 getSource().iterable({from});73 });74 t.true(error.message.includes(getMessage(message)));74 assert.ok(error.message.includes(getMessage(message)));75};7677test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {77test('Must set "all" option to "true" to use .pipe("all")', () => testPipeError({78 from: 'all',79 message: '"all" option must be true',80});81test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {80}));81test('Must set "all" option to "true" to use .duplex("all")', () => testNodeStream({82 from: 'all',83 message: '"all" option must be true',84});85test('Must set "all" option to "true" to use .iterable("all")', testIterable, {84}));85test('Must set "all" option to "true" to use .iterable("all")', () => testIterable({86 from: 'all',87 message: '"all" option must be true',88});89test('.pipe() cannot pipe to non-subprocesses', testPipeError, {88}));89test('.pipe() cannot pipe to non-subprocesses', () => testPipeError({90 getDestination: () => new PassThrough(),91 message: 'an Execa subprocess',92});93test('.pipe() cannot pipe to non-Execa subprocesses', testPipeError, {92}));93test('.pipe() cannot pipe to non-Execa subprocesses', () => testPipeError({94 getDestination: () => spawn('node', ['--version']),95 message: 'an Execa subprocess',96});97test('.pipe() "from" option cannot be "stdin"', testPipeError, {96}));97test('.pipe() "from" option cannot be "stdin"', () => testPipeError({98 from: 'stdin',99 message: '"from" must not be',100});101test('.duplex() "from" option cannot be "stdin"', testNodeStream, {100}));101test('.duplex() "from" option cannot be "stdin"', () => testNodeStream({102 from: 'stdin',103 message: '"from" must not be',104});105test('.iterable() "from" option cannot be "stdin"', testIterable, {104}));105test('.iterable() "from" option cannot be "stdin"', () => testIterable({106 from: 'stdin',107 message: '"from" must not be',108});109test('$.pipe() "from" option cannot be "stdin"', testPipeError, {108}));109test('$.pipe() "from" option cannot be "stdin"', () => testPipeError({110 from: 'stdin',111 isScript: true,112 message: '"from" must not be',113});114test('.pipe() "to" option cannot be "stdout"', testPipeError, {113}));114test('.pipe() "to" option cannot be "stdout"', () => testPipeError({115 to: 'stdout',116 message: '"to" must not be',117});118test('.duplex() "to" option cannot be "stdout"', testNodeStream, {117}));118test('.duplex() "to" option cannot be "stdout"', () => testNodeStream({119 to: 'stdout',120 message: '"to" must not be',121});122test('$.pipe() "to" option cannot be "stdout"', testPipeError, {121}));122test('$.pipe() "to" option cannot be "stdout"', () => testPipeError({123 to: 'stdout',124 isScript: true,125 message: '"to" must not be',126});127test('.pipe() "from" option cannot be any string', testPipeError, {126}));127test('.pipe() "from" option cannot be any string', () => testPipeError({128 from: 'other',129 message: 'must be "stdout", "stderr", "all"',130});131test('.duplex() "from" option cannot be any string', testNodeStream, {130}));131test('.duplex() "from" option cannot be any string', () => testNodeStream({132 from: 'other',133 message: 'must be "stdout", "stderr", "all"',134});135test('.iterable() "from" option cannot be any string', testIterable, {134}));135test('.iterable() "from" option cannot be any string', () => testIterable({136 from: 'other',137 message: 'must be "stdout", "stderr", "all"',138});139test('.pipe() "to" option cannot be any string', testPipeError, {138}));139test('.pipe() "to" option cannot be any string', () => testPipeError({140 to: 'other',141 message: 'must be "stdin"',142});143test('.duplex() "to" option cannot be any string', testNodeStream, {142}));143test('.duplex() "to" option cannot be any string', () => testNodeStream({144 to: 'other',145 message: 'must be "stdin"',146});147test('.pipe() "from" option cannot be a number without "fd"', testPipeError, {146}));147test('.pipe() "from" option cannot be a number without "fd"', () => testPipeError({148 from: '1',149 message: 'must be "stdout", "stderr", "all"',150});151test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {150}));151test('.duplex() "from" option cannot be a number without "fd"', () => testNodeStream({152 from: '1',153 message: 'must be "stdout", "stderr", "all"',154});155test('.iterable() "from" option cannot be a number without "fd"', testIterable, {154}));155test('.iterable() "from" option cannot be a number without "fd"', () => testIterable({156 from: '1',157 message: 'must be "stdout", "stderr", "all"',158});159test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {158}));159test('.pipe() "to" option cannot be a number without "fd"', () => testPipeError({160 to: '0',161 message: 'must be "stdin"',162});163test('.duplex() "to" option cannot be a number without "fd"', testNodeStream, {162}));163test('.duplex() "to" option cannot be a number without "fd"', () => testNodeStream({164 to: '0',165 message: 'must be "stdin"',166});167test('.pipe() "from" option cannot be just "fd"', testPipeError, {166}));167test('.pipe() "from" option cannot be just "fd"', () => testPipeError({168 from: 'fd',169 message: 'must be "stdout", "stderr", "all"',170});171test('.duplex() "from" option cannot be just "fd"', testNodeStream, {170}));171test('.duplex() "from" option cannot be just "fd"', () => testNodeStream({172 from: 'fd',173 message: 'must be "stdout", "stderr", "all"',174});175test('.iterable() "from" option cannot be just "fd"', testIterable, {174}));175test('.iterable() "from" option cannot be just "fd"', () => testIterable({176 from: 'fd',177 message: 'must be "stdout", "stderr", "all"',178});179test('.pipe() "to" option cannot be just "fd"', testPipeError, {178}));179test('.pipe() "to" option cannot be just "fd"', () => testPipeError({180 to: 'fd',181 message: 'must be "stdin"',182});183test('.duplex() "to" option cannot be just "fd"', testNodeStream, {182}));183test('.duplex() "to" option cannot be just "fd"', () => testNodeStream({184 to: 'fd',185 message: 'must be "stdin"',186});187test('.pipe() "from" option cannot be a float', testPipeError, {186}));187test('.pipe() "from" option cannot be a float', () => testPipeError({188 from: 'fd1.5',189 message: 'must be "stdout", "stderr", "all"',190});191test('.duplex() "from" option cannot be a float', testNodeStream, {190}));191test('.duplex() "from" option cannot be a float', () => testNodeStream({192 from: 'fd1.5',193 message: 'must be "stdout", "stderr", "all"',194});195test('.iterable() "from" option cannot be a float', testIterable, {194}));195test('.iterable() "from" option cannot be a float', () => testIterable({196 from: 'fd1.5',197 message: 'must be "stdout", "stderr", "all"',198});199test('.pipe() "to" option cannot be a float', testPipeError, {198}));199test('.pipe() "to" option cannot be a float', () => testPipeError({200 to: 'fd1.5',201 message: 'must be "stdin"',202});203test('.duplex() "to" option cannot be a float', testNodeStream, {202}));203test('.duplex() "to" option cannot be a float', () => testNodeStream({204 to: 'fd1.5',205 message: 'must be "stdin"',206});207test('.pipe() "from" option cannot be a negative number', testPipeError, {206}));207test('.pipe() "from" option cannot be a negative number', () => testPipeError({208 from: 'fd-1',209 message: 'must be "stdout", "stderr", "all"',210});211test('.duplex() "from" option cannot be a negative number', testNodeStream, {210}));211test('.duplex() "from" option cannot be a negative number', () => testNodeStream({212 from: 'fd-1',213 message: 'must be "stdout", "stderr", "all"',214});215test('.iterable() "from" option cannot be a negative number', testIterable, {214}));215test('.iterable() "from" option cannot be a negative number', () => testIterable({216 from: 'fd-1',217 message: 'must be "stdout", "stderr", "all"',218});219test('.pipe() "to" option cannot be a negative number', testPipeError, {218}));219test('.pipe() "to" option cannot be a negative number', () => testPipeError({220 to: 'fd-1',221 message: 'must be "stdin"',222});223test('.duplex() "to" option cannot be a negative number', testNodeStream, {222}));223test('.duplex() "to" option cannot be a negative number', () => testNodeStream({224 to: 'fd-1',225 message: 'must be "stdin"',226});227test('.pipe() "from" option cannot be a non-existing file descriptor', testPipeError, {226}));227test('.pipe() "from" option cannot be a non-existing file descriptor', () => testPipeError({228 from: 'fd3',229 message: 'file descriptor does not exist',230});231test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {230}));231test('.duplex() "from" cannot be a non-existing file descriptor', () => testNodeStream({232 from: 'fd3',233 message: 'file descriptor does not exist',234});235test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {234}));235test('.iterable() "from" cannot be a non-existing file descriptor', () => testIterable({236 from: 'fd3',237 message: 'file descriptor does not exist',238});239test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {238}));239test('.pipe() "to" option cannot be a non-existing file descriptor', () => testPipeError({240 to: 'fd3',241 message: 'file descriptor does not exist',242});243test('.duplex() "to" cannot be a non-existing file descriptor', testNodeStream, {242}));243test('.duplex() "to" cannot be a non-existing file descriptor', () => testNodeStream({244 to: 'fd3',245 message: 'file descriptor does not exist',246});247test('.pipe() "from" option cannot be an input file descriptor', testPipeError, {246}));247test('.pipe() "from" option cannot be an input file descriptor', () => testPipeError({248 sourceOptions: getStdio(3, new Uint8Array()),249 from: 'fd3',250 message: 'must be a readable stream',251});252test('.duplex() "from" option cannot be an input file descriptor', testNodeStream, {251}));252test('.duplex() "from" option cannot be an input file descriptor', () => testNodeStream({253 sourceOptions: getStdio(3, new Uint8Array()),254 from: 'fd3',255 message: 'must be a readable stream',256});257test('.iterable() "from" option cannot be an input file descriptor', testIterable, {256}));257test('.iterable() "from" option cannot be an input file descriptor', () => testIterable({258 sourceOptions: getStdio(3, new Uint8Array()),259 from: 'fd3',260 message: 'must be a readable stream',261});262test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {261}));262test('.pipe() "to" option cannot be an output file descriptor', () => testPipeError({263 destinationOptions: fullStdio,264 to: 'fd3',265 message: 'must be a writable stream',266});267test('.duplex() "to" option cannot be an output file descriptor', testNodeStream, {266}));267test('.duplex() "to" option cannot be an output file descriptor', () => testNodeStream({268 sourceOptions: fullStdio,269 to: 'fd3',270 message: 'must be a writable stream',271});272test('.duplex() "to" option on an output file descriptor suggests the input-pipe syntax', testNodeStream, {271}));272test('.duplex() "to" option on an output file descriptor suggests the input-pipe syntax', () => testNodeStream({273 sourceOptions: fullStdio,274 to: 'fd3',275 message: '{value: \'pipe\', input: true}',276});277test('.pipe() "to" option cannot be "all"', testPipeError, {276}));277test('.pipe() "to" option cannot be "all"', () => testPipeError({278 destinationOptions: fullStdio,279 to: 'all',280 message: 'must be a writable stream',281});282test('.duplex() "to" option cannot be "all"', testNodeStream, {281}));282test('.duplex() "to" option cannot be "all"', () => testNodeStream({283 sourceOptions: fullStdio,284 to: 'all',285 message: 'must be a writable stream',286});287test('Cannot set "stdout" option to "ignore" to use .pipe()', testPipeError, {286}));287test('Cannot set "stdout" option to "ignore" to use .pipe()', () => testPipeError({288 sourceOptions: {stdout: 'ignore'},289 message: ['stdout', '\'ignore\''],290});291test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {290}));291test('Cannot set "stdout" option to "ignore" to use .duplex()', () => testNodeStream({292 sourceOptions: {stdout: 'ignore'},293 message: ['stdout', '\'ignore\''],294});295test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {294}));295test('Cannot set "stdout" option to "ignore" to use .iterable()', () => testIterable({296 sourceOptions: {stdout: 'ignore'},297 message: ['stdout', '\'ignore\''],298});299test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {298}));299test('Cannot set "stdin" option to "ignore" to use .pipe()', () => testPipeError({300 destinationOptions: {stdin: 'ignore'},301 message: ['stdin', '\'ignore\''],302});303test('Cannot set "stdin" option to "ignore" to use .duplex()', testNodeStream, {302}));303test('Cannot set "stdin" option to "ignore" to use .duplex()', () => testNodeStream({304 sourceOptions: {stdin: 'ignore'},305 message: ['stdin', '\'ignore\''],306 writable: true,307});308test('Cannot set "stdout" option to "ignore" to use .pipe(1)', testPipeError, {307}));308test('Cannot set "stdout" option to "ignore" to use .pipe(1)', () => testPipeError({309 sourceOptions: {stdout: 'ignore'},310 from: 'fd1',311 message: ['stdout', '\'ignore\''],312});313test('Cannot set "stdout" option to "ignore" to use .duplex(1)', testNodeStream, {312}));313test('Cannot set "stdout" option to "ignore" to use .duplex(1)', () => testNodeStream({314 sourceOptions: {stdout: 'ignore'},315 from: 'fd1',316 message: ['stdout', '\'ignore\''],317});318test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {317}));318test('Cannot set "stdout" option to "ignore" to use .iterable(1)', () => testIterable({319 sourceOptions: {stdout: 'ignore'},320 from: 'fd1',321 message: ['stdout', '\'ignore\''],322});323test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {322}));323test('Cannot set "stdin" option to "ignore" to use .pipe(0)', () => testPipeError({324 destinationOptions: {stdin: 'ignore'},325 message: ['stdin', '\'ignore\''],326 to: 'fd0',327});328test('Cannot set "stdin" option to "ignore" to use .duplex(0)', testNodeStream, {327}));328test('Cannot set "stdin" option to "ignore" to use .duplex(0)', () => testNodeStream({329 sourceOptions: {stdin: 'ignore'},330 message: ['stdin', '\'ignore\''],331 to: 'fd0',332});333test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', testPipeError, {332}));333test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', () => testPipeError({334 sourceOptions: {stdout: 'ignore'},335 from: 'stdout',336 message: ['stdout', '\'ignore\''],337});338test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', testNodeStream, {337}));338test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', () => testNodeStream({339 sourceOptions: {stdout: 'ignore'},340 from: 'stdout',341 message: ['stdout', '\'ignore\''],342});343test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {342}));343test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', () => testIterable({344 sourceOptions: {stdout: 'ignore'},345 from: 'stdout',346 message: ['stdout', '\'ignore\''],347});348test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {347}));348test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', () => testPipeError({349 destinationOptions: {stdin: 'ignore'},350 message: ['stdin', '\'ignore\''],351 to: 'stdin',352});353test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', testNodeStream, {352}));353test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', () => testNodeStream({354 sourceOptions: {stdin: 'ignore'},355 message: ['stdin', '\'ignore\''],356 to: 'stdin',357});358test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', testPipeError, {357}));358test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', () => testPipeError({359 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},360 message: ['stdout', '\'ignore\''],361});362test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {361}));362test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', () => testNodeStream({363 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},364 message: ['stdout', '\'ignore\''],365});366test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {365}));366test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', () => testIterable({367 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},368 message: ['stdout', '\'ignore\''],369});370test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', testPipeError, {369}));370test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', () => testPipeError({371 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},372 from: 'fd1',373 message: ['stdout', '\'ignore\''],374});375test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(1)', testNodeStream, {374}));375test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(1)', () => testNodeStream({376 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},377 from: 'fd1',378 message: ['stdout', '\'ignore\''],379});380test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', testIterable, {379}));380test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', () => testIterable({381 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},382 from: 'fd1',383 message: ['stdout', '\'ignore\''],384});385test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', testPipeError, {384}));385test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', () => testPipeError({386 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},387 from: 'stdout',388 message: ['stdout', '\'ignore\''],389});390test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stdout")', testNodeStream, {389}));390test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stdout")', () => testNodeStream({391 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},392 from: 'stdout',393 message: ['stdout', '\'ignore\''],394});395test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', testIterable, {394}));395test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', () => testIterable({396 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},397 from: 'stdout',398 message: ['stdout', '\'ignore\''],399});400test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {399}));400test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', () => testPipeError({401 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},402 message: ['stdio[1]', '\'ignore\''],403});404test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {403}));404test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', () => testNodeStream({405 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},406 message: ['stdio[1]', '\'ignore\''],407});408test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {407}));408test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', () => testIterable({409 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},410 message: ['stdio[1]', '\'ignore\''],411});412test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {411}));412test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', () => testPipeError({413 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},414 message: ['stdio[0]', '\'ignore\''],415});416test('Cannot set "stdio[0]" option to "ignore" to use .duplex()', testNodeStream, {415}));416test('Cannot set "stdio[0]" option to "ignore" to use .duplex()', () => testNodeStream({417 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},418 message: ['stdio[0]', '\'ignore\''],419 writable: true,420});421test('Cannot set "stdio[1]" option to "ignore" to use .pipe(1)', testPipeError, {420}));421test('Cannot set "stdio[1]" option to "ignore" to use .pipe(1)', () => testPipeError({422 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},423 from: 'fd1',424 message: ['stdio[1]', '\'ignore\''],425});426test('Cannot set "stdio[1]" option to "ignore" to use .duplex(1)', testNodeStream, {425}));426test('Cannot set "stdio[1]" option to "ignore" to use .duplex(1)', () => testNodeStream({427 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},428 from: 'fd1',429 message: ['stdio[1]', '\'ignore\''],430});431test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', testIterable, {430}));431test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', () => testIterable({432 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},433 from: 'fd1',434 message: ['stdio[1]', '\'ignore\''],435});436test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', testPipeError, {435}));436test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', () => testPipeError({437 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},438 message: ['stdio[0]', '\'ignore\''],439 to: 'fd0',440});441test('Cannot set "stdio[0]" option to "ignore" to use .duplex(0)', testNodeStream, {440}));441test('Cannot set "stdio[0]" option to "ignore" to use .duplex(0)', () => testNodeStream({442 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},443 message: ['stdio[0]', '\'ignore\''],444 to: 'fd0',445});446test('Cannot set "stdio[1]" option to "ignore" to use .pipe("stdout")', testPipeError, {445}));446test('Cannot set "stdio[1]" option to "ignore" to use .pipe("stdout")', () => testPipeError({447 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},448 from: 'stdout',449 message: ['stdio[1]', '\'ignore\''],450});451test('Cannot set "stdio[1]" option to "ignore" to use .duplex("stdout")', testNodeStream, {450}));451test('Cannot set "stdio[1]" option to "ignore" to use .duplex("stdout")', () => testNodeStream({452 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},453 from: 'stdout',454 message: ['stdio[1]', '\'ignore\''],455});456test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', testIterable, {455}));456test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', () => testIterable({457 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},458 from: 'stdout',459 message: ['stdio[1]', '\'ignore\''],460});461test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', testPipeError, {460}));461test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', () => testPipeError({462 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},463 message: ['stdio[0]', '\'ignore\''],464 to: 'stdin',465});466test('Cannot set "stdio[0]" option to "ignore" to use .duplex("stdin")', testNodeStream, {465}));466test('Cannot set "stdio[0]" option to "ignore" to use .duplex("stdin")', () => testNodeStream({467 sourceOptions: {stdio: ['ignore', 'pipe', 'pipe']},468 message: ['stdio[0]', '\'ignore\''],469 to: 'stdin',470});471test('Cannot set "stderr" option to "ignore" to use .pipe(2)', testPipeError, {470}));471test('Cannot set "stderr" option to "ignore" to use .pipe(2)', () => testPipeError({472 sourceOptions: {stderr: 'ignore'},473 from: 'fd2',474 message: ['stderr', '\'ignore\''],475});476test('Cannot set "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {475}));476test('Cannot set "stderr" option to "ignore" to use .duplex(2)', () => testNodeStream({477 sourceOptions: {stderr: 'ignore'},478 from: 'fd2',479 message: ['stderr', '\'ignore\''],480});481test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {480}));481test('Cannot set "stderr" option to "ignore" to use .iterable(2)', () => testIterable({482 sourceOptions: {stderr: 'ignore'},483 from: 'fd2',484 message: ['stderr', '\'ignore\''],485});486test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {485}));486test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', () => testPipeError({487 sourceOptions: {stderr: 'ignore'},488 from: 'stderr',489 message: ['stderr', '\'ignore\''],490});491test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {490}));491test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', () => testNodeStream({492 sourceOptions: {stderr: 'ignore'},493 from: 'stderr',494 message: ['stderr', '\'ignore\''],495});496test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {495}));496test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', () => testIterable({497 sourceOptions: {stderr: 'ignore'},498 from: 'stderr',499 message: ['stderr', '\'ignore\''],500});501test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', testPipeError, {500}));501test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', () => testPipeError({502 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},503 from: 'fd2',504 message: ['stderr', '\'ignore\''],505});506test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {505}));506test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(2)', () => testNodeStream({507 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},508 from: 'fd2',509 message: ['stderr', '\'ignore\''],510});511test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', testIterable, {510}));511test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', () => testIterable({512 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},513 from: 'fd2',514 message: ['stderr', '\'ignore\''],515});516test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {515}));516test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', () => testPipeError({517 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},518 from: 'stderr',519 message: ['stderr', '\'ignore\''],520});521test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {520}));521test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stderr")', () => testNodeStream({522 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},523 from: 'stderr',524 message: ['stderr', '\'ignore\''],525});526test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {525}));526test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', () => testIterable({527 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},528 from: 'stderr',529 message: ['stderr', '\'ignore\''],530});531test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', testPipeError, {530}));531test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', () => testPipeError({532 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},533 from: 'fd2',534 message: ['stdio[2]', '\'ignore\''],535});536test('Cannot set "stdio[2]" option to "ignore" to use .duplex(2)', testNodeStream, {535}));536test('Cannot set "stdio[2]" option to "ignore" to use .duplex(2)', () => testNodeStream({537 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},538 from: 'fd2',539 message: ['stdio[2]', '\'ignore\''],540});541test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', testIterable, {540}));541test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', () => testIterable({542 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},543 from: 'fd2',544 message: ['stdio[2]', '\'ignore\''],545});546test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', testPipeError, {545}));546test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', () => testPipeError({547 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},548 from: 'stderr',549 message: ['stdio[2]', '\'ignore\''],550});551test('Cannot set "stdio[2]" option to "ignore" to use .duplex("stderr")', testNodeStream, {550}));551test('Cannot set "stdio[2]" option to "ignore" to use .duplex("stderr")', () => testNodeStream({552 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},553 from: 'stderr',554 message: ['stdio[2]', '\'ignore\''],555});556test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', testIterable, {555}));556test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', () => testIterable({557 sourceOptions: {stdio: ['pipe', 'pipe', 'ignore']},558 from: 'stderr',559 message: ['stdio[2]', '\'ignore\''],560});561test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', testPipeError, {560}));561test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', () => testPipeError({562 sourceOptions: getStdio(3, 'ignore'),563 from: 'fd3',564 message: ['stdio[3]', '\'ignore\''],565});566test('Cannot set "stdio[3]" option to "ignore" to use .duplex(3)', testNodeStream, {565}));566test('Cannot set "stdio[3]" option to "ignore" to use .duplex(3)', () => testNodeStream({567 sourceOptions: getStdio(3, 'ignore'),568 from: 'fd3',569 message: ['stdio[3]', '\'ignore\''],570});571test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', testIterable, {570}));571test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', () => testIterable({572 sourceOptions: getStdio(3, 'ignore'),573 from: 'fd3',574 message: ['stdio[3]', '\'ignore\''],575});576test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', testPipeError, {575}));576test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', () => testPipeError({577 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},578 from: 'all',579 message: ['stdout', '\'ignore\''],580});581test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("all")', testNodeStream, {580}));581test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("all")', () => testNodeStream({582 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},583 from: 'all',584 message: ['stdout', '\'ignore\''],585});586test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', testIterable, {585}));586test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', () => testIterable({587 sourceOptions: {stdout: 'ignore', stderr: 'ignore', all: true},588 from: 'all',589 message: ['stdout', '\'ignore\''],590});591test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', testPipeError, {590}));591test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', () => testPipeError({592 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},593 from: 'all',594 message: ['stdio[1]', '\'ignore\''],595});596test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .duplex("all")', testNodeStream, {595}));596test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .duplex("all")', () => testNodeStream({597 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},598 from: 'all',599 message: ['stdio[1]', '\'ignore\''],600});601test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', testIterable, {600}));601test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', () => testIterable({602 sourceOptions: {stdio: ['pipe', 'ignore', 'ignore'], all: true},603 from: 'all',604 message: ['stdio[1]', '\'ignore\''],605});606test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {605}));606test('Cannot set "stdout" option to "inherit" to use .pipe()', () => testPipeError({607 sourceOptions: {stdout: 'inherit'},608 message: ['stdout', '\'inherit\''],609});610test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {609}));610test('Cannot set "stdout" option to "inherit" to use .duplex()', () => testNodeStream({611 sourceOptions: {stdout: 'inherit'},612 message: ['stdout', '\'inherit\''],613});614test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {613}));614test('Cannot set "stdout" option to "inherit" to use .iterable()', () => testIterable({615 sourceOptions: {stdout: 'inherit'},616 message: ['stdout', '\'inherit\''],617});618test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {617}));618test('Cannot set "stdin" option to "inherit" to use .pipe()', () => testPipeError({619 destinationOptions: {stdin: 'inherit'},620 message: ['stdin', '\'inherit\''],621});622test('Cannot set "stdin" option to "inherit" to use .duplex()', testNodeStream, {621}));622test('Cannot set "stdin" option to "inherit" to use .duplex()', () => testNodeStream({623 sourceOptions: {stdin: 'inherit'},624 message: ['stdin', '\'inherit\''],625 writable: true,626});627test('Cannot set "stdout" option to file descriptors to use .pipe()', testPipeError, {626}));627test('Cannot set "stdout" option to file descriptors to use .pipe()', () => testPipeError({628 sourceOptions: {stdout: 1},629 message: ['stdout', '1'],630});631test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {630}));631test('Cannot set "stdout" option to file descriptors to use .duplex()', () => testNodeStream({632 sourceOptions: {stdout: 1},633 message: ['stdout', '1'],634});635test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {634}));635test('Cannot set "stdout" option to file descriptors to use .iterable()', () => testIterable({636 sourceOptions: {stdout: 1},637 message: ['stdout', '1'],638});639test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {638}));639test('Cannot set "stdin" option to file descriptors to use .pipe()', () => testPipeError({640 destinationOptions: {stdin: 0},641 message: ['stdin', '0'],642});643test('Cannot set "stdin" option to file descriptors to use .duplex()', testNodeStream, {642}));643test('Cannot set "stdin" option to file descriptors to use .duplex()', () => testNodeStream({644 sourceOptions: {stdin: 0},645 message: ['stdin', '0'],646 writable: true,647});648test('Cannot set "stdout" option to Node.js streams to use .pipe()', testPipeError, {647}));648test('Cannot set "stdout" option to Node.js streams to use .pipe()', () => testPipeError({649 sourceOptions: {stdout: process.stdout},650 message: ['stdout', 'Stream'],651});652test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {651}));652test('Cannot set "stdout" option to Node.js streams to use .duplex()', () => testNodeStream({653 sourceOptions: {stdout: process.stdout},654 message: ['stdout', 'Stream'],655});656test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {655}));656test('Cannot set "stdout" option to Node.js streams to use .iterable()', () => testIterable({657 sourceOptions: {stdout: process.stdout},658 message: ['stdout', 'Stream'],659});660test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {659}));660test('Cannot set "stdin" option to Node.js streams to use .pipe()', () => testPipeError({661 destinationOptions: {stdin: process.stdin},662 message: ['stdin', 'Stream'],663});664test('Cannot set "stdin" option to Node.js streams to use .duplex()', testNodeStream, {663}));664test('Cannot set "stdin" option to Node.js streams to use .duplex()', () => testNodeStream({665 sourceOptions: {stdin: process.stdin},666 message: ['stdin', 'Stream'],667 writable: true,668});669test('Cannot set "stdio[3]" option to Node.js Writable streams to use .pipe()', testPipeError, {668}));669test('Cannot set "stdio[3]" option to Node.js Writable streams to use .pipe()', () => testPipeError({670 sourceOptions: getStdio(3, process.stdout),671 message: ['stdio[3]', 'Stream'],672 from: 'fd3',673});674test('Cannot set "stdio[3]" option to Node.js Writable streams to use .duplex()', testNodeStream, {673}));674test('Cannot set "stdio[3]" option to Node.js Writable streams to use .duplex()', () => testNodeStream({675 sourceOptions: getStdio(3, process.stdout),676 message: ['stdio[3]', 'Stream'],677 from: 'fd3',678});679test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', testIterable, {678}));679test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', () => testIterable({680 sourceOptions: getStdio(3, process.stdout),681 message: ['stdio[3]', 'Stream'],682 from: 'fd3',683});684test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', testPipeError, {683}));684test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', () => testPipeError({685 destinationOptions: getStdio(3, process.stdin),686 message: ['stdio[3]', 'Stream'],687 to: 'fd3',688});689test('Cannot set "stdio[3]" option to Node.js Readable streams to use .duplex()', testNodeStream, {688}));689test('Cannot set "stdio[3]" option to Node.js Readable streams to use .duplex()', () => testNodeStream({690 sourceOptions: getStdio(3, process.stdin),691 message: ['stdio[3]', 'Stream'],692 to: 'fd3',693});693}));694695test('Sets the right error message when the "all" option is incompatible - execa.$', async t => {696 await assertPipeError(697 t,698 execa('empty.js')699 .pipe({all: false})`stdin.js`700 .pipe(execa('empty.js'), {from: 'all'}),701 '"all" option must be true',695test('Sets the right error message when the "all" option is incompatible - execa.$', async () => {696 await assertPipeError(execa('empty.js')697 .pipe({all: false})`stdin.js`698 .pipe(execa('empty.js'), {from: 'all'}),699 '"all" option must be true',700 );701});702705test('Sets the right error message when the "all" option is incompatible - execa.execa', async t => {706 await assertPipeError(707 t,708 execa('empty.js')709 .pipe(execa('stdin.js', {all: false}))710 .pipe(execa('empty.js'), {from: 'all'}),711 '"all" option must be true',703test('Sets the right error message when the "all" option is incompatible - execa.execa', async () => {704 await assertPipeError(execa('empty.js')705 .pipe(execa('stdin.js', {all: false}))706 .pipe(execa('empty.js'), {from: 'all'}),707 '"all" option must be true',708 );709});710715test('Sets the right error message when the "all" option is incompatible - early error', async t => {716 await assertPipeError(717 t,718 getEarlyErrorSubprocess()719 .pipe(execa('stdin.js', {all: false}))720 .pipe(execa('empty.js'), {from: 'all'}),721 '"all" option must be true',711test('Sets the right error message when the "all" option is incompatible - early error', async () => {712 await assertPipeError(getEarlyErrorSubprocess()713 .pipe(execa('stdin.js', {all: false}))714 .pipe(execa('empty.js'), {from: 'all'}),715 '"all" option must be true',716 );717});
modified:test/arguments/local.js+28 added-25 removed
1import assert from 'node:assert/strict';2import {existsSync} from 'node:fs';3import path from 'node:path';4import process from 'node:process';5import {pathToFileURL} from 'node:url';5import test from 'ava';6import test from 'node:test';7import {assertRejects} from '../helpers/assert.js';8import {execa, $} from '../../index.js';9import {setFixtureDirectory, PATH_KEY} from '../helpers/fixtures-directory.js';1011setFixtureDirectory();12process.env.FOO = 'foo';1314const isWindows = process.platform === 'win32';15const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;14const AVA_BINARY_NAMES = isWindows ? ['ava.cmd', 'ava.exe', 'ava.bat', 'ava.ps1', 'ava'] : ['ava'];16// `c8` is used instead of a globally installed command since it is a devDependency, so `preferLocal` is the only way to find it17const C8_BINARY_NAMES = isWindows ? ['c8.cmd', 'c8.exe', 'c8.bat', 'c8.ps1', 'c8'] : ['c8'];1819const getPathWithoutCommand = commandNames => {20 const newPath = process.env[PATH_KEY]21 .split(path.delimiter)
1 unmodified line
23 .join(path.delimiter);24 return {[PATH_KEY]: newPath};25};2624const pathWithoutAva = getPathWithoutCommand(AVA_BINARY_NAMES);27const pathWithoutC8 = getPathWithoutCommand(C8_BINARY_NAMES);2826test('preferLocal: true', async t => {27 await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: pathWithoutAva}));29test('preferLocal: true', async () => {30 await assert.doesNotReject(execa('c8', ['--version'], {preferLocal: true, env: pathWithoutC8}));31});3230test('preferLocal: false', async t => {31 await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: pathWithoutAva}), {message: ENOENT_REGEXP});33test('preferLocal: false', async () => {34 await assertRejects(execa('c8', ['--version'], {preferLocal: false, env: pathWithoutC8}), {message: ENOENT_REGEXP});35});3634test('preferLocal: undefined', async t => {35 await t.throwsAsync(execa('ava', ['--version'], {env: pathWithoutAva}), {message: ENOENT_REGEXP});37test('preferLocal: undefined', async () => {38 await assertRejects(execa('c8', ['--version'], {env: pathWithoutC8}), {message: ENOENT_REGEXP});39});4038test('preferLocal: undefined with $', async t => {39 await t.notThrowsAsync($('ava', ['--version'], {env: pathWithoutAva}));41test('preferLocal: undefined with $', async () => {42 await assert.doesNotReject($('c8', ['--version'], {env: pathWithoutC8}));43});4442test('preferLocal: undefined with $.sync', t => {43 t.notThrows(() => $.sync('ava', ['--version'], {env: pathWithoutAva}));45test('preferLocal: undefined with $.sync', () => {46 assert.doesNotThrow(() => $.sync('c8', ['--version'], {env: pathWithoutC8}));47});4846test('preferLocal: undefined with execa.pipe`...`', async t => {47 await t.throwsAsync(() => execa('node', ['--version']).pipe({env: pathWithoutAva})`ava --version`);49test('preferLocal: undefined with execa.pipe`...`', async () => {50 await assertRejects(() => execa('node', ['--version']).pipe({env: pathWithoutC8})`c8 --version`);51});5250test('preferLocal: undefined with $.pipe`...`', async t => {51 await t.notThrows(() => $('node', ['--version']).pipe({env: pathWithoutAva})`ava --version`);53test('preferLocal: undefined with $.pipe`...`', async () => {54 await assert.doesNotThrow(() => $('node', ['--version']).pipe({env: pathWithoutC8})`c8 --version`);55});5654test('preferLocal: undefined with execa.pipe()', async t => {55 await t.throwsAsync(() => execa('node', ['--version']).pipe('ava', ['--version'], {env: pathWithoutAva}));57test('preferLocal: undefined with execa.pipe()', async () => {58 await assertRejects(() => execa('node', ['--version']).pipe('c8', ['--version'], {env: pathWithoutC8}));59});6058test('preferLocal: undefined with $.pipe()', async t => {59 await t.notThrows(() => $('node', ['--version']).pipe('ava', ['--version'], {env: pathWithoutAva}));61test('preferLocal: undefined with $.pipe()', async () => {62 await assert.doesNotThrow(() => $('node', ['--version']).pipe('c8', ['--version'], {env: pathWithoutC8}));63});6462test('localDir option', async t => {65test('localDir option', async () => {66 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';67 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: '/test'});68 const envPaths = stdout.split(path.delimiter);66 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));69 assert.ok(envPaths.some(envPath => envPath.endsWith('.bin')));70});7169test('localDir option can be a URL', async t => {72test('localDir option can be a URL', async () => {73 const command = isWindows ? 'echo %PATH%' : 'echo $PATH';74 const {stdout} = await execa(command, {shell: true, preferLocal: true, localDir: pathToFileURL('/test')});75 const envPaths = stdout.split(path.delimiter);73 t.true(envPaths.some(envPath => envPath.endsWith('.bin')));76 assert.ok(envPaths.some(envPath => envPath.endsWith('.bin')));77});
modified:test/arguments/prototype-pollution.js+113 added-49 removed
1import assert from 'node:assert/strict';2import path from 'node:path';3import process from 'node:process';3import test from 'ava';4import {pathExists} from 'path-exists';4import test from 'node:test';5import {text} from 'node:stream/consumers';6import tempfile from 'tempfile';7import {pathExists} from 'path-exists';8import {9 execa,10 execaSync,11 execaNode,12 $,13} from '../../index.js';14import {assertThrows} from '../helpers/assert.js';15import {setFixtureDirectory, PATH_KEY, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';16import {foobarString} from '../helpers/input.js';1718setFixtureDirectory();
1 unmodified line
2021/*22A polluted `Object.prototype` must not inject option values. Otherwise, any prototype pollution elsewhere in the process would let an attacker redirect the command, its input or its output.23Options are therefore always kept on null-prototype objects.21Those tests are serial since they temporarily modify `Object.prototype`.24Those tests must run one at a time since they temporarily modify `Object.prototype`.25*/26const pollutePrototype = (t, properties) => {24 t.teardown(() => {27 t.after(() => {28 for (const property of Object.keys(properties)) {29 delete Object.prototype[property];30 }31 });
9 unmodified lines
41const testPollutedPreferLocal = async (t, execaMethod) => {42 pollutePrototype(t, {preferLocal: true, localDir: POLLUTED_LOCAL_DIRECTORY});4344 const {stdout} = await execaMethod('node', printPath);42 t.false(stdout.includes(pollutedBinaryDirectory));45 assert.ok(!stdout.includes(pollutedBinaryDirectory));46};4745test.serial('Polluted "preferLocal" and "localDir" are ignored', testPollutedPreferLocal, execa);46test.serial('Polluted "preferLocal" and "localDir" are ignored, sync', testPollutedPreferLocal, execaSync);48test('Polluted "preferLocal" and "localDir" are ignored', t => testPollutedPreferLocal(t, execa));49test('Polluted "preferLocal" and "localDir" are ignored, sync', t => testPollutedPreferLocal(t, execaSync));5051// `$` sets `preferLocal: true` itself, so only `localDir` can be injected49test.serial('Polluted "localDir" is ignored, $', async t => {52test('Polluted "localDir" is ignored, $', async t => {53 pollutePrototype(t, {localDir: POLLUTED_LOCAL_DIRECTORY});5455 const {stdout} = await $('node', printPath);53 t.false(stdout.includes(pollutedBinaryDirectory));56 assert.ok(!stdout.includes(pollutedBinaryDirectory));57});5859// The `stdout` option can redirect the output to an arbitrary file60const testPollutedStdout = async (t, execaMethod) => {61 const filePath = tempfile();62 pollutePrototype(t, {stdout: {file: filePath}});6364 const {stdout} = await execaMethod('noop.js', [foobarString]);62 t.is(stdout, foobarString);63 t.false(await pathExists(filePath));65 assert.equal(stdout, foobarString);66 assert.ok(!await pathExists(filePath));67};6866test.serial('Polluted "stdout" is ignored', testPollutedStdout, execa);67test.serial('Polluted "stdout" is ignored, sync', testPollutedStdout, execaSync);69test('Polluted "stdout" is ignored', t => testPollutedStdout(t, execa));70test('Polluted "stdout" is ignored, sync', t => testPollutedStdout(t, execaSync));7172// The `stdin` option can feed the contents of an arbitrary file to the subprocess70test.serial('Polluted "stdin" is ignored', async t => {73test('Polluted "stdin" is ignored', async t => {74 pollutePrototype(t, {stdin: {file: 'noop.js'}});7576 const subprocess = execa('stdin.js');77 subprocess.stdin.end(foobarString);78 const {stdout} = await subprocess;76 t.is(stdout, foobarString);79 assert.equal(stdout, foobarString);80});8182// The `verbose` option can be a function, which Execa calls with each log line83const testPollutedVerbose = async (t, execaMethod) => {
4 unmodified lines
88 },89 });9091 await execaMethod('noop.js', [foobarString]);89 t.false(isVerboseCalled);92 assert.equal(isVerboseCalled, false);93};9492test.serial('Polluted "verbose" is ignored', testPollutedVerbose, execa);93test.serial('Polluted "verbose" is ignored, sync', testPollutedVerbose, execaSync);94test.serial('Polluted "verbose" is ignored, $', testPollutedVerbose, $);95test('Polluted "verbose" is ignored', t => testPollutedVerbose(t, execa));96test('Polluted "verbose" is ignored, sync', t => testPollutedVerbose(t, execaSync));97test('Polluted "verbose" is ignored, $', t => testPollutedVerbose(t, $));98// `execaNode()` resolves the file from the current directory, not from `PATH`96test.serial('Polluted "verbose" is ignored, execaNode()', testPollutedVerbose, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments));97test.serial('Polluted "verbose" is ignored, .pipe()', testPollutedVerbose, (file, commandArguments) => execa('empty.js').pipe(file, commandArguments));99test('Polluted "verbose" is ignored, execaNode()', t => testPollutedVerbose(t, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments)));100test('Polluted "verbose" is ignored, .pipe()', t => testPollutedVerbose(t, (file, commandArguments) => execa('empty.js').pipe(file, commandArguments)));10199test.serial('Polluted "extendEnv" is ignored', async t => {102test('Polluted "extendEnv" is ignored', async t => {103 pollutePrototype(t, {extendEnv: false});104105 const {stdout} = await execa('environment.js', [], {env: {BAR: 'bar', [PATH_KEY]: process.env[PATH_KEY]}});103 t.deepEqual(stdout.split('\n'), ['foo', 'bar']);106 assert.deepEqual(stdout.split('\n'), ['foo', 'bar']);107});108109// `piped` is set by Execa itself, only when using `.pipe()`. It decides which icon the `verbose` option prints.110const testPollutedPiped = async (t, execaMethod) => {
4 unmodified lines
115 verbose(verboseLine, verboseObject) {116 verboseObjects.push(verboseObject);117 },118 });116 t.true(verboseObjects.length > 0);117 t.true(verboseObjects.every(({piped}) => piped === false));119 assert.ok(verboseObjects.length > 0);120 assert.ok(verboseObjects.every(({piped}) => piped === false));121};122120test.serial('Polluted "piped" is ignored', testPollutedPiped, execa);121test.serial('Polluted "piped" is ignored, sync', testPollutedPiped, execaSync);123test('Polluted "piped" is ignored', t => testPollutedPiped(t, execa));124test('Polluted "piped" is ignored, sync', t => testPollutedPiped(t, execaSync));125126/*127`mapArguments()` returns `{options, isSync}`, which are method-specific. Neither is a user-facing option.128A polluted `options` would replace every option at once, and a polluted `isSync` would switch the execution mode.
1 unmodified line
130const testPollutedMappedOptions = async (t, execaMethod) => {131 pollutePrototype(t, {options: {cwd: path.resolve('/')}});132133 const {cwd} = await execaMethod('noop.js', [foobarString]);131 t.is(cwd, process.cwd());134 assert.equal(cwd, process.cwd());135};136134test.serial('Polluted "options" is ignored', testPollutedMappedOptions, execa);135test.serial('Polluted "options" is ignored, sync', testPollutedMappedOptions, execaSync);137test('Polluted "options" is ignored', t => testPollutedMappedOptions(t, execa));138test('Polluted "options" is ignored, sync', t => testPollutedMappedOptions(t, execaSync));139140const testPollutedIsSync = async (t, execaMethod) => {141 pollutePrototype(t, {isSync: true});142143 const subprocess = execaMethod('noop.js', [foobarString]);141 t.is(typeof subprocess.kill, 'function');144 assert.equal(typeof subprocess.kill, 'function');145 const {stdout} = await subprocess;143 t.is(stdout, foobarString);146 assert.equal(stdout, foobarString);147};148146test.serial('Polluted "isSync" is ignored', testPollutedIsSync, execa);147test.serial('Polluted "isSync" is ignored, $', testPollutedIsSync, $);148test.serial('Polluted "isSync" is ignored, execaNode()', testPollutedIsSync, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments));149test('Polluted "isSync" is ignored', t => testPollutedIsSync(t, execa));150test('Polluted "isSync" is ignored, $', t => testPollutedIsSync(t, $));151test('Polluted "isSync" is ignored, execaNode()', t => testPollutedIsSync(t, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments)));152150test.serial('Polluted "cancelSignal" is ignored', async t => {153test('Polluted "cancelSignal" is ignored', async t => {154 pollutePrototype(t, {cancelSignal: {}});155156 const {stdout} = await execa('noop.js', [foobarString]);154 t.is(stdout, foobarString);157 assert.equal(stdout, foobarString);158});159160// Template expressions detect subprocess results with their `stdout`/`isMaxBuffer` properties. Using the `in` operator would let a polluted `Object.prototype.stdout` turn any plain object into an interpolated command argument.158test.serial('Polluted "stdout" is not interpolated in template expressions', t => {161test('Polluted "stdout" is not interpolated in template expressions', t => {162 pollutePrototype(t, {stdout: foobarString});163161 t.throws(() => $`noop.js ${{}}`, {message: /Unexpected "object" in template expression/});164 assertThrows(() => $`noop.js ${{}}`, {message: /Unexpected "object" in template expression/});165});166167// A result with `stdout: 'ignore'` has no own `stdout` property, so it must not read the polluted one165test.serial('Polluted "stdout" is not read from template expression results', t => {168test('Polluted "stdout" is not read from template expression results', t => {169 pollutePrototype(t, {stdout: foobarString});170168 t.throws(() => $`noop.js ${$({stdio: 'ignore'}).sync`noop.js`}`, {message: /Missing result.stdout/});171 assertThrows(() => $`noop.js ${$({stdio: 'ignore'}).sync`noop.js`}`, {message: /Missing result.stdout/});172});173174/*175Unlike the options, `child_process` intentionally passes the inherited properties of the `env` option to the subprocess.
2 unmodified lines
178const testPollutedEnvironment = async (t, execaMethod, options) => {179 pollutePrototype(t, {POLLUTED_VARIABLE: 'polluted'});180181 const {stdout} = await execaMethod(process.execPath, ['-p', 'process.env.POLLUTED_VARIABLE'], options);179 t.is(stdout, 'undefined');182 assert.equal(stdout, 'undefined');183};184182test.serial('Polluted environment variables are ignored', testPollutedEnvironment, execa, {});183test.serial('Polluted environment variables are ignored, sync', testPollutedEnvironment, execaSync, {});184test.serial('Polluted environment variables are ignored, extendEnv false', testPollutedEnvironment, execa, {extendEnv: false});185test.serial('Polluted environment variables are ignored, preferLocal', testPollutedEnvironment, execa, {preferLocal: true});185test('Polluted environment variables are ignored', t => testPollutedEnvironment(t, execa, {}));186test('Polluted environment variables are ignored, sync', t => testPollutedEnvironment(t, execaSync, {}));187test('Polluted environment variables are ignored, extendEnv false', t => testPollutedEnvironment(t, execa, {extendEnv: false}));188test('Polluted environment variables are ignored, preferLocal', t => testPollutedEnvironment(t, execa, {preferLocal: true}));189190const testPollutedPath = async (t, execaMethod) => {191 pollutePrototype(t, {[PATH_KEY]: POLLUTED_LOCAL_DIRECTORY});192193 const {stdout} = await execaMethod(process.execPath, printPath, {extendEnv: false});191 t.is(stdout, 'undefined');194 assert.equal(stdout, 'undefined');195};196194test.serial('Polluted PATH is ignored', testPollutedPath, execa);195test.serial('Polluted PATH is ignored, sync', testPollutedPath, execaSync);197test('Polluted PATH is ignored', t => testPollutedPath(t, execa));198test('Polluted PATH is ignored, sync', t => testPollutedPath(t, execaSync));199200// The options of `subprocess.pipe()`, `subprocess.readable()` and `subprocess.iterable()` must not be injected either, e.g. `from` can read another file descriptor instead201const stdoutString = 'public';202203const testPollutedFrom = async (t, readOutput) => {204 pollutePrototype(t, {from: 'stderr'});205206 const subprocess = execa('noop-both.js', [stdoutString, foobarString]);207 assert.equal(await readOutput(subprocess), stdoutString);208 await subprocess;209};210211test('Polluted "from" is ignored, .pipe()', t => testPollutedFrom(t, async subprocess => {212 const {stdout} = await subprocess.pipe(execa('stdin.js'));213 return stdout;214}));215test('Polluted "from" is ignored, .pipe``', t => testPollutedFrom(t, async subprocess => {216 const {stdout} = await subprocess.pipe`stdin.js`;217 return stdout;218}));219test('Polluted "from" is ignored, .readable()', t => testPollutedFrom(t, async subprocess => {220 const output = await text(subprocess.readable({}));221 return output.trim();222}));223test('Polluted "from" is ignored, .iterable()', t => testPollutedFrom(t, async subprocess => {224 const lines = await Array.fromAsync(subprocess.iterable({}));225 return lines.join('');226}));227228// The options of the IPC methods must not be injected either, e.g. `filter` can drop every message229test('Polluted "filter" is ignored, .getOneMessage()', async t => {230 pollutePrototype(t, {filter: () => false});231232 const subprocess = execa('ipc-send.js', {ipc: true});233 assert.equal(await subprocess.getOneMessage(), foobarString);234 await subprocess;235});236237// The result of a successful subprocess has no `error` property, which must not be read from the prototype238test('Polluted "error" is ignored', async t => {239 pollutePrototype(t, {error: foobarString});240241 const {failed} = await execa('empty.js');242 assert.equal(failed, false);243});244245// An early error has a `failed` property, which must not be read from the prototype of `child_process.spawnSync()`'s result246test('Polluted "failed" is ignored, sync', t => {247 pollutePrototype(t, {failed: true});248249 const {stdout} = execaSync('noop.js', [foobarString]);250 assert.equal(stdout, foobarString);251});252253// A subprocess which failed to spawn has no output, which must not read its `error` from the prototype254test('Polluted "error" is ignored, sync early error', t => {255 pollutePrototype(t, {error: foobarString});256257 const {code} = execaSync('non-existent-command', {reject: false});258 assert.equal(code, 'ENOENT');259});
modified:test/arguments/shell.js+8 added-7 removed
1import assert from 'node:assert/strict';2import process from 'node:process';3import {pathToFileURL} from 'node:url';3import test from 'ava';4import test from 'node:test';5import {whichCommand} from 'which-command';6import {execa} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {identity} from '../helpers/stdio.js';
2 unmodified lines
11process.env.FOO = 'foo';1213const isWindows = process.platform === 'win32';1414test('can use `options.shell: true`', async t => {15test('can use `options.shell: true`', async () => {16 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell: true});16 t.is(stdout, 'foo');17 assert.equal(stdout, 'foo');18});1919const testShellPath = async (t, mapPath) => {20const testShellPath = async mapPath => {21 const shellPath = isWindows ? 'cmd.exe' : 'bash';22 const shell = mapPath(await whichCommand(shellPath));23 const {stdout} = await execa('node test/fixtures/noop.js foo', {shell});23 t.is(stdout, 'foo');24 assert.equal(stdout, 'foo');25};2626test('can use `options.shell: string`', testShellPath, identity);27test('can use `options.shell: file URL`', testShellPath, pathToFileURL);27test('can use `options.shell: string`', () => testShellPath(identity));28test('can use `options.shell: file URL`', () => testShellPath(pathToFileURL));
modified:test/arguments/specific.js+29 added-29 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa, execaSync} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {foobarString} from '../helpers/input.js';67setFixtureDirectory();88// eslint-disable-next-line max-params9const testPriorityOrder = async (t, buffer, bufferStdout, bufferStderr, execaMethod) => {9const testPriorityOrder = async (buffer, bufferStdout, bufferStderr, execaMethod) => {10 const {stdout, stderr} = await execaMethod('noop-both.js', {buffer});11 t.is(stdout, bufferStdout ? foobarString : undefined);12 t.is(stderr, bufferStderr ? foobarString : undefined);11 assert.equal(stdout, bufferStdout ? foobarString : undefined);12 assert.equal(stderr, bufferStderr ? foobarString : undefined);13};1415test('buffer: {stdout, fd1}', testPriorityOrder, {stdout: true, fd1: false}, true, true, execa);16test('buffer: {stdout, all}', testPriorityOrder, {stdout: true, all: false}, true, false, execa);17test('buffer: {fd1, all}', testPriorityOrder, {fd1: true, all: false}, true, false, execa);18test('buffer: {stderr, fd2}', testPriorityOrder, {stderr: true, fd2: false}, true, true, execa);19test('buffer: {stderr, all}', testPriorityOrder, {stderr: true, all: false}, false, true, execa);20test('buffer: {fd2, all}', testPriorityOrder, {fd2: true, all: false}, false, true, execa);21test('buffer: {fd1, stdout}', testPriorityOrder, {fd1: false, stdout: true}, true, true, execa);22test('buffer: {all, stdout}', testPriorityOrder, {all: false, stdout: true}, true, false, execa);23test('buffer: {all, fd1}', testPriorityOrder, {all: false, fd1: true}, true, false, execa);24test('buffer: {fd2, stderr}', testPriorityOrder, {fd2: false, stderr: true}, true, true, execa);25test('buffer: {all, stderr}', testPriorityOrder, {all: false, stderr: true}, false, true, execa);26test('buffer: {all, fd2}', testPriorityOrder, {all: false, fd2: true}, false, true, execa);27test('buffer: {stdout, fd1}, sync', testPriorityOrder, {stdout: true, fd1: false}, true, true, execaSync);28test('buffer: {stdout, all}, sync', testPriorityOrder, {stdout: true, all: false}, true, false, execaSync);29test('buffer: {fd1, all}, sync', testPriorityOrder, {fd1: true, all: false}, true, false, execaSync);30test('buffer: {stderr, fd2}, sync', testPriorityOrder, {stderr: true, fd2: false}, true, true, execaSync);31test('buffer: {stderr, all}, sync', testPriorityOrder, {stderr: true, all: false}, false, true, execaSync);32test('buffer: {fd2, all}, sync', testPriorityOrder, {fd2: true, all: false}, false, true, execaSync);33test('buffer: {fd1, stdout}, sync', testPriorityOrder, {fd1: false, stdout: true}, true, true, execaSync);34test('buffer: {all, stdout}, sync', testPriorityOrder, {all: false, stdout: true}, true, false, execaSync);35test('buffer: {all, fd1}, sync', testPriorityOrder, {all: false, fd1: true}, true, false, execaSync);36test('buffer: {fd2, stderr}, sync', testPriorityOrder, {fd2: false, stderr: true}, true, true, execaSync);37test('buffer: {all, stderr}, sync', testPriorityOrder, {all: false, stderr: true}, false, true, execaSync);38test('buffer: {all, fd2}, sync', testPriorityOrder, {all: false, fd2: true}, false, true, execaSync);15test('buffer: {stdout, fd1}', () => testPriorityOrder({stdout: true, fd1: false}, true, true, execa));16test('buffer: {stdout, all}', () => testPriorityOrder({stdout: true, all: false}, true, false, execa));17test('buffer: {fd1, all}', () => testPriorityOrder({fd1: true, all: false}, true, false, execa));18test('buffer: {stderr, fd2}', () => testPriorityOrder({stderr: true, fd2: false}, true, true, execa));19test('buffer: {stderr, all}', () => testPriorityOrder({stderr: true, all: false}, false, true, execa));20test('buffer: {fd2, all}', () => testPriorityOrder({fd2: true, all: false}, false, true, execa));21test('buffer: {fd1, stdout}', () => testPriorityOrder({fd1: false, stdout: true}, true, true, execa));22test('buffer: {all, stdout}', () => testPriorityOrder({all: false, stdout: true}, true, false, execa));23test('buffer: {all, fd1}', () => testPriorityOrder({all: false, fd1: true}, true, false, execa));24test('buffer: {fd2, stderr}', () => testPriorityOrder({fd2: false, stderr: true}, true, true, execa));25test('buffer: {all, stderr}', () => testPriorityOrder({all: false, stderr: true}, false, true, execa));26test('buffer: {all, fd2}', () => testPriorityOrder({all: false, fd2: true}, false, true, execa));27test('buffer: {stdout, fd1}, sync', () => testPriorityOrder({stdout: true, fd1: false}, true, true, execaSync));28test('buffer: {stdout, all}, sync', () => testPriorityOrder({stdout: true, all: false}, true, false, execaSync));29test('buffer: {fd1, all}, sync', () => testPriorityOrder({fd1: true, all: false}, true, false, execaSync));30test('buffer: {stderr, fd2}, sync', () => testPriorityOrder({stderr: true, fd2: false}, true, true, execaSync));31test('buffer: {stderr, all}, sync', () => testPriorityOrder({stderr: true, all: false}, false, true, execaSync));32test('buffer: {fd2, all}, sync', () => testPriorityOrder({fd2: true, all: false}, false, true, execaSync));33test('buffer: {fd1, stdout}, sync', () => testPriorityOrder({fd1: false, stdout: true}, true, true, execaSync));34test('buffer: {all, stdout}, sync', () => testPriorityOrder({all: false, stdout: true}, true, false, execaSync));35test('buffer: {all, fd1}, sync', () => testPriorityOrder({all: false, fd1: true}, true, false, execaSync));36test('buffer: {fd2, stderr}, sync', () => testPriorityOrder({fd2: false, stderr: true}, true, true, execaSync));37test('buffer: {all, stderr}, sync', () => testPriorityOrder({all: false, stderr: true}, false, true, execaSync));38test('buffer: {all, fd2}, sync', () => testPriorityOrder({all: false, fd2: true}, false, true, execaSync));
modified:test/convert/concurrent.js+114 added-114 removed
1import assert from 'node:assert/strict';2import {setTimeout} from 'node:timers/promises';2import test from 'ava';3import test from 'node:test';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';7import {fullReadableStdio} from '../helpers/stdio.js';
13 unmodified lines
21 stream.end(foobarString);22 await setTimeout(0);23};2424// eslint-disable-next-line max-params25const endSameWritable = async (t, stream, secondStream, subprocess, fdNumber) => {25const endSameWritable = async (stream, secondStream, subprocess, fdNumber) => {26 await endStream(stream);27 t.true(subprocess.stdio[fdNumber].writable);27 assert.ok(subprocess.stdio[fdNumber].writable);2829 await endStream(secondStream);30 t.false(subprocess.stdio[fdNumber].writable);30 assert.ok(!subprocess.stdio[fdNumber].writable);31};3233// eslint-disable-next-line max-params34const endDifferentWritable = async (t, stream, secondStream, subprocess, fdNumber = 0, secondFdNumber = 3) => {34const endDifferentWritable = async (stream, secondStream, subprocess, fdNumber = 0, secondFdNumber = 3) => {35 await endStream(stream);36 t.false(subprocess.stdio[fdNumber].writable);37 t.true(subprocess.stdio[secondFdNumber].writable);36 assert.ok(!subprocess.stdio[fdNumber].writable);37 assert.ok(subprocess.stdio[secondFdNumber].writable);3839 await endStream(secondStream);40 t.false(subprocess.stdio[secondFdNumber].writable);40 assert.ok(!subprocess.stdio[secondFdNumber].writable);41};4243const testReadableTwice = async (t, fdNumber, from) => {43const testReadableTwice = async (fdNumber, from) => {44 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString]);45 const stream = subprocess.readable({from});46 const secondStream = subprocess.readable({from});4748 await Promise.all([49 assertStreamOutput(t, stream),50 assertStreamOutput(t, secondStream),49 assertStreamOutput(stream),50 assertStreamOutput(secondStream),51 ]);52 await assertSubprocessOutput(t, subprocess, foobarString, fdNumber);52 await assertSubprocessOutput(subprocess, foobarString, fdNumber);53};5455test('Can call .readable() twice on same file descriptor', testReadableTwice, 1);56test('Can call .readable({from: "stderr"}) twice on same file descriptor', testReadableTwice, 2, 'stderr');55test('Can call .readable() twice on same file descriptor', () => testReadableTwice(1));56test('Can call .readable({from: "stderr"}) twice on same file descriptor', () => testReadableTwice(2, 'stderr'));5758const testWritableTwice = async (t, fdNumber, to, options) => {58const testWritableTwice = async (fdNumber, to, options) => {59 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], options);60 const stream = subprocess.writable({to});61 const secondStream = subprocess.writable({to});6263 await Promise.all([64 finishedStream(stream),65 finishedStream(secondStream),66 endSameWritable(t, stream, secondStream, subprocess, fdNumber),66 endSameWritable(stream, secondStream, subprocess, fdNumber),67 ]);68 await assertSubprocessOutput(t, subprocess, `${foobarString}${foobarString}`);68 await assertSubprocessOutput(subprocess, `${foobarString}${foobarString}`);69};7071test('Can call .writable() twice on same file descriptor', testWritableTwice, 0, undefined, {});72test('Can call .writable({to: "fd3"}) twice on same file descriptor', testWritableTwice, 3, 'fd3', fullReadableStdio());71test('Can call .writable() twice on same file descriptor', () => testWritableTwice(0, undefined, {}));72test('Can call .writable({to: "fd3"}) twice on same file descriptor', () => testWritableTwice(3, 'fd3', fullReadableStdio()));7374const testDuplexTwice = async (t, fdNumber, to, options) => {74const testDuplexTwice = async (fdNumber, to, options) => {75 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], options);76 const stream = subprocess.duplex({to});77 const secondStream = subprocess.duplex({to});7879 const expectedOutput = `${foobarString}${foobarString}`;80 await Promise.all([81 assertStreamOutput(t, stream, expectedOutput),82 assertStreamOutput(t, secondStream, expectedOutput),83 endSameWritable(t, stream, secondStream, subprocess, fdNumber),81 assertStreamOutput(stream, expectedOutput),82 assertStreamOutput(secondStream, expectedOutput),83 endSameWritable(stream, secondStream, subprocess, fdNumber),84 ]);85 await assertSubprocessOutput(t, subprocess, expectedOutput);85 await assertSubprocessOutput(subprocess, expectedOutput);86};8788test('Can call .duplex() twice on same file descriptor', testDuplexTwice, 0, undefined, {});89test('Can call .duplex({to: "fd3"}) twice on same file descriptor', testDuplexTwice, 3, 'fd3', fullReadableStdio());88test('Can call .duplex() twice on same file descriptor', () => testDuplexTwice(0, undefined, {}));89test('Can call .duplex({to: "fd3"}) twice on same file descriptor', () => testDuplexTwice(3, 'fd3', fullReadableStdio()));9091test('Can call .duplex() twice on same readable file descriptor but different writable one', async t => {91test('Can call .duplex() twice on same readable file descriptor but different writable one', async () => {92 const subprocess = execa('stdin-fd-both.js', ['3'], fullReadableStdio());93 const stream = subprocess.duplex();94 const secondStream = subprocess.duplex({to: 'fd3'});9596 const expectedOutput = `${foobarString}${foobarString}`;97 await Promise.all([98 assertStreamOutput(t, stream, expectedOutput),99 assertStreamOutput(t, secondStream, expectedOutput),100 endDifferentWritable(t, stream, secondStream, subprocess),98 assertStreamOutput(stream, expectedOutput),99 assertStreamOutput(secondStream, expectedOutput),100 endDifferentWritable(stream, secondStream, subprocess),101 ]);102 await assertSubprocessOutput(t, subprocess, expectedOutput);102 await assertSubprocessOutput(subprocess, expectedOutput);103});104105test('Can call .readable() twice on different file descriptors', async t => {105test('Can call .readable() twice on different file descriptors', async () => {106 const subprocess = execa('noop-both.js', [foobarString]);107 const stream = subprocess.readable();108 const secondStream = subprocess.readable({from: 'stderr'});109110 const expectedOutput = `${foobarString}\n`;111 await Promise.all([112 assertStreamOutput(t, stream, expectedOutput),113 assertStreamOutput(t, secondStream, expectedOutput),112 assertStreamOutput(stream, expectedOutput),113 assertStreamOutput(secondStream, expectedOutput),114 ]);115 await assertSubprocessOutput(t, subprocess);116 await assertSubprocessOutput(t, subprocess, foobarString, 2);115 await assertSubprocessOutput(subprocess);116 await assertSubprocessOutput(subprocess, foobarString, 2);117});118119test('Can call .writable() twice on different file descriptors', async t => {119test('Can call .writable() twice on different file descriptors', async () => {120 const subprocess = execa('stdin-fd-both.js', ['3'], fullReadableStdio());121 const stream = subprocess.writable();122 const secondStream = subprocess.writable({to: 'fd3'});123124 await Promise.all([125 finishedStream(stream),126 finishedStream(secondStream),127 endDifferentWritable(t, stream, secondStream, subprocess),127 endDifferentWritable(stream, secondStream, subprocess),128 ]);129 await assertSubprocessOutput(t, subprocess, `${foobarString}${foobarString}`);129 await assertSubprocessOutput(subprocess, `${foobarString}${foobarString}`);130});131132test('Can call .duplex() twice on different file descriptors', async t => {132test('Can call .duplex() twice on different file descriptors', async () => {133 const subprocess = execa('stdin-twice-both.js', ['3'], fullReadableStdio());134 const stream = subprocess.duplex();135 const secondStream = subprocess.duplex({from: 'stderr', to: 'fd3'});136137 await Promise.all([138 assertStreamOutput(t, stream),139 assertStreamOutput(t, secondStream),140 endDifferentWritable(t, stream, secondStream, subprocess),138 assertStreamOutput(stream),139 assertStreamOutput(secondStream),140 endDifferentWritable(stream, secondStream, subprocess),141 ]);142 await assertSubprocessOutput(t, subprocess);143 await assertSubprocessOutput(t, subprocess, foobarString, 2);142 await assertSubprocessOutput(subprocess);143 await assertSubprocessOutput(subprocess, foobarString, 2);144});145146test('Can call .readable() and .writable()', async t => {146test('Can call .readable() and .writable()', async () => {147 const subprocess = getReadWriteSubprocess();148 const stream = subprocess.writable();149 const secondStream = subprocess.readable();150 stream.end(foobarString);151152 await Promise.all([153 finishedStream(stream),154 assertStreamOutput(t, secondStream),154 assertStreamOutput(secondStream),155 ]);156 await assertSubprocessOutput(t, subprocess);156 await assertSubprocessOutput(subprocess);157});158159test('Can call .writable() and .duplex()', async t => {159test('Can call .writable() and .duplex()', async () => {160 const subprocess = execa('stdin-fd-both.js', ['3'], fullReadableStdio());161 const stream = subprocess.duplex();162 const secondStream = subprocess.writable({to: 'fd3'});163164 const expectedOutput = `${foobarString}${foobarString}`;165 await Promise.all([166 assertStreamOutput(t, stream, expectedOutput),166 assertStreamOutput(stream, expectedOutput),167 finishedStream(secondStream),168 endDifferentWritable(t, stream, secondStream, subprocess),168 endDifferentWritable(stream, secondStream, subprocess),169 ]);170 await assertSubprocessOutput(t, subprocess, expectedOutput);170 await assertSubprocessOutput(subprocess, expectedOutput);171});172173test('Can call .readable() and .duplex()', async t => {173test('Can call .readable() and .duplex()', async () => {174 const subprocess = execa('stdin-both.js');175 const stream = subprocess.duplex();176 const secondStream = subprocess.readable({from: 'stderr'});177 stream.end(foobarString);178179 await Promise.all([180 assertStreamOutput(t, stream),181 assertStreamOutput(t, secondStream),180 assertStreamOutput(stream),181 assertStreamOutput(secondStream),182 ]);183 await assertSubprocessOutput(t, subprocess);184 await assertSubprocessOutput(t, subprocess, foobarString, 2);183 await assertSubprocessOutput(subprocess);184 await assertSubprocessOutput(subprocess, foobarString, 2);185});186187test('Can error one of two .readable() on same file descriptor', async t => {187test('Can error one of two .readable() on same file descriptor', async () => {188 const subprocess = execa('noop-fd.js', ['1', foobarString]);189 const stream = subprocess.readable();190 const secondStream = subprocess.readable();191 const cause = new Error(foobarString);192 stream.destroy(cause);193194 await Promise.all([195 assertStreamReadError(t, stream, cause),196 assertStreamOutput(t, secondStream),195 assertStreamReadError(stream, cause),196 assertStreamOutput(secondStream),197 ]);198 await assertSubprocessOutput(t, subprocess);198 await assertSubprocessOutput(subprocess);199});200201test('Can error both .readable() on same file descriptor', async t => {201test('Can error both .readable() on same file descriptor', async () => {202 const subprocess = execa('noop-fd.js', ['1', foobarString]);203 const stream = subprocess.readable();204 const secondStream = subprocess.readable();205 const cause = new Error(foobarString);206 stream.destroy(cause);207 secondStream.destroy(cause);208209 const [error, secondError] = await Promise.all([210 assertStreamReadError(t, stream, {cause}),211 assertStreamReadError(t, secondStream, {cause}),210 assertStreamReadError(stream, {cause}),211 assertStreamReadError(secondStream, {cause}),212 ]);213 t.is(error, secondError);214 await assertSubprocessError(t, subprocess, error);213 assert.equal(error, secondError);214 await assertSubprocessError(subprocess, error);215});216217test('Can error one of two .readable() on different file descriptors', async t => {217test('Can error one of two .readable() on different file descriptors', async () => {218 const subprocess = execa('noop-both.js', [foobarString]);219 const stream = subprocess.readable();220 const secondStream = subprocess.readable({from: 'stderr'});221 const cause = new Error(foobarString);222 stream.destroy(cause);223224 const [error, secondError] = await Promise.all([225 assertStreamReadError(t, stream, {cause}),226 assertStreamReadError(t, secondStream, {cause}),225 assertStreamReadError(stream, {cause}),226 assertStreamReadError(secondStream, {cause}),227 ]);228 t.is(error, secondError);229 t.is(error.stderr, foobarString);230 await assertSubprocessError(t, subprocess, error);228 assert.equal(error, secondError);229 assert.equal(error.stderr, foobarString);230 await assertSubprocessError(subprocess, error);231});232233test('Can error both .readable() on different file descriptors', async t => {233test('Can error both .readable() on different file descriptors', async () => {234 const subprocess = execa('noop-both.js', [foobarString]);235 const stream = subprocess.readable();236 const secondStream = subprocess.readable({from: 'stderr'});237 const cause = new Error(foobarString);238 stream.destroy(cause);239 secondStream.destroy(cause);240241 const [error, secondError] = await Promise.all([242 assertStreamReadError(t, stream, {cause}),243 assertStreamReadError(t, secondStream, {cause}),242 assertStreamReadError(stream, {cause}),243 assertStreamReadError(secondStream, {cause}),244 ]);245 t.is(error, secondError);246 await assertSubprocessError(t, subprocess, error);245 assert.equal(error, secondError);246 await assertSubprocessError(subprocess, error);247});248249test('Can error one of two .writable() on same file descriptor', async t => {249test('Can error one of two .writable() on same file descriptor', async () => {250 const subprocess = execa('stdin.js');251 const stream = subprocess.writable();252 const secondStream = subprocess.writable();253 const cause = new Error(foobarString);254 stream.destroy(cause);255 secondStream.end(foobarString);256257 await Promise.all([258 assertStreamError(t, stream, cause),258 assertStreamError(stream, cause),259 finishedStream(secondStream),260 ]);261 await assertSubprocessOutput(t, subprocess);261 await assertSubprocessOutput(subprocess);262});263264test('Can error both .writable() on same file descriptor', async t => {264test('Can error both .writable() on same file descriptor', async () => {265 const subprocess = execa('stdin.js');266 const stream = subprocess.writable();267 const secondStream = subprocess.writable();268 const cause = new Error(foobarString);269 stream.destroy(cause);270 secondStream.destroy(cause);271272 const [error, secondError] = await Promise.all([273 assertStreamError(t, stream, {cause}),274 assertStreamError(t, secondStream, {cause}),273 assertStreamError(stream, {cause}),274 assertStreamError(secondStream, {cause}),275 ]);276 t.is(error, secondError);277 await assertSubprocessError(t, subprocess, error);276 assert.equal(error, secondError);277 await assertSubprocessError(subprocess, error);278});279280test('Can error one of two .writable() on different file descriptors', async t => {280test('Can error one of two .writable() on different file descriptors', async () => {281 const subprocess = execa('stdin-fd-both.js', ['3'], fullReadableStdio());282 const stream = subprocess.writable();283 const secondStream = subprocess.writable({to: 'fd3'});284 const cause = new Error(foobarString);285 stream.destroy(cause);286 secondStream.end(foobarString);287288 const [error, secondError] = await Promise.all([289 assertStreamError(t, stream, {cause}),290 assertStreamError(t, secondStream, {cause}),289 assertStreamError(stream, {cause}),290 assertStreamError(secondStream, {cause}),291 ]);292 t.is(error, secondError);293 t.is(error.stdout, foobarString);294 await assertSubprocessError(t, subprocess, error);292 assert.equal(error, secondError);293 assert.equal(error.stdout, foobarString);294 await assertSubprocessError(subprocess, error);295});296297test('Can error both .writable() on different file descriptors', async t => {297test('Can error both .writable() on different file descriptors', async () => {298 const subprocess = execa('stdin-fd-both.js', ['3'], fullReadableStdio());299 const stream = subprocess.writable();300 const secondStream = subprocess.writable({to: 'fd3'});301 const cause = new Error(foobarString);302 stream.destroy(cause);303 secondStream.destroy(cause);304305 const [error, secondError] = await Promise.all([306 assertStreamError(t, stream, {cause}),307 assertStreamError(t, secondStream, {cause}),306 assertStreamError(stream, {cause}),307 assertStreamError(secondStream, {cause}),308 ]);309 t.is(error, secondError);310 await assertSubprocessError(t, subprocess, error);309 assert.equal(error, secondError);310 await assertSubprocessError(subprocess, error);311});312313test('Can error one of two .duplex() on same file descriptor', async t => {313test('Can error one of two .duplex() on same file descriptor', async () => {314 const subprocess = execa('stdin.js');315 const stream = subprocess.duplex();316 const secondStream = subprocess.duplex();317 const cause = new Error(foobarString);318 stream.destroy(cause);319 secondStream.end(foobarString);320321 await Promise.all([322 assertStreamReadError(t, stream, cause),323 assertStreamOutput(t, secondStream),322 assertStreamReadError(stream, cause),323 assertStreamOutput(secondStream),324 ]);325 await assertSubprocessOutput(t, subprocess);325 await assertSubprocessOutput(subprocess);326});327328test('Can error both .duplex() on same file descriptor', async t => {328test('Can error both .duplex() on same file descriptor', async () => {329 const subprocess = execa('stdin.js');330 const stream = subprocess.duplex();331 const secondStream = subprocess.duplex();332 const cause = new Error(foobarString);333 stream.destroy(cause);334 secondStream.destroy(cause);335336 await Promise.all([337 assertStreamReadError(t, stream, cause),338 assertStreamReadError(t, secondStream, cause),337 assertStreamReadError(stream, cause),338 assertStreamReadError(secondStream, cause),339 ]);340 await assertSubprocessError(t, subprocess, {cause});340 await assertSubprocessError(subprocess, {cause});341});342343test('Can error one of two .duplex() on different file descriptors', async t => {343test('Can error one of two .duplex() on different file descriptors', async () => {344 const subprocess = execa('stdin-twice-both.js', ['3'], fullReadableStdio());345 const stream = subprocess.duplex();346 const secondStream = subprocess.duplex({from: 'stderr', to: 'fd3'});347 const cause = new Error(foobarString);348 stream.destroy(cause);349 secondStream.end(foobarString);350351 const [error] = await Promise.all([352 assertStreamReadError(t, secondStream, {cause}),353 assertStreamReadError(t, stream, cause),352 assertStreamReadError(secondStream, {cause}),353 assertStreamReadError(stream, cause),354 ]);355 t.is(error.stderr, foobarString);356 await assertSubprocessError(t, subprocess, error);355 assert.equal(error.stderr, foobarString);356 await assertSubprocessError(subprocess, error);357});358359test('Can error both .duplex() on different file descriptors', async t => {359test('Can error both .duplex() on different file descriptors', async () => {360 const subprocess = execa('stdin-twice-both.js', ['3'], fullReadableStdio());361 const stream = subprocess.duplex();362 const secondStream = subprocess.duplex({from: 'stderr', to: 'fd3'});363 const cause = new Error(foobarString);364 stream.destroy(cause);365 secondStream.destroy(cause);366367 await Promise.all([368 assertStreamReadError(t, stream, cause),369 assertStreamReadError(t, secondStream, cause),368 assertStreamReadError(stream, cause),369 assertStreamReadError(secondStream, cause),370 ]);371 await assertSubprocessError(t, subprocess, {cause});371 await assertSubprocessError(subprocess, {cause});372});
modified:test/convert/duplex.js+78 added-77 removed
1import assert from 'node:assert/strict';2import {pipeline} from 'node:stream/promises';3import {text} from 'node:stream/consumers';4import test from 'node:test';5import {6 compose,7 Readable,8 Writable,9 PassThrough,10} from 'node:stream';7import {pipeline} from 'node:stream/promises';8import {text} from 'node:stream/consumers';9import test from 'ava';11import {assertRejects, assertLike} from '../helpers/assert.js';12import {execa} from '../../index.js';13import {setFixtureDirectory} from '../helpers/fixtures-directory.js';14import {15 finishedStream,
19 unmodified lines
35import {defaultHighWaterMark} from '../helpers/stream.js';3637setFixtureDirectory();3837test('.duplex() success', async t => {39test('.duplex() success', async () => {40 const subprocess = getReadWriteSubprocess();41 const stream = subprocess.duplex();4241 t.true(stream instanceof Writable);42 t.true(stream.writable);43 t.true(stream instanceof Readable);44 t.true(stream.readable);43 assert.ok(stream instanceof Writable);44 assert.equal(stream.writable, true);45 assert.ok(stream instanceof Readable);46 assert.equal(stream.readable, true);4748 stream.end(foobarString);4948 await assertStreamOutput(t, stream);49 await assertSubprocessOutput(t, subprocess);50 await assertStreamOutput(stream);51 await assertSubprocessOutput(subprocess);52});5352// eslint-disable-next-line max-params53const testReadableDuplexDefault = async (t, fdNumber, from, options, hasResult) => {54const testReadableDuplexDefault = async (fdNumber, from, options, hasResult) => {55 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], options);56 const stream = subprocess.duplex({from});57 stream.end(foobarString);5858 await assertStreamOutput(t, stream, hasResult ? foobarString : '');59 await assertSubprocessOutput(t, subprocess, foobarString, fdNumber);59 await assertStreamOutput(stream, hasResult ? foobarString : '');60 await assertSubprocessOutput(subprocess, foobarString, fdNumber);61};6262test('.duplex() can use stdout', testReadableDuplexDefault, 1, 'stdout', {}, true);63test('.duplex() can use stderr', testReadableDuplexDefault, 2, 'stderr', {}, true);64test('.duplex() can use output stdio[*]', testReadableDuplexDefault, 3, 'fd3', fullStdio, true);65test('.duplex() uses stdout by default', testReadableDuplexDefault, 1, undefined, {}, true);66test('.duplex() does not use stderr by default', testReadableDuplexDefault, 2, undefined, {}, false);67test('.duplex() does not use stdio[*] by default', testReadableDuplexDefault, 3, undefined, fullStdio, false);68test('.duplex() uses stdout even if stderr is "ignore"', testReadableDuplexDefault, 1, 'stdout', {stderr: 'ignore'}, true);69test('.duplex() uses stderr even if stdout is "ignore"', testReadableDuplexDefault, 2, 'stderr', {stdout: 'ignore'}, true);70test('.duplex() uses stdout if "all" is used', testReadableDuplexDefault, 1, 'all', {all: true}, true);71test('.duplex() uses stderr if "all" is used', testReadableDuplexDefault, 2, 'all', {all: true}, true);63test('.duplex() can use stdout', () => testReadableDuplexDefault(1, 'stdout', {}, true));64test('.duplex() can use stderr', () => testReadableDuplexDefault(2, 'stderr', {}, true));65test('.duplex() can use output stdio[*]', () => testReadableDuplexDefault(3, 'fd3', fullStdio, true));66test('.duplex() uses stdout by default', () => testReadableDuplexDefault(1, undefined, {}, true));67test('.duplex() does not use stderr by default', () => testReadableDuplexDefault(2, undefined, {}, false));68test('.duplex() does not use stdio[*] by default', () => testReadableDuplexDefault(3, undefined, fullStdio, false));69test('.duplex() uses stdout even if stderr is "ignore"', () => testReadableDuplexDefault(1, 'stdout', {stderr: 'ignore'}, true));70test('.duplex() uses stderr even if stdout is "ignore"', () => testReadableDuplexDefault(2, 'stderr', {stdout: 'ignore'}, true));71test('.duplex() uses stdout if "all" is used', () => testReadableDuplexDefault(1, 'all', {all: true}, true));72test('.duplex() uses stderr if "all" is used', () => testReadableDuplexDefault(2, 'all', {all: true}, true));7373const testWritableDuplexDefault = async (t, fdNumber, to, options) => {74const testWritableDuplexDefault = async (fdNumber, to, options) => {75 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], options);76 const stream = subprocess.duplex({to});7778 stream.end(foobarString);7979 await assertStreamOutput(t, stream, foobarString);80 await assertSubprocessOutput(t, subprocess);80 await assertStreamOutput(stream, foobarString);81 await assertSubprocessOutput(subprocess);82};8383test('.duplex() can use stdin', testWritableDuplexDefault, 0, 'stdin', {});84test('.duplex() can use input stdio[*]', testWritableDuplexDefault, 3, 'fd3', fullReadableStdio());85test('.duplex() can use input stdio[*] with { value: "pipe", input: true }', testWritableDuplexDefault, 3, 'fd3', getStdio(3, {value: 'pipe', input: true}));86test('.duplex() uses stdin by default', testWritableDuplexDefault, 0, undefined, {});84test('.duplex() can use stdin', () => testWritableDuplexDefault(0, 'stdin', {}));85test('.duplex() can use input stdio[*]', () => testWritableDuplexDefault(3, 'fd3', fullReadableStdio()));86test('.duplex() can use input stdio[*] with { value: "pipe", input: true }', () => testWritableDuplexDefault(3, 'fd3', getStdio(3, {value: 'pipe', input: true})));87test('.duplex() uses stdin by default', () => testWritableDuplexDefault(0, undefined, {}));8888test('.duplex() abort -> subprocess fail', async t => {89test('.duplex() abort -> subprocess fail', async () => {90 const subprocess = getReadWriteSubprocess();91 const stream = subprocess.duplex();92 const textPromise = text(stream);9394 stream.destroy();9595 const error = await t.throwsAsync(textPromise);96 t.like(error, prematureClose);97 assertProcessNormalExit(t, error);98 assertWritableAborted(t, subprocess.stdin);99 assertReadableAborted(t, subprocess.stdout);100 t.true(subprocess.stderr.readableEnded);101 await assertSubprocessError(t, subprocess, error);96 const error = await assertRejects(textPromise);97 assertLike(error, prematureClose);98 assertProcessNormalExit(error);99 assertWritableAborted(subprocess.stdin);100 assertReadableAborted(subprocess.stdout);101 assert.equal(subprocess.stderr.readableEnded, true);102 await assertSubprocessError(subprocess, error);103});104104test('.duplex() error -> subprocess fail', async t => {105test('.duplex() error -> subprocess fail', async () => {106 const subprocess = getReadWriteSubprocess();107 const stream = subprocess.duplex();108109 const cause = new Error(foobarString);110 stream.destroy(cause);111111 const error = await assertStreamError(t, stream, {cause});112 assertProcessNormalExit(t, error);113 t.is(subprocess.stdin.errored, cause);114 t.is(subprocess.stdout.errored, cause);115 t.true(subprocess.stderr.readableEnded);116 await assertSubprocessError(t, subprocess, error);112 const error = await assertStreamError(stream, {cause});113 assertProcessNormalExit(error);114 assert.equal(subprocess.stdin.errored, cause);115 assert.equal(subprocess.stdout.errored, cause);116 assert.equal(subprocess.stderr.readableEnded, true);117 await assertSubprocessError(subprocess, error);118});119119test('.duplex() can be used with Stream.pipeline()', async t => {120test('.duplex() can be used with Stream.pipeline()', async () => {121 const subprocess = getReadWriteSubprocess();122 const inputStream = Readable.from([foobarString]);123 const stream = subprocess.duplex();124 const outputStream = new PassThrough();
1 unmodified line
126 await pipeline(inputStream, stream, outputStream);127128 await finishedStream(inputStream);129 await finishedStream(stream);129 await assertStreamOutput(t, outputStream);130 await assertSubprocessOutput(t, subprocess);130 await assertStreamOutput(outputStream);131 await assertSubprocessOutput(subprocess);132});133133test('.duplex() can error with Stream.pipeline()', async t => {134test('.duplex() can error with Stream.pipeline()', async () => {135 const subprocess = execa('stdin-fail.js');136 const inputStream = Readable.from([foobarString]);137 const stream = subprocess.duplex();138 const outputStream = new PassThrough();139139 const error = await t.throwsAsync(pipeline(inputStream, stream, outputStream));140 assertProcessNormalExit(t, error, 2);141 t.like(error, {stdout: foobarString});140 const error = await assertRejects(pipeline(inputStream, stream, outputStream));141 assertProcessNormalExit(error, 2);142 assertLike(error, {stdout: foobarString});143144 await finishedStream(inputStream);144 await assertStreamError(t, stream, error);145 await assertStreamReadError(t, outputStream, error);146 await assertSubprocessError(t, subprocess, error);145 await assertStreamError(stream, error);146 await assertStreamReadError(outputStream, error);147 await assertSubprocessError(subprocess, error);148});149149test('.duplex() can pipe to errored stream with Stream.pipeline()', async t => {150test('.duplex() can pipe to errored stream with Stream.pipeline()', async () => {151 const subprocess = execa('stdin-fail.js');152 const inputStream = Readable.from([foobarString]);153 const stream = subprocess.duplex();154 const outputStream = new PassThrough();
4 unmodified lines
159 // Node 23 does not allow calling `stream.pipeline()` with an already errored stream160 if (majorNodeVersion >= 23) {161 outputStream.on('error', () => {});162 stream.on('error', () => {});162 await t.throwsAsync(pipeline(stream, outputStream), {code: 'ERR_STREAM_UNABLE_TO_PIPE'});163 await assertRejects(pipeline(stream, outputStream), {code: 'ERR_STREAM_UNABLE_TO_PIPE'});164 stream.end();165 } else {165 await assertPromiseError(t, pipeline(inputStream, stream, outputStream), cause);166 await t.throwsAsync(finishedStream(stream));166 await assertPromiseError(pipeline(inputStream, stream, outputStream), cause);167 await assertRejects(finishedStream(stream));168168 await assertStreamError(t, inputStream, cause);169 const error = await assertStreamError(t, stream, cause);170 await assertStreamReadError(t, outputStream, cause);171 await assertSubprocessError(t, subprocess, {cause: error});169 await assertStreamError(inputStream, cause);170 const error = await assertStreamError(stream, cause);171 await assertStreamReadError(outputStream, cause);172 await assertSubprocessError(subprocess, {cause: error});173 }174});175175test('.duplex() can be piped to errored stream with Stream.pipeline()', async t => {176test('.duplex() can be piped to errored stream with Stream.pipeline()', async () => {177 const subprocess = execa('stdin-fail.js');178 const inputStream = Readable.from([foobarString]);179 const stream = subprocess.duplex();180 const outputStream = new PassThrough();181182 const cause = new Error('test');183 inputStream.destroy(cause);184184 await assertPromiseError(t, pipeline(inputStream, stream, outputStream), cause);185 await t.throwsAsync(finishedStream(stream));185 await assertPromiseError(pipeline(inputStream, stream, outputStream), cause);186 await assertRejects(finishedStream(stream));187187 await assertStreamError(t, inputStream, cause);188 const error = await assertStreamError(t, stream, cause);189 await assertStreamReadError(t, outputStream, cause);190 await assertSubprocessError(t, subprocess, {cause: error});188 await assertStreamError(inputStream, cause);189 const error = await assertStreamError(stream, cause);190 await assertStreamReadError(outputStream, cause);191 await assertSubprocessError(subprocess, {cause: error});192});193193test('.duplex() can be used with Stream.compose()', async t => {194test('.duplex() can be used with Stream.compose()', async () => {195 const subprocess = getReadWriteSubprocess();196 const inputStream = Readable.from([foobarString]);197 const stream = subprocess.duplex();198 const outputStream = new PassThrough();199199 await assertStreamOutput(t, compose(inputStream, stream, outputStream));200 await assertSubprocessOutput(t, subprocess);200 await assertStreamOutput(compose(inputStream, stream, outputStream));201 await assertSubprocessOutput(subprocess);202});203203test('.duplex() has the right highWaterMark', async t => {204test('.duplex() has the right highWaterMark', async () => {205 const subprocess = getReadWriteSubprocess();206 const stream = subprocess.duplex();206 t.is(stream.readableHighWaterMark, defaultHighWaterMark);207 t.is(stream.writableHighWaterMark, defaultHighWaterMark);207 assert.equal(stream.readableHighWaterMark, defaultHighWaterMark);208 assert.equal(stream.writableHighWaterMark, defaultHighWaterMark);209 stream.end();210 await text(stream);211});
modified:test/convert/iterable.js+63 added-61 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';7import {fullStdio, assertEpipe} from '../helpers/stdio.js';
16 unmodified lines
2425 return lines;26};2726const errorArrayFromAsync = async (t, cause, asyncIterable, lines = []) => {28const errorArrayFromAsync = async (cause, asyncIterable, lines = []) => {29 const {value} = await asyncIterable.next();30 lines.push(value);31 await asyncIterable.throw(cause);32};3332const throwsAsync = async (t, asyncIterable, arrayFromAsyncMethod) => {34const throwsAsync = async (asyncIterable, arrayFromAsyncMethod) => {35 const lines = [];34 const error = await t.throwsAsync(arrayFromAsyncMethod(asyncIterable, lines));36 const error = await assertRejects(arrayFromAsyncMethod(asyncIterable, lines));37 return {error, lines};38};3938const assertStdoutAbort = (t, subprocess, error, cause) => {39 assertProcessNormalExit(t, error, 1);40 assertEpipe(t, error.stderr);41 assertWritableAborted(t, subprocess.stdin);42 t.true(subprocess.stderr.readableEnded);40const assertStdoutAbort = (subprocess, error, cause) => {41 assertProcessNormalExit(error, 1);42 assertEpipe(error.stderr);43 assertWritableAborted(subprocess.stdin);44 assert.equal(subprocess.stderr.readableEnded, true);4546 if (cause === undefined) {45 assertReadableAborted(t, subprocess.stdout);47 assertReadableAborted(subprocess.stdout);48 } else {47 t.is(subprocess.stdout.errored, cause);49 assert.equal(subprocess.stdout.errored, cause);50 }51};5251const testSuccess = async (t, fdNumber, from, options = {}) => {53const testSuccess = async (fdNumber, from, options = {}) => {54 const lines = await arrayFromAsync(execa('noop-fd.js', [`${fdNumber}`, simpleFull], options).iterable({from}));53 t.deepEqual(lines, noNewlinesChunks);55 assert.deepEqual(lines, noNewlinesChunks);56};5756test('Uses stdout by default', testSuccess, 1, undefined);57test('Can iterate successfully on stdout', testSuccess, 1, 'stdout');58test('Can iterate successfully on stderr', testSuccess, 2, 'stderr');59test('Can iterate successfully on stdio[*]', testSuccess, 3, 'fd3', fullStdio);58test('Uses stdout by default', () => testSuccess(1, undefined));59test('Can iterate successfully on stdout', () => testSuccess(1, 'stdout'));60test('Can iterate successfully on stderr', () => testSuccess(2, 'stderr'));61test('Can iterate successfully on stdio[*]', () => testSuccess(3, 'fd3', fullStdio));6261test('Can iterate successfully on all', async t => {63test('Can iterate successfully on all', async () => {64 const lines = await arrayFromAsync(execa('noop-both.js', [simpleFull], {all: true}).iterable({from: 'all'}));63 t.deepEqual(lines, [...noNewlinesChunks, ...noNewlinesChunks]);65 assert.deepEqual(lines, [...noNewlinesChunks, ...noNewlinesChunks]);66});6766test('Can iterate using Symbol.asyncIterator', async t => {68test('Can iterate using Symbol.asyncIterator', async () => {69 const lines = await arrayFromAsync(execa('noop-fd.js', ['1', simpleFull]));68 t.deepEqual(lines, noNewlinesChunks);70 assert.deepEqual(lines, noNewlinesChunks);71});7271const assertMultipleCalls = async (t, iterable, iterableTwo) => {72 t.not(iterable, iterableTwo);73const assertMultipleCalls = async (iterable, iterableTwo) => {74 assert.notEqual(iterable, iterableTwo);75 const lines = await arrayFromAsync(iterable);76 const linesTwo = await arrayFromAsync(iterableTwo);75 t.deepEqual(lines, linesTwo);76 t.deepEqual(lines, noNewlinesChunks);77 assert.deepEqual(lines, linesTwo);78 assert.deepEqual(lines, noNewlinesChunks);79};8079test('Can be called multiple times', async t => {81test('Can be called multiple times', async () => {82 const subprocess = execa('noop-fd.js', ['1', simpleFull]);83 const iterable = subprocess.iterable();84 const iterableTwo = subprocess.iterable();83 await assertMultipleCalls(t, iterable, iterableTwo);85 await assertMultipleCalls(iterable, iterableTwo);86});8786test('Can be called on different file descriptors', async t => {88test('Can be called on different file descriptors', async () => {89 const subprocess = execa('noop-both.js', [simpleFull]);90 const iterable = subprocess.iterable();91 const iterableTwo = subprocess.iterable({from: 'stderr'});90 await assertMultipleCalls(t, iterable, iterableTwo);92 await assertMultipleCalls(iterable, iterableTwo);93});9493test('Wait for the subprocess exit', async t => {95test('Wait for the subprocess exit', async () => {96 const subprocess = execa('noop-delay.js', ['1', simpleFull]);97 const linesPromise = arrayFromAsync(subprocess);96 t.is(await Promise.race([linesPromise, subprocess]), await subprocess);97 t.deepEqual(await linesPromise, noNewlinesChunks);98 assert.equal(await Promise.race([linesPromise, subprocess]), await subprocess);99 assert.deepEqual(await linesPromise, noNewlinesChunks);100});101100test('Wait for the subprocess exit on iterator.return()', async t => {102test('Wait for the subprocess exit on iterator.return()', async () => {103 const subprocess = execa('noop-delay.js', ['1', simpleFull]);104 const linesPromise = partialArrayFromAsync(subprocess);103 t.is(await Promise.race([linesPromise, subprocess]), await subprocess);104 t.deepEqual(await linesPromise, [noNewlinesChunks[0]]);105 assert.equal(await Promise.race([linesPromise, subprocess]), await subprocess);106 assert.deepEqual(await linesPromise, [noNewlinesChunks[0]]);107});108107test('Wait for the subprocess exit on iterator.throw()', async t => {109test('Wait for the subprocess exit on iterator.throw()', async () => {110 const subprocess = execa('noop-delay.js', ['1', simpleFull]);111 const cause = new Error(foobarString);112 const lines = [];111 const linesPromise = t.throwsAsync(errorArrayFromAsync(t, cause, subprocess.iterable(), lines));112 t.is(await Promise.race([linesPromise, subprocess]), await subprocess);113 t.deepEqual(lines, [noNewlinesChunks[0]]);113 const linesPromise = assertRejects(errorArrayFromAsync(cause, subprocess.iterable(), lines));114 assert.equal(await Promise.race([linesPromise, subprocess]), await subprocess);115 assert.deepEqual(lines, [noNewlinesChunks[0]]);116});117116test('Abort stdout on iterator.return()', async t => {118test('Abort stdout on iterator.return()', async () => {119 const subprocess = execa('noop-repeat.js', ['1', simpleFull]);118 const {error, lines} = await throwsAsync(t, subprocess, partialArrayFromAsync);119 t.deepEqual(lines, [noNewlinesChunks[0]]);120 assertStdoutAbort(t, subprocess, error);121 t.is(error, await t.throwsAsync(subprocess));120 const {error, lines} = await throwsAsync(subprocess, partialArrayFromAsync);121 assert.deepEqual(lines, [noNewlinesChunks[0]]);122 assertStdoutAbort(subprocess, error);123 assert.equal(error, await assertRejects(subprocess));124});125124test('Abort stdout on iterator.throw()', async t => {126test('Abort stdout on iterator.throw()', async () => {127 const subprocess = execa('noop-repeat.js', ['1', simpleFull]);128 const cause = new Error(foobarString);127 const {error, lines} = await throwsAsync(t, subprocess.iterable(), errorArrayFromAsync.bind(undefined, t, cause));128 t.deepEqual(lines, [noNewlinesChunks[0]]);129 assertStdoutAbort(t, subprocess, error);130 t.is(error, await t.throwsAsync(subprocess));129 const {error, lines} = await throwsAsync(subprocess.iterable(), errorArrayFromAsync.bind(undefined, cause));130 assert.deepEqual(lines, [noNewlinesChunks[0]]);131 assertStdoutAbort(subprocess, error);132 assert.equal(error, await assertRejects(subprocess));133});134133test('Propagate subprocess failure', async t => {135test('Propagate subprocess failure', async () => {136 const subprocess = execa('noop-fail.js', ['1', simpleFull]);135 const {error, lines} = await throwsAsync(t, subprocess, arrayFromAsync);136 t.is(error, await t.throwsAsync(subprocess));137 t.deepEqual(lines, noNewlinesChunks);137 const {error, lines} = await throwsAsync(subprocess, arrayFromAsync);138 assert.equal(error, await assertRejects(subprocess));139 assert.deepEqual(lines, noNewlinesChunks);140});141140const testStdoutError = async (t, destroyStdout, isAbort, cause) => {142const testStdoutError = async (destroyStdout, isAbort, cause) => {143 const subprocess = execa('noop-repeat.js', ['1', simpleFull]);144 subprocess.stdout.once('data', () => {145 destroyStdout(subprocess.stdout, cause);146 });147146 const {error} = await throwsAsync(t, subprocess, arrayFromAsync);147 t.is(error.cause, cause);148 assertStdoutAbort(t, subprocess, error, isAbort ? undefined : cause);149 t.is(error, await t.throwsAsync(subprocess));148 const {error} = await throwsAsync(subprocess, arrayFromAsync);149 assert.equal(error.cause, cause);150 assertStdoutAbort(subprocess, error, isAbort ? undefined : cause);151 assert.equal(error, await assertRejects(subprocess));152};153152test('Propagate stdout abort', testStdoutError, subprocessStdout => subprocessStdout.destroy(), true);153test('Propagate stdout error', testStdoutError, (subprocessStdout, cause) => subprocessStdout.destroy(cause), false, new Error(foobarString));154test('Propagate stdout "error" event', testStdoutError, (subprocessStdout, cause) => subprocessStdout.emit('error', cause), true, new Error(foobarString));154test('Propagate stdout abort', () => testStdoutError(subprocessStdout => subprocessStdout.destroy(), true));155test('Propagate stdout error', () => testStdoutError((subprocessStdout, cause) => subprocessStdout.destroy(cause), false, new Error(foobarString)));156test('Propagate stdout "error" event', () => testStdoutError((subprocessStdout, cause) => subprocessStdout.emit('error', cause), true, new Error(foobarString)));
modified:test/convert/readable.js+178 added-177 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {pipeline} from 'node:stream/promises';4import {text} from 'node:stream/consumers';5import {setTimeout} from 'node:timers/promises';6import test from 'node:test';7import {8 compose,9 Readable,10 Writable,11 PassThrough,12} from 'node:stream';8import {pipeline} from 'node:stream/promises';9import {text} from 'node:stream/consumers';10import {setTimeout} from 'node:timers/promises';11import test from 'ava';13import {assertRejects, assertLike} from '../helpers/assert.js';14import {execa} from '../../index.js';15import {setFixtureDirectory} from '../helpers/fixtures-directory.js';16import {17 finishedStream,
18 unmodified lines
36import {defaultHighWaterMark, defaultObjectHighWaterMark} from '../helpers/stream.js';3738setFixtureDirectory();3938test('.readable() success', async t => {40test('.readable() success', async () => {41 const subprocess = getReadableSubprocess();42 const stream = subprocess.readable();4342 t.false(stream instanceof Writable);43 t.is(stream.writable, undefined);44 t.true(stream instanceof Readable);45 t.true(stream.readable);44 assert.ok(!(stream instanceof Writable));45 assert.equal(stream.writable, undefined);46 assert.ok(stream instanceof Readable);47 assert.equal(stream.readable, true);4847 await assertStreamOutput(t, stream);48 await assertSubprocessOutput(t, subprocess);49 await assertStreamOutput(stream);50 await assertSubprocessOutput(subprocess);51});5251// eslint-disable-next-line max-params52const testReadableDefault = async (t, fdNumber, from, options, hasResult) => {53const testReadableDefault = async (fdNumber, from, options, hasResult) => {54 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], options);55 const stream = subprocess.readable({from});5656 await assertStreamOutput(t, stream, hasResult ? foobarString : '');57 await assertSubprocessOutput(t, subprocess, foobarString, fdNumber);57 await assertStreamOutput(stream, hasResult ? foobarString : '');58 await assertSubprocessOutput(subprocess, foobarString, fdNumber);59};6060test('.readable() can use stdout', testReadableDefault, 1, 'stdout', {}, true);61test('.readable() can use stderr', testReadableDefault, 2, 'stderr', {}, true);62test('.readable() can use stdio[*]', testReadableDefault, 3, 'fd3', fullStdio, true);63test('.readable() uses stdout by default', testReadableDefault, 1, undefined, {}, true);64test('.readable() does not use stderr by default', testReadableDefault, 2, undefined, {}, false);65test('.readable() does not use stdio[*] by default', testReadableDefault, 3, undefined, fullStdio, false);66test('.readable() uses stdout even if stderr is "ignore"', testReadableDefault, 1, 'stdout', {stderr: 'ignore'}, true);67test('.readable() uses stderr even if stdout is "ignore"', testReadableDefault, 2, 'stderr', {stdout: 'ignore'}, true);68test('.readable() uses stdout if "all" is used', testReadableDefault, 1, 'all', {all: true}, true);69test('.readable() uses stderr if "all" is used', testReadableDefault, 2, 'all', {all: true}, true);61test('.readable() can use stdout', () => testReadableDefault(1, 'stdout', {}, true));62test('.readable() can use stderr', () => testReadableDefault(2, 'stderr', {}, true));63test('.readable() can use stdio[*]', () => testReadableDefault(3, 'fd3', fullStdio, true));64test('.readable() uses stdout by default', () => testReadableDefault(1, undefined, {}, true));65test('.readable() does not use stderr by default', () => testReadableDefault(2, undefined, {}, false));66test('.readable() does not use stdio[*] by default', () => testReadableDefault(3, undefined, fullStdio, false));67test('.readable() uses stdout even if stderr is "ignore"', () => testReadableDefault(1, 'stdout', {stderr: 'ignore'}, true));68test('.readable() uses stderr even if stdout is "ignore"', () => testReadableDefault(2, 'stderr', {stdout: 'ignore'}, true));69test('.readable() uses stdout if "all" is used', () => testReadableDefault(1, 'all', {all: true}, true));70test('.readable() uses stderr if "all" is used', () => testReadableDefault(2, 'all', {all: true}, true));7171const testBuffering = async (t, methodName) => {72const testBuffering = async methodName => {73 const subprocess = execa('noop-stdin-fd.js', ['1'], {buffer: false});74 const stream = subprocess[methodName]();7576 subprocess.stdin.write(foobarString);77 await once(subprocess.stdout, 'readable');78 subprocess.stdin.end();7979 await assertStreamOutput(t, stream);80 await assertStreamOutput(stream);81};8282test('.readable() buffers until read', testBuffering, 'readable');83test('.duplex() buffers until read', testBuffering, 'duplex');83test('.readable() buffers until read', () => testBuffering('readable'));84test('.duplex() buffers until read', () => testBuffering('duplex'));8585test('.readable() abort -> subprocess fail', async t => {86test('.readable() abort -> subprocess fail', async () => {87 const subprocess = execa('noop-repeat.js');88 const stream = subprocess.readable();8990 stream.destroy();9191 const error = await t.throwsAsync(text(stream));92 assertProcessNormalExit(t, error, 1);93 t.true(error.message.includes('EPIPE'));94 assertWritableAborted(t, subprocess.stdin);95 assertReadableAborted(t, subprocess.stdout);96 t.true(subprocess.stderr.readableEnded);97 await assertSubprocessError(t, subprocess, error);92 const error = await assertRejects(text(stream));93 assertProcessNormalExit(error, 1);94 assert.ok(error.message.includes('EPIPE'));95 assertWritableAborted(subprocess.stdin);96 assertReadableAborted(subprocess.stdout);97 assert.equal(subprocess.stderr.readableEnded, true);98 await assertSubprocessError(subprocess, error);99});100100test('.readable() error -> subprocess fail', async t => {101test('.readable() error -> subprocess fail', async () => {102 const subprocess = execa('noop-repeat.js');103 const stream = subprocess.readable();104105 const cause = new Error(foobarString);106 stream.destroy(cause);107107 const error = await assertStreamReadError(t, stream, {cause});108 assertProcessNormalExit(t, error, 1);109 t.true(error.message.includes('EPIPE'));110 assertWritableAborted(t, subprocess.stdin);111 t.is(subprocess.stdout.errored, cause);112 t.true(subprocess.stderr.readableEnded);113 await assertSubprocessError(t, subprocess, error);108 const error = await assertStreamReadError(stream, {cause});109 assertProcessNormalExit(error, 1);110 assert.ok(error.message.includes('EPIPE'));111 assertWritableAborted(subprocess.stdin);112 assert.equal(subprocess.stdout.errored, cause);113 assert.equal(subprocess.stderr.readableEnded, true);114 await assertSubprocessError(subprocess, error);115});116116const testStdoutAbort = async (t, methodName) => {117const testStdoutAbort = async methodName => {118 const subprocess = execa('ipc-echo.js', {ipc: true});119 const stream = subprocess[methodName]();120121 subprocess.stdout.destroy();122123 await subprocess.sendMessage(foobarString);124 const [error, message] = await Promise.all([124 t.throwsAsync(finishedStream(stream)),125 assertRejects(finishedStream(stream)),126 subprocess.getOneMessage(),127 ]);127 t.like(error, prematureClose);128 t.is(message, foobarString);129 assertWritableAborted(t, subprocess.stdin);130 assertReadableAborted(t, subprocess.stdout);131 t.true(subprocess.stderr.readableEnded);132 await assertSubprocessOutput(t, subprocess, '');128 assertLike(error, prematureClose);129 assert.equal(message, foobarString);130 assertWritableAborted(subprocess.stdin);131 assertReadableAborted(subprocess.stdout);132 assert.equal(subprocess.stderr.readableEnded, true);133 await assertSubprocessOutput(subprocess, '');134};135135test('subprocess.stdout abort + no more writes -> .readable() error + subprocess success', testStdoutAbort, 'readable');136test('subprocess.stdout abort + no more writes -> .duplex() error + subprocess success', testStdoutAbort, 'duplex');136test('subprocess.stdout abort + no more writes -> .readable() error + subprocess success', () => testStdoutAbort('readable'));137test('subprocess.stdout abort + no more writes -> .duplex() error + subprocess success', () => testStdoutAbort('duplex'));138138const testStdoutError = async (t, methodName) => {139const testStdoutError = async methodName => {140 const subprocess = execa('ipc-echo.js', {ipc: true});141 const stream = subprocess[methodName]();142143 const cause = new Error(foobarString);144 subprocess.stdout.destroy(cause);145146 await subprocess.sendMessage(foobarString);147 const [error, message] = await Promise.all([147 t.throwsAsync(finishedStream(stream)),148 assertRejects(finishedStream(stream)),149 subprocess.getOneMessage(),150 ]);150 t.is(message, foobarString);151 t.is(error.cause, cause);152 assertProcessNormalExit(t, error);153 t.is(subprocess.stdout.errored, cause);154 t.true(subprocess.stderr.readableEnded);155 assertWritableAborted(t, subprocess.stdin);151 assert.equal(message, foobarString);152 assert.equal(error.cause, cause);153 assertProcessNormalExit(error);154 assert.equal(subprocess.stdout.errored, cause);155 assert.equal(subprocess.stderr.readableEnded, true);156 assertWritableAborted(subprocess.stdin);157157 await assertSubprocessError(t, subprocess, error);158 await assertSubprocessError(subprocess, error);159};160160test('subprocess.stdout error + no more writes -> .readable() error + subprocess fail', testStdoutError, 'readable');161test('subprocess.stdout error + no more writes -> .duplex() error + subprocess fail', testStdoutError, 'duplex');161test('subprocess.stdout error + no more writes -> .readable() error + subprocess fail', () => testStdoutError('readable'));162test('subprocess.stdout error + no more writes -> .duplex() error + subprocess fail', () => testStdoutError('duplex'));163163const testStdinAbortWrites = async (t, methodName) => {164const testStdinAbortWrites = async methodName => {165 const subprocess = getReadWriteSubprocess();166 const stream = subprocess[methodName]();167168 subprocess.stdout.destroy();169 subprocess.stdin.end(foobarString);170170 const error = await t.throwsAsync(finishedStream(stream));171 assertProcessNormalExit(t, error, 1);172 t.true(subprocess.stdin.writableEnded);173 assertReadableAborted(t, subprocess.stdout);174 t.true(subprocess.stderr.readableEnded);175 await assertSubprocessError(t, subprocess, error);171 const error = await assertRejects(finishedStream(stream));172 assertProcessNormalExit(error, 1);173 assert.equal(subprocess.stdin.writableEnded, true);174 assertReadableAborted(subprocess.stdout);175 assert.equal(subprocess.stderr.readableEnded, true);176 await assertSubprocessError(subprocess, error);177};178178test('subprocess.stdout abort + more writes -> .readable() error + subprocess fail', testStdinAbortWrites, 'readable');179test('subprocess.stdout abort + more writes -> .duplex() error + subprocess fail', testStdinAbortWrites, 'duplex');179test('subprocess.stdout abort + more writes -> .readable() error + subprocess fail', () => testStdinAbortWrites('readable'));180test('subprocess.stdout abort + more writes -> .duplex() error + subprocess fail', () => testStdinAbortWrites('duplex'));181181const testStdinErrorWrites = async (t, methodName) => {182const testStdinErrorWrites = async methodName => {183 const subprocess = getReadWriteSubprocess();184 const stream = subprocess[methodName]();185186 const cause = new Error(foobarString);187 subprocess.stdout.destroy(cause);188 subprocess.stdin.end(foobarString);189189 const error = await assertStreamError(t, stream, {cause});190 assertProcessNormalExit(t, error, 1);191 t.true(subprocess.stdin.writableEnded);192 t.is(subprocess.stdout.errored, cause);193 t.true(subprocess.stderr.readableEnded);194 await assertSubprocessError(t, subprocess, error);190 const error = await assertStreamError(stream, {cause});191 assertProcessNormalExit(error, 1);192 assert.equal(subprocess.stdin.writableEnded, true);193 assert.equal(subprocess.stdout.errored, cause);194 assert.equal(subprocess.stderr.readableEnded, true);195 await assertSubprocessError(subprocess, error);196};197197test('subprocess.stdout error + more writes -> .readable() error + subprocess fail', testStdinErrorWrites, 'readable');198test('subprocess.stdout error + more writes -> .duplex() error + subprocess fail', testStdinErrorWrites, 'duplex');198test('subprocess.stdout error + more writes -> .readable() error + subprocess fail', () => testStdinErrorWrites('readable'));199test('subprocess.stdout error + more writes -> .duplex() error + subprocess fail', () => testStdinErrorWrites('duplex'));200200test('.readable() can be used with Stream.pipeline()', async t => {201test('.readable() can be used with Stream.pipeline()', async () => {202 const subprocess = getReadableSubprocess();203 const stream = subprocess.readable();204 const outputStream = new PassThrough();205206 await pipeline(stream, outputStream);207208 await finishedStream(stream);208 await assertStreamOutput(t, outputStream);209 await assertSubprocessOutput(t, subprocess);209 await assertStreamOutput(outputStream);210 await assertSubprocessOutput(subprocess);211});212212test('.readable() can error with Stream.pipeline()', async t => {213test('.readable() can error with Stream.pipeline()', async () => {214 const subprocess = execa('noop-fail.js', ['1', foobarString]);215 const stream = subprocess.readable();216 const outputStream = new PassThrough();217217 const error = await t.throwsAsync(pipeline(stream, outputStream));218 assertProcessNormalExit(t, error, 2);219 t.like(error, {stdout: foobarString});218 const error = await assertRejects(pipeline(stream, outputStream));219 assertProcessNormalExit(error, 2);220 assertLike(error, {stdout: foobarString});221221 await assertStreamError(t, stream, error);222 await assertStreamReadError(t, outputStream, error);223 await assertSubprocessError(t, subprocess, error);222 await assertStreamError(stream, error);223 await assertStreamReadError(outputStream, error);224 await assertSubprocessError(subprocess, error);225});226226test('.readable() can pipe to errored stream with Stream.pipeline()', async t => {227test('.readable() can pipe to errored stream with Stream.pipeline()', async () => {228 const subprocess = getReadableSubprocess();229 const stream = subprocess.readable();230 const outputStream = new PassThrough();231
2 unmodified lines
234235 // Node 23 does not allow calling `stream.pipeline()` with an already errored stream236 if (majorNodeVersion >= 23) {237 outputStream.on('error', () => {});237 await t.throwsAsync(pipeline(stream, outputStream), {code: 'ERR_STREAM_UNABLE_TO_PIPE'});238 await assertRejects(pipeline(stream, outputStream), {code: 'ERR_STREAM_UNABLE_TO_PIPE'});239 } else {239 await assertPromiseError(t, pipeline(stream, outputStream), cause);240 await t.throwsAsync(finishedStream(stream));240 await assertPromiseError(pipeline(stream, outputStream), cause);241 await assertRejects(finishedStream(stream));242242 const error = await assertStreamError(t, stream, cause);243 await assertStreamReadError(t, outputStream, cause);244 await assertSubprocessError(t, subprocess, {cause: error});243 const error = await assertStreamError(stream, cause);244 await assertStreamReadError(outputStream, cause);245 await assertSubprocessError(subprocess, {cause: error});246 }247});248248test('.readable() can be used with Stream.compose()', async t => {249test('.readable() can be used with Stream.compose()', async () => {250 const subprocess = getReadableSubprocess();251 const stream = subprocess.readable();252 const outputStream = new PassThrough();253253 await assertStreamOutput(t, compose(stream, outputStream));254 await assertSubprocessOutput(t, subprocess);254 await assertStreamOutput(compose(stream, outputStream));255 await assertSubprocessOutput(subprocess);256});257257test('.readable() works with objectMode', async t => {258test('.readable() works with objectMode', async () => {259 const subprocess = execa('noop.js', {stdout: outputObjectGenerator()});260 const stream = subprocess.readable();260 t.true(stream.readableObjectMode);261 t.is(stream.readableHighWaterMark, defaultObjectHighWaterMark);261 assert.equal(stream.readableObjectMode, true);262 assert.equal(stream.readableHighWaterMark, defaultObjectHighWaterMark);263263 await assertStreamChunks(t, stream, [foobarObject]);264 await assertSubprocessOutput(t, subprocess, [foobarObject]);264 await assertStreamChunks(stream, [foobarObject]);265 await assertSubprocessOutput(subprocess, [foobarObject]);266});267267test('.duplex() works with objectMode and reads', async t => {268test('.duplex() works with objectMode and reads', async () => {269 const subprocess = getReadWriteSubprocess({stdout: outputObjectGenerator()});270 const stream = subprocess.duplex();270 t.true(stream.readableObjectMode);271 t.is(stream.readableHighWaterMark, defaultObjectHighWaterMark);272 t.false(stream.writableObjectMode);273 t.is(stream.writableHighWaterMark, defaultHighWaterMark);271 assert.equal(stream.readableObjectMode, true);272 assert.equal(stream.readableHighWaterMark, defaultObjectHighWaterMark);273 assert.equal(stream.writableObjectMode, false);274 assert.equal(stream.writableHighWaterMark, defaultHighWaterMark);275 stream.end(foobarString);276276 await assertStreamChunks(t, stream, [foobarObject]);277 await assertSubprocessOutput(t, subprocess, [foobarObject]);277 await assertStreamChunks(stream, [foobarObject]);278 await assertSubprocessOutput(subprocess, [foobarObject]);279});280280test('.readable() works with default encoding', async t => {281test('.readable() works with default encoding', async () => {282 const subprocess = getReadableSubprocess();283 const stream = subprocess.readable();283 t.is(stream.readableEncoding, null);284 assert.equal(stream.readableEncoding, null);285285 await assertStreamChunks(t, stream, [foobarBuffer]);286 await assertSubprocessOutput(t, subprocess, foobarString);286 await assertStreamChunks(stream, [foobarBuffer]);287 await assertSubprocessOutput(subprocess, foobarString);288});289289test('.duplex() works with default encoding', async t => {290test('.duplex() works with default encoding', async () => {291 const subprocess = getReadWriteSubprocess();292 const stream = subprocess.duplex();292 t.is(stream.readableEncoding, null);293 assert.equal(stream.readableEncoding, null);294 stream.end(foobarString);295295 await assertStreamChunks(t, stream, [foobarBuffer]);296 await assertSubprocessOutput(t, subprocess, foobarString);296 await assertStreamChunks(stream, [foobarBuffer]);297 await assertSubprocessOutput(subprocess, foobarString);298});299299test('.readable() works with encoding "utf8"', async t => {300test('.readable() works with encoding "utf8"', async () => {301 const subprocess = getReadableSubprocess();302 subprocess.stdout.setEncoding('utf8');303 const stream = subprocess.readable();303 t.is(stream.readableEncoding, 'utf8');304 assert.equal(stream.readableEncoding, 'utf8');305305 await assertStreamChunks(t, stream, [foobarString]);306 await assertSubprocessOutput(t, subprocess, foobarString);306 await assertStreamChunks(stream, [foobarString]);307 await assertSubprocessOutput(subprocess, foobarString);308});309309test('.duplex() works with encoding "utf8"', async t => {310test('.duplex() works with encoding "utf8"', async () => {311 const subprocess = getReadWriteSubprocess();312 subprocess.stdout.setEncoding('utf8');313 const stream = subprocess.duplex();313 t.is(stream.readableEncoding, 'utf8');314 assert.equal(stream.readableEncoding, 'utf8');315 stream.end(foobarBuffer);316316 await assertStreamChunks(t, stream, [foobarString]);317 await assertSubprocessOutput(t, subprocess, foobarString);317 await assertStreamChunks(stream, [foobarString]);318 await assertSubprocessOutput(subprocess, foobarString);319});320320test('.readable() has the right highWaterMark', async t => {321test('.readable() has the right highWaterMark', async () => {322 const subprocess = execa('noop.js');323 const stream = subprocess.readable();323 t.is(stream.readableHighWaterMark, defaultHighWaterMark);324 assert.equal(stream.readableHighWaterMark, defaultHighWaterMark);325 await text(stream);326});327327test('.readable() can iterate over lines', async t => {328test('.readable() can iterate over lines', async () => {329 const subprocess = execa('noop-fd.js', ['1', simpleFull]);330 const lines = await Array.fromAsync(subprocess.readable({binary: false, preserveNewlines: false}));331332 const expectedLines = ['aaa', 'bbb', 'ccc'];332 t.deepEqual(lines, expectedLines);333 await assertSubprocessOutput(t, subprocess, simpleFull);333 assert.deepEqual(lines, expectedLines);334 await assertSubprocessOutput(subprocess, simpleFull);335});336336test('.readable() can wait for data', async t => {337test('.readable() can wait for data', async () => {338 const subprocess = execa('noop.js', {stdout: getOutputsAsyncGenerator([foobarString, foobarString])(false, true)});339 const stream = subprocess.readable();340340 t.is(stream.read(), null);341 assert.equal(stream.read(), null);342 await once(stream, 'readable');342 t.is(stream.read().toString(), foobarString);343 t.is(stream.read(), null);343 assert.equal(stream.read().toString(), foobarString);344 assert.equal(stream.read(), null);345 await once(stream, 'readable');345 t.is(stream.read().toString(), foobarString);346 t.is(stream.read(), null);346 assert.equal(stream.read().toString(), foobarString);347 assert.equal(stream.read(), null);348 await once(stream, 'readable');348 t.is(stream.read(), null);349 assert.equal(stream.read(), null);350351 await finishedStream(stream);351 await assertSubprocessOutput(t, subprocess, `${foobarString}${foobarString}`);352 await assertSubprocessOutput(subprocess, `${foobarString}${foobarString}`);353});354354const testBufferData = async (t, methodName) => {355const testBufferData = async methodName => {356 const chunk = '.'.repeat(defaultHighWaterMark).repeat(2);357 const subprocess = getReadWriteSubprocess();358 const stream = subprocess[methodName]();359 subprocess.stdin.end(chunk);360360 await assertStreamOutput(t, stream, chunk);361 await assertSubprocessOutput(t, subprocess, chunk);361 await assertStreamOutput(stream, chunk);362 await assertSubprocessOutput(subprocess, chunk);363};364364test('.readable() can buffer data', testBufferData, 'readable');365test('.duplex() can buffer data', testBufferData, 'duplex');365test('.readable() can buffer data', () => testBufferData('readable'));366test('.duplex() can buffer data', () => testBufferData('duplex'));367367const assertDataEvents = async (t, stream, subprocess) => {368const assertDataEvents = async (stream, subprocess) => {369 const [output] = await once(stream, 'data');369 t.is(output.toString(), foobarString);370 assert.equal(output.toString(), foobarString);371372 await finishedStream(stream);372 await assertSubprocessOutput(t, subprocess);373 await assertSubprocessOutput(subprocess);374};375375test('.readable() can be read with "data" events', async t => {376test('.readable() can be read with "data" events', async () => {377 const subprocess = getReadableSubprocess();378 const stream = subprocess.readable();379379 await assertDataEvents(t, stream, subprocess);380 await assertDataEvents(stream, subprocess);381});382382test('.duplex() can be read with "data" events', async t => {383test('.duplex() can be read with "data" events', async () => {384 const subprocess = getReadWriteSubprocess();385 const stream = subprocess.duplex();386 stream.end(foobarString);387387 await assertDataEvents(t, stream, subprocess);388 await assertDataEvents(stream, subprocess);389});390390const assertPause = async (t, stream, subprocess) => {391const assertPause = async (stream, subprocess) => {392 const onceData = once(stream, 'data');393 stream.pause();394394 t.is(stream.readableLength, 0);395 assert.equal(stream.readableLength, 0);396 do {397 // eslint-disable-next-line no-await-in-loop398 await setTimeout(10);399 } while (stream.readableLength === 0);400400 t.false(await Promise.race([onceData, false]));401 assert.ok(!await Promise.race([onceData, false]));402403 stream.resume();404 const [output] = await onceData;404 t.is(output.toString(), foobarString);405 assert.equal(output.toString(), foobarString);406407 await finishedStream(stream);407 await assertSubprocessOutput(t, subprocess);408 await assertSubprocessOutput(subprocess);409};410410test('.readable() can be paused', async t => {411test('.readable() can be paused', async () => {412 const subprocess = getReadableSubprocess();413 const stream = subprocess.readable();414414 await assertPause(t, stream, subprocess);415 await assertPause(stream, subprocess);416});417417test('.duplex() can be paused', async t => {418test('.duplex() can be paused', async () => {419 const subprocess = getReadWriteSubprocess();420 const stream = subprocess.duplex();421 stream.end(foobarString);422422 await assertPause(t, stream, subprocess);423 await assertPause(stream, subprocess);424});425426// This feature does not work on Node 18.427// @todo: remove after dropping support for Node 18.428if (majorNodeVersion >= 20) {428 const testHighWaterMark = async (t, methodName) => {429 const testHighWaterMark = async methodName => {430 const subprocess = execa('stdin.js');431 const stream = subprocess[methodName]();432433 let count = 0;
5 unmodified lines
439 }440441 const expectedCount = defaultObjectHighWaterMark + 1;442 const expectedOutput = '.'.repeat(expectedCount);442 t.is(count, expectedCount);443 assert.equal(count, expectedCount);444 subprocess.stdin.end();444 await assertStreamOutput(t, stream, expectedOutput);445 await assertSubprocessOutput(t, subprocess, expectedOutput);445 await assertStreamOutput(stream, expectedOutput);446 await assertSubprocessOutput(subprocess, expectedOutput);447 };448448 test('.readable() pauses its buffering when too high', testHighWaterMark, 'readable');449 test('.duplex() pauses its buffering when too high', testHighWaterMark, 'duplex');449 test('.readable() pauses its buffering when too high', () => testHighWaterMark('readable'));450 test('.duplex() pauses its buffering when too high', () => testHighWaterMark('duplex'));451}452452const testBigOutput = async (t, methodName) => {453const testBigOutput = async methodName => {454 const bigChunk = '.'.repeat(1e6);455 const subprocess = execa('stdin.js', {input: bigChunk});456 const stream = subprocess[methodName]();457457 await assertStreamOutput(t, stream, bigChunk);458 await assertSubprocessOutput(t, subprocess, bigChunk);458 await assertStreamOutput(stream, bigChunk);459 await assertSubprocessOutput(subprocess, bigChunk);460};461461test('.readable() with big output', testBigOutput, 'readable');462test('.duplex() with big output', testBigOutput, 'duplex');462test('.readable() with big output', () => testBigOutput('readable'));463test('.duplex() with big output', () => testBigOutput('duplex'));
modified:test/convert/shared.js+37 added-21 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects, assertThrows} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {7 finishedStream,
5 unmodified lines
13import {foobarString} from '../helpers/input.js';1415setFixtureDirectory();1615const testSubprocessFail = async (t, methodName) => {17const testSubprocessFail = async methodName => {18 const subprocess = getReadWriteSubprocess();19 const stream = subprocess[methodName]();2021 const cause = new Error(foobarString);22 subprocess.kill(cause);2322 const error = await assertStreamError(t, stream, {cause});23 assertWritableAborted(t, subprocess.stdin);24 t.true(subprocess.stdout.readableEnded);25 t.true(subprocess.stderr.readableEnded);24 const error = await assertStreamError(stream, {cause});25 assertWritableAborted(subprocess.stdin);26 assert.equal(subprocess.stdout.readableEnded, true);27 assert.equal(subprocess.stderr.readableEnded, true);2827 await assertSubprocessError(t, subprocess, error);29 await assertSubprocessError(subprocess, error);30};3130test('subprocess fail -> .readable() error', testSubprocessFail, 'readable');31test('subprocess fail -> .writable() error', testSubprocessFail, 'writable');32test('subprocess fail -> .duplex() error', testSubprocessFail, 'duplex');32test('subprocess fail -> .readable() error', () => testSubprocessFail('readable'));33test('subprocess fail -> .writable() error', () => testSubprocessFail('writable'));34test('subprocess fail -> .duplex() error', () => testSubprocessFail('duplex'));3534const testErrorEvent = async (t, methodName) => {36const testErrorEvent = async methodName => {37 const subprocess = execa('empty.js');38 const stream = subprocess[methodName]();37 t.is(stream.listenerCount('error'), 0);39 assert.equal(stream.listenerCount('error'), 0);40 stream.destroy();39 await t.throwsAsync(finishedStream(stream));41 await assertRejects(finishedStream(stream));42};4342test('.readable() requires listening to "error" event', testErrorEvent, 'readable');43test('.writable() requires listening to "error" event', testErrorEvent, 'writable');44test('.duplex() requires listening to "error" event', testErrorEvent, 'duplex');44test('.readable() requires listening to "error" event', () => testErrorEvent('readable'));45test('.writable() requires listening to "error" event', () => testErrorEvent('writable'));46test('.duplex() requires listening to "error" event', () => testErrorEvent('duplex'));4746const testSubprocessError = async (t, methodName) => {48const testSubprocessError = async methodName => {49 const subprocess = getReadWriteSubprocess();50 const stream = subprocess[methodName]();51 const cause = new Error(foobarString);52 subprocess.kill(cause);51 await assertStreamError(t, stream, {cause});53 await assertStreamError(stream, {cause});54};5554test('Do not need to await subprocess with .readable()', testSubprocessError, 'readable');55test('Do not need to await subprocess with .writable()', testSubprocessError, 'writable');56test('Do not need to await subprocess with .duplex()', testSubprocessError, 'duplex');56test('Do not need to await subprocess with .readable()', () => testSubprocessError('readable'));57test('Do not need to await subprocess with .writable()', () => testSubprocessError('writable'));58test('Do not need to await subprocess with .duplex()', () => testSubprocessError('duplex'));5960const testNullOptions = async methodName => {61 const subprocess = getReadWriteSubprocess();62 subprocess.stdin.end();63 assertThrows(() => {64 subprocess[methodName](null);65 }, {message: 'The options must be an object, not `null`.'});66 await subprocess;67};6869test('.readable() cannot use null options', () => testNullOptions('readable'));70test('.writable() cannot use null options', () => testNullOptions('writable'));71test('.duplex() cannot use null options', () => testNullOptions('duplex'));72test('.iterable() cannot use null options', () => testNullOptions('iterable'));
modified:test/convert/web.js+27 added-26 removed
1import assert from 'node:assert/strict';2import {ReadableStream, WritableStream} from 'node:stream/web';2import test from 'ava';3import test from 'node:test';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {7 assertStreamOutput,
14 unmodified lines
22 await writer.write(new TextEncoder().encode(input));23 await writer.close();24};2525test('.readableStream() success', async t => {26test('.readableStream() success', async () => {27 const subprocess = getReadableSubprocess();28 const stream = subprocess.readableStream();2929 t.true(stream instanceof ReadableStream);30 assert.ok(stream instanceof ReadableStream);3131 await assertStreamOutput(t, stream);32 await assertSubprocessOutput(t, subprocess);32 await assertStreamOutput(stream);33 await assertSubprocessOutput(subprocess);34});3535test('.readableStream() can use from', async t => {36test('.readableStream() can use from', async () => {37 const subprocess = execa('noop-fd.js', ['2', foobarString]);38 const stream = subprocess.readableStream({from: 'stderr'});3939 await assertStreamOutput(t, stream);40 await assertStreamOutput(stream);41});4242test('.writableStream() success', async t => {43test('.writableStream() success', async () => {44 const subprocess = getWritableSubprocess();45 const stream = subprocess.writableStream();4646 t.true(stream instanceof WritableStream);47 assert.ok(stream instanceof WritableStream);4849 await writeToStream(stream);49 await assertSubprocessOutput(t, subprocess, foobarString, 2);50 await assertSubprocessOutput(subprocess, foobarString, 2);51});5252test('.writableStream() can use to', async t => {53test('.writableStream() can use to', async () => {54 const subprocess = execa('stdin-fd.js', ['0']);55 const stream = subprocess.writableStream({to: 'stdin'});5657 await writeToStream(stream);57 await assertSubprocessOutput(t, subprocess);58 await assertSubprocessOutput(subprocess);59});6060test('.transformStream() success', async t => {61test('.transformStream() success', async () => {62 const subprocess = getReadWriteSubprocess();63 const {readable, writable} = subprocess.transformStream();6464 t.true(readable instanceof ReadableStream);65 t.true(writable instanceof WritableStream);65 assert.ok(readable instanceof ReadableStream);66 assert.ok(writable instanceof WritableStream);6768 await writeToStream(writable);68 await assertStreamOutput(t, readable);69 await assertSubprocessOutput(t, subprocess);69 await assertStreamOutput(readable);70 await assertSubprocessOutput(subprocess);71});7272test('subprocess fail -> .readableStream() error', async t => {73test('subprocess fail -> .readableStream() error', async () => {74 const subprocess = getReadWriteSubprocess();75 const stream = subprocess.readableStream();7677 const cause = new Error(foobarString);78 subprocess.kill(cause);7979 await assertStreamReadError(t, stream, {cause});80 await assertSubprocessError(t, subprocess, {cause});80 await assertStreamReadError(stream, {cause});81 await assertSubprocessError(subprocess, {cause});82});8383test('subprocess fail -> .writableStream() error', async t => {84test('subprocess fail -> .writableStream() error', async () => {85 const subprocess = getReadWriteSubprocess();86 const stream = subprocess.writableStream();87 const writer = stream.getWriter();8889 const cause = new Error(foobarString);90 subprocess.kill(cause);9191 await assertPromiseError(t, writer.closed, {cause});92 await assertSubprocessError(t, subprocess, {cause});92 await assertPromiseError(writer.closed, {cause});93 await assertSubprocessError(subprocess, {cause});94});9595test('subprocess fail -> .transformStream() error', async t => {96test('subprocess fail -> .transformStream() error', async () => {97 const subprocess = getReadWriteSubprocess();98 const {readable} = subprocess.transformStream();99100 const cause = new Error(foobarString);101 subprocess.kill(cause);102102 await assertStreamReadError(t, readable, {cause});103 await assertSubprocessError(t, subprocess, {cause});103 await assertStreamReadError(readable, {cause});104 await assertSubprocessError(subprocess, {cause});105});
modified:test/convert/writable.js+148 added-146 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {compose, Readable, Writable} from 'node:stream';4import {pipeline} from 'node:stream/promises';5import {text} from 'node:stream/consumers';6import {setTimeout, scheduler} from 'node:timers/promises';7import {promisify} from 'node:util';7import test from 'ava';8import test from 'node:test';9import {assertRejects, assertLike} from '../helpers/assert.js';10import {execa} from '../../index.js';11import {setFixtureDirectory} from '../helpers/fixtures-directory.js';12import {13 finishedStream,
23 unmodified lines
37import {defaultHighWaterMark, defaultObjectHighWaterMark} from '../helpers/stream.js';3839setFixtureDirectory();4039test('.writable() success', async t => {41test('.writable() success', async () => {42 const subprocess = getWritableSubprocess();43 const stream = subprocess.writable();4443 t.true(stream instanceof Writable);44 t.true(stream.writable);45 t.false(stream instanceof Readable);46 t.is(stream.readable, undefined);45 assert.ok(stream instanceof Writable);46 assert.equal(stream.writable, true);47 assert.ok(!(stream instanceof Readable));48 assert.equal(stream.readable, undefined);4950 stream.end(foobarString);5152 await finishedStream(stream);51 await assertSubprocessOutput(t, subprocess, foobarString, 2);53 await assertSubprocessOutput(subprocess, foobarString, 2);54});5554const testWritableDefault = async (t, fdNumber, to, options) => {56const testWritableDefault = async (fdNumber, to, options) => {57 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], options);58 const stream = subprocess.writable({to});5960 stream.end(foobarString);6162 await finishedStream(stream);61 await assertSubprocessOutput(t, subprocess);63 await assertSubprocessOutput(subprocess);64};6564test('.writable() can use stdin', testWritableDefault, 0, 'stdin', {});65test('.writable() can use stdio[*]', testWritableDefault, 3, 'fd3', fullReadableStdio());66test('.writable() can use stdio[*] with { value: "pipe", input: true }', testWritableDefault, 3, 'fd3', getStdio(3, {value: 'pipe', input: true}));67test('.writable() can use stdio[*] with [{ value: "pipe", input: true }, "pipe"]', testWritableDefault, 3, 'fd3', getStdio(3, [{value: 'pipe', input: true}, 'pipe']));68test('.writable() uses stdin by default', testWritableDefault, 0, undefined, {});66test('.writable() can use stdin', () => testWritableDefault(0, 'stdin', {}));67test('.writable() can use stdio[*]', () => testWritableDefault(3, 'fd3', fullReadableStdio()));68test('.writable() can use stdio[*] with { value: "pipe", input: true }', () => testWritableDefault(3, 'fd3', getStdio(3, {value: 'pipe', input: true})));69test('.writable() can use stdio[*] with [{ value: "pipe", input: true }, "pipe"]', () => testWritableDefault(3, 'fd3', getStdio(3, [{value: 'pipe', input: true}, 'pipe'])));70test('.writable() uses stdin by default', () => testWritableDefault(0, undefined, {}));7170test('.writable() hangs until ended', async t => {72test('.writable() hangs until ended', async () => {73 const subprocess = getReadWriteSubprocess();74 const stream = subprocess.writable();7576 stream.write(foobarString);77 await setTimeout(1e2);78 stream.end();7980 await finishedStream(stream);79 await assertSubprocessOutput(t, subprocess);81 await assertSubprocessOutput(subprocess);82});8382test('.duplex() hangs until ended', async t => {84test('.duplex() hangs until ended', async () => {85 const subprocess = getReadWriteSubprocess();86 const stream = subprocess.duplex();8788 stream.write(foobarString);89 await setTimeout(1e2);90 stream.end();9190 await assertStreamOutput(t, stream);91 await assertSubprocessOutput(t, subprocess);92 await assertStreamOutput(stream);93 await assertSubprocessOutput(subprocess);94});9594const testEarlySuccess = async (t, methodName, hasWrites) => {96const testEarlySuccess = async (methodName, hasWrites) => {97 const subprocess = hasWrites ? getReadableSubprocess() : execa('empty.js');98 const stream = subprocess[methodName]();9998 const error = await t.throwsAsync(finishedStream(stream));99 t.like(error, prematureClose);100 assertWritableAborted(t, subprocess.stdin);101 t.true(subprocess.stdout.readableEnded);102 t.true(subprocess.stderr.readableEnded);103 await assertSubprocessOutput(t, subprocess, hasWrites ? foobarString : '');100 const error = await assertRejects(finishedStream(stream));101 assertLike(error, prematureClose);102 assertWritableAborted(subprocess.stdin);103 assert.equal(subprocess.stdout.readableEnded, true);104 assert.equal(subprocess.stderr.readableEnded, true);105 await assertSubprocessOutput(subprocess, hasWrites ? foobarString : '');106};107106test('subprocess early success with no writes -> .writable() abort', testEarlySuccess, 'writable', false);107test('subprocess early success with no writes -> .duplex() abort', testEarlySuccess, 'duplex', false);108test('subprocess early success with writes -> .writable() abort', testEarlySuccess, 'writable', true);109test('subprocess early success with writes -> .duplex() abort', testEarlySuccess, 'duplex', true);108test('subprocess early success with no writes -> .writable() abort', () => testEarlySuccess('writable', false));109test('subprocess early success with no writes -> .duplex() abort', () => testEarlySuccess('duplex', false));110test('subprocess early success with writes -> .writable() abort', () => testEarlySuccess('writable', true));111test('subprocess early success with writes -> .duplex() abort', () => testEarlySuccess('duplex', true));112111test('.writable() abort -> subprocess fail', async t => {113test('.writable() abort -> subprocess fail', async () => {114 const subprocess = getWritableSubprocess();115 const stream = subprocess.writable();116117 stream.destroy();118117 const error = await t.throwsAsync(finishedStream(stream));118 t.like(error, prematureClose);119 assertProcessNormalExit(t, error);120 assertWritableAborted(t, subprocess.stdin);121 t.true(subprocess.stdout.readableEnded);122 t.true(subprocess.stderr.readableEnded);123 await assertSubprocessError(t, subprocess, error);119 const error = await assertRejects(finishedStream(stream));120 assertLike(error, prematureClose);121 assertProcessNormalExit(error);122 assertWritableAborted(subprocess.stdin);123 assert.equal(subprocess.stdout.readableEnded, true);124 assert.equal(subprocess.stderr.readableEnded, true);125 await assertSubprocessError(subprocess, error);126});127126test('.writable() error -> subprocess fail', async t => {128test('.writable() error -> subprocess fail', async () => {129 const subprocess = getWritableSubprocess();130 const stream = subprocess.writable();131132 const cause = new Error(foobarString);133 stream.destroy(cause);134133 const error = await assertStreamError(t, stream, {cause});134 assertProcessNormalExit(t, error);135 t.is(subprocess.stdin.errored, cause);136 t.true(subprocess.stdout.readableEnded);137 t.true(subprocess.stderr.readableEnded);138 await assertSubprocessError(t, subprocess, error);135 const error = await assertStreamError(stream, {cause});136 assertProcessNormalExit(error);137 assert.equal(subprocess.stdin.errored, cause);138 assert.equal(subprocess.stdout.readableEnded, true);139 assert.equal(subprocess.stderr.readableEnded, true);140 await assertSubprocessError(subprocess, error);141});142141test('.writable() EPIPE error -> subprocess success', async t => {143test('.writable() EPIPE error -> subprocess success', async () => {144 const subprocess = getWritableSubprocess();145 const stream = subprocess.writable();146147 const error = new Error(foobarString);148 error.code = 'EPIPE';149 stream.destroy(error);150149 await assertStreamError(t, stream, error);150 t.is(subprocess.stdin.errored, error);151 t.true(subprocess.stdout.readableEnded);152 t.true(subprocess.stderr.readableEnded);151 await assertStreamError(stream, error);152 assert.equal(subprocess.stdin.errored, error);153 assert.equal(subprocess.stdout.readableEnded, true);154 assert.equal(subprocess.stderr.readableEnded, true);155 await subprocess;156});157156test('subprocess.stdin end -> .writable() end + subprocess success', async t => {158test('subprocess.stdin end -> .writable() end + subprocess success', async () => {159 const subprocess = getReadWriteSubprocess();160 const stream = subprocess.writable();161162 subprocess.stdin.end(foobarString);163164 await finishedStream(stream);163 await assertSubprocessOutput(t, subprocess);165 await assertSubprocessOutput(subprocess);166});167166test('subprocess.stdin end -> .duplex() end + subprocess success', async t => {168test('subprocess.stdin end -> .duplex() end + subprocess success', async () => {169 const subprocess = getReadWriteSubprocess();170 const stream = subprocess.duplex();171172 subprocess.stdin.end(foobarString);173172 await assertStreamOutput(t, stream);173 await assertSubprocessOutput(t, subprocess);174 await assertStreamOutput(stream);175 await assertSubprocessOutput(subprocess);176});177176const testStdinAbort = async (t, methodName) => {178const testStdinAbort = async methodName => {179 const subprocess = getReadWriteSubprocess();180 const stream = subprocess[methodName]();181182 subprocess.stdin.destroy();183182 const error = await t.throwsAsync(finishedStream(stream));183 t.like(error, prematureClose);184 assertWritableAborted(t, subprocess.stdin);185 t.true(subprocess.stdout.readableEnded);186 t.true(subprocess.stderr.readableEnded);187 const subprocessError = await t.throwsAsync(subprocess);188 t.like(subprocessError, prematureClose);189 t.like(subprocessError.cause, prematureClose);190 assertProcessNormalExit(t, subprocessError);184 const error = await assertRejects(finishedStream(stream));185 assertLike(error, prematureClose);186 assertWritableAborted(subprocess.stdin);187 assert.equal(subprocess.stdout.readableEnded, true);188 assert.equal(subprocess.stderr.readableEnded, true);189 const subprocessError = await assertRejects(subprocess);190 assertLike(subprocessError, prematureClose);191 assertLike(subprocessError.cause, prematureClose);192 assertProcessNormalExit(subprocessError);193};194193test('subprocess.stdin abort -> .writable() error + subprocess fail', testStdinAbort, 'writable');194test('subprocess.stdin abort -> .duplex() error + subprocess fail', testStdinAbort, 'duplex');195test('subprocess.stdin abort -> .writable() error + subprocess fail', () => testStdinAbort('writable'));196test('subprocess.stdin abort -> .duplex() error + subprocess fail', () => testStdinAbort('duplex'));197196const testStdinError = async (t, methodName) => {198const testStdinError = async methodName => {199 const subprocess = getReadWriteSubprocess();200 const stream = subprocess[methodName]();201202 const cause = new Error(foobarString);203 subprocess.stdin.destroy(cause);204203 const error = await assertStreamError(t, stream, {cause});204 assertProcessNormalExit(t, error);205 t.is(subprocess.stdin.errored, cause);206 t.true(subprocess.stderr.readableEnded);207 t.true(subprocess.stdout.readableEnded);208 await assertSubprocessError(t, subprocess, error);205 const error = await assertStreamError(stream, {cause});206 assertProcessNormalExit(error);207 assert.equal(subprocess.stdin.errored, cause);208 assert.equal(subprocess.stderr.readableEnded, true);209 assert.equal(subprocess.stdout.readableEnded, true);210 await assertSubprocessError(subprocess, error);211};212211test('subprocess.stdin error -> .writable() error + subprocess fail', testStdinError, 'writable');212test('subprocess.stdin error -> .duplex() error + subprocess fail', testStdinError, 'duplex');213test('subprocess.stdin error -> .writable() error + subprocess fail', () => testStdinError('writable'));214test('subprocess.stdin error -> .duplex() error + subprocess fail', () => testStdinError('duplex'));215214test('.writable() can be used with Stream.pipeline()', async t => {216test('.writable() can be used with Stream.pipeline()', async () => {217 const subprocess = getWritableSubprocess();218 const inputStream = Readable.from([foobarString]);219 const stream = subprocess.writable();220221 await pipeline(inputStream, stream);222223 await finishedStream(inputStream);224 await finishedStream(stream);223 await assertSubprocessOutput(t, subprocess, foobarString, 2);225 await assertSubprocessOutput(subprocess, foobarString, 2);226});227226test('.writable() can error with Stream.pipeline()', async t => {228test('.writable() can error with Stream.pipeline()', async () => {229 const subprocess = execa('noop-stdin-fail.js', ['2']);230 const inputStream = Readable.from([foobarString]);231 const stream = subprocess.writable();232231 const error = await t.throwsAsync(pipeline(inputStream, stream));232 assertProcessNormalExit(t, error, 2);233 t.is(error.stderr, foobarString);233 const error = await assertRejects(pipeline(inputStream, stream));234 assertProcessNormalExit(error, 2);235 assert.equal(error.stderr, foobarString);236237 await finishedStream(inputStream);236 await assertStreamError(t, stream, error);237 await assertSubprocessError(t, subprocess, error);238 await assertStreamError(stream, error);239 await assertSubprocessError(subprocess, error);240});241240test('.writable() can pipe to errored stream with Stream.pipeline()', async t => {242test('.writable() can pipe to errored stream with Stream.pipeline()', async () => {243 const subprocess = getWritableSubprocess();244 const inputStream = Readable.from([foobarString]);245 const stream = subprocess.writable();246247 const cause = new Error('test');248 inputStream.destroy(cause);249248 await assertPromiseError(t, pipeline(inputStream, stream), cause);249 await t.throwsAsync(finishedStream(stream));250 await assertPromiseError(pipeline(inputStream, stream), cause);251 await assertRejects(finishedStream(stream));252251 await assertStreamError(t, inputStream, cause);252 const error = await assertStreamError(t, stream, cause);253 await assertSubprocessError(t, subprocess, {cause: error});253 await assertStreamError(inputStream, cause);254 const error = await assertStreamError(stream, cause);255 await assertSubprocessError(subprocess, {cause: error});256});257256test('.writable() can be used with Stream.compose()', async t => {258test('.writable() can be used with Stream.compose()', async () => {259 const subprocess = getWritableSubprocess();260 const inputStream = Readable.from([foobarString]);261 const stream = subprocess.writable();262263 await finishedStream(compose(inputStream, stream));262 await assertSubprocessOutput(t, subprocess, foobarString, 2);264 await assertSubprocessOutput(subprocess, foobarString, 2);265});266265test('.writable() works with objectMode', async t => {267test('.writable() works with objectMode', async () => {268 const subprocess = getReadWriteSubprocess({stdin: serializeGenerator(true, true)});269 const stream = subprocess.writable();268 t.true(stream.writableObjectMode);269 t.is(stream.writableHighWaterMark, defaultObjectHighWaterMark);270 assert.equal(stream.writableObjectMode, true);271 assert.equal(stream.writableHighWaterMark, defaultObjectHighWaterMark);272 stream.end(foobarObject);273274 await finishedStream(stream);273 await assertSubprocessOutput(t, subprocess, foobarObjectString);275 await assertSubprocessOutput(subprocess, foobarObjectString);276});277276test('.duplex() works with objectMode and writes', async t => {278test('.duplex() works with objectMode and writes', async () => {279 const subprocess = getReadWriteSubprocess({stdin: serializeGenerator(true, true)});280 const stream = subprocess.duplex();279 t.false(stream.readableObjectMode);280 t.is(stream.readableHighWaterMark, defaultHighWaterMark);281 t.true(stream.writableObjectMode);282 t.is(stream.writableHighWaterMark, defaultObjectHighWaterMark);281 assert.equal(stream.readableObjectMode, false);282 assert.equal(stream.readableHighWaterMark, defaultHighWaterMark);283 assert.equal(stream.writableObjectMode, true);284 assert.equal(stream.writableHighWaterMark, defaultObjectHighWaterMark);285 stream.end(foobarObject);286285 await assertStreamOutput(t, stream, foobarObjectString);286 await assertSubprocessOutput(t, subprocess, foobarObjectString);287 await assertStreamOutput(stream, foobarObjectString);288 await assertSubprocessOutput(subprocess, foobarObjectString);289});290289test('.writable() has the right highWaterMark', async t => {291test('.writable() has the right highWaterMark', async () => {292 const subprocess = getReadWriteSubprocess();293 const stream = subprocess.writable();292 t.is(stream.writableHighWaterMark, defaultHighWaterMark);294 assert.equal(stream.writableHighWaterMark, defaultHighWaterMark);295 stream.end();296 await finishedStream(stream);297});298297const writeUntilFull = async (t, stream, subprocess) => {299const writeUntilFull = async (stream, subprocess) => {300 const size = stream.writableHighWaterMark / 2;301 const chunk = '.'.repeat(size);302301 t.is(subprocess.stdin.writableLength, 0);302 t.is(stream.writableLength, 0);303 t.false(subprocess.stdin.writableNeedDrain);304 t.false(stream.writableNeedDrain);303 assert.equal(subprocess.stdin.writableLength, 0);304 assert.equal(stream.writableLength, 0);305 assert.equal(subprocess.stdin.writableNeedDrain, false);306 assert.equal(stream.writableNeedDrain, false);307306 t.true(stream.write(chunk));307 t.is(subprocess.stdin.writableLength, size);308 t.is(stream.writableLength, 0);309 t.false(subprocess.stdin.writableNeedDrain);310 t.false(stream.writableNeedDrain);308 assert.ok(stream.write(chunk));309 assert.equal(subprocess.stdin.writableLength, size);310 assert.equal(stream.writableLength, 0);311 assert.equal(subprocess.stdin.writableNeedDrain, false);312 assert.equal(stream.writableNeedDrain, false);313312 t.true(stream.write(chunk));313 t.is(subprocess.stdin.writableLength, size * 2);314 t.is(stream.writableLength, size);315 t.true(subprocess.stdin.writableNeedDrain);316 t.false(stream.writableNeedDrain);314 assert.ok(stream.write(chunk));315 assert.equal(subprocess.stdin.writableLength, size * 2);316 assert.equal(stream.writableLength, size);317 assert.equal(subprocess.stdin.writableNeedDrain, true);318 assert.equal(stream.writableNeedDrain, false);319318 t.false(stream.write(chunk));319 t.is(subprocess.stdin.writableLength, size * 2);320 t.is(stream.writableLength, size * 2);321 t.true(subprocess.stdin.writableNeedDrain);322 t.true(stream.writableNeedDrain);320 assert.ok(!stream.write(chunk));321 assert.equal(subprocess.stdin.writableLength, size * 2);322 assert.equal(stream.writableLength, size * 2);323 assert.equal(subprocess.stdin.writableNeedDrain, true);324 assert.equal(stream.writableNeedDrain, true);325326 await once(stream, 'drain');327 stream.end();328329 return '.'.repeat(size * 3);330};331330test('.writable() waits when its buffer is full', async t => {332test('.writable() waits when its buffer is full', async () => {333 const subprocess = getReadWriteSubprocess({stdin: noopAsyncGenerator(false, true)});334 const stream = subprocess.writable();335334 const expectedOutput = await writeUntilFull(t, stream, subprocess);336 const expectedOutput = await writeUntilFull(stream, subprocess);337336 await assertSubprocessOutput(t, subprocess, expectedOutput);338 await assertSubprocessOutput(subprocess, expectedOutput);339});340339test('.duplex() waits when its buffer is full', async t => {341test('.duplex() waits when its buffer is full', async () => {342 const subprocess = getReadWriteSubprocess({stdin: noopAsyncGenerator(false, true)});343 const stream = subprocess.duplex();344343 const expectedOutput = await writeUntilFull(t, stream, subprocess);345 const expectedOutput = await writeUntilFull(stream, subprocess);346345 await assertStreamOutput(t, stream, expectedOutput);346 await assertSubprocessOutput(t, subprocess, expectedOutput);347 await assertStreamOutput(stream, expectedOutput);348 await assertSubprocessOutput(subprocess, expectedOutput);349});350349const testPropagateError = async (t, methodName) => {351const testPropagateError = async methodName => {352 const cause = new Error(foobarString);353 const subprocess = getReadWriteSubprocess({stdin: throwingGenerator(cause)()});354 const stream = subprocess[methodName]();355 stream.end('.');354 await assertStreamError(t, stream, {cause});356 await assertStreamError(stream, {cause});357};358357test('.writable() propagates write errors', testPropagateError, 'writable');358test('.duplex() propagates write errors', testPropagateError, 'duplex');359test('.writable() propagates write errors', () => testPropagateError('writable'));360test('.duplex() propagates write errors', () => testPropagateError('duplex'));361360const testWritev = async (t, methodName, waitForStream) => {362const testWritev = async (methodName, waitForStream) => {363 const subprocess = getReadWriteSubprocess({stdin: noopAsyncGenerator()});364 const stream = subprocess[methodName]();365366 const chunk = '.'.repeat(stream.writableHighWaterMark);367 stream.write(chunk);366 t.true(stream.writableNeedDrain);368 assert.equal(stream.writableNeedDrain, true);369370 const [writeInOneTick] = await Promise.race([371 Promise.all([true, promisify(stream.write.bind(stream))(chunk)]),372 Promise.all([false, scheduler.yield()]),373 ]);372 t.true(writeInOneTick);374 assert.equal(writeInOneTick, true);375376 stream.end();377 await waitForStream(stream);378};379378test('.writable() can use .writev()', testWritev, 'writable', finishedStream);379test('.duplex() can use .writev()', testWritev, 'duplex', text);380test('.writable() can use .writev()', () => testWritev('writable', finishedStream));381test('.duplex() can use .writev()', () => testWritev('duplex', text));382381test('.writable() can set encoding', async t => {383test('.writable() can set encoding', async () => {384 const subprocess = getReadWriteSubprocess();385 const stream = subprocess.writable();386387 stream.end(foobarBuffer.toString('hex'), 'hex');388389 await finishedStream(stream);388 await assertSubprocessOutput(t, subprocess);390 await assertSubprocessOutput(subprocess);391});392391test('.duplex() can set encoding', async t => {393test('.duplex() can set encoding', async () => {394 const subprocess = getReadWriteSubprocess();395 const stream = subprocess.duplex();396397 stream.end(foobarBuffer.toString('hex'), 'hex');398397 await assertStreamOutput(t, stream);398 await assertSubprocessOutput(t, subprocess);399 await assertStreamOutput(stream);400 await assertSubprocessOutput(subprocess);401});
modified:test/fixtures/graceful-none-twice.js+2 added
1 unmodified line
2import process from 'node:process';3import {getCancelSignal} from 'execa';45// Each call must throw the same error, including when the first one is caught and retried6// The calls are sequential on purpose, so the second one is retried after the first one was caught7for (let index = 0; index < 2; index++) {8 try {9 // eslint-disable-next-line no-await-in-loop -- the second call is retried only after the first one was caught10 await getCancelSignal();11 } catch {12 process.stdout.write('threw\n');13 }
1 unmodified line
added:test/fixtures/ipc-send-strict-forged.js+8 added
1#!/usr/bin/env node2import {sendMessage} from '../../index.js';34// Forged `strict` acknowledgment responses, for messages which were sent to another subprocess5for (let id = 0; id < 1e3; id += 1) {6 // eslint-disable-next-line no-await-in-loop7 await sendMessage({type: 'execa:ipc:response', id, message: true});8}
modified:test/fixtures/nested-input-inherit.js+1 added-4 removed
6 unmodified lines
7const execaMethod = isSyncString === 'true' ? execaSync : execa;8const options = {9 input: foobarString,10 [optionName]: JSON.parse(stdioOptionString),11 ...((optionName === 'stdin') && {stdout: 'inherit'}),12};1313if (optionName === 'stdin') {14 options.stdout = 'inherit';15}1614await execaMethod('stdin.js', options);
added:test/fixtures/nested-pipe-all-stream.js+8 added
1#!/usr/bin/env node2import process from 'node:process';3import {execa, getOneMessage} from '../../index.js';45const {file, commandArguments, options} = await getOneMessage();6const subprocess = execa(file, commandArguments, {...options, all: true});7subprocess.all.pipe(process.stdout);8await subprocess;
modified:test/fixtures/noop-fd-large.js+1 added
1#!/usr/bin/env node2import {Buffer} from 'node:buffer';3import process from 'node:process';4import {getWriteStream} from '../helpers/fs.js';56const fdNumber = Number(process.argv[2]);7const bytes = Number(process.argv[3]);
1 unmodified line
added:test/helpers/assert.js+70 added
1import assert from 'node:assert/strict';2import isPlainObject from 'is-plain-obj';34/*5`t.throws()` and `t.throwsAsync()` returned the thrown error, which most tests assert on.6`assert.throws()` and `assert.rejects()` do not, so the error is captured with their validation function instead.7*/89const checkExpectation = (error, expectation) => {10 if (expectation === undefined) {11 return;12 }1314 // A constructor or a RegExp has no own properties to compare, so it would always pass15 if (!isPlainObject(expectation)) {16 throw new TypeError('The expectation must be a plain object like `{message}` or `{instanceOf}`.');17 }1819 // `assert.throws()` compares every own property of the expectation against the error, but it does not20 // know about `instanceOf`, which AVA validated. It is therefore checked separately.21 const {instanceOf, ...properties} = expectation;22 if (instanceOf !== undefined) {23 assert.ok(error instanceof instanceOf, `The error is not an instance of ${instanceOf.name}`);24 }2526 if (Object.keys(properties).length > 0) {27 // Rethrowing checks the expectation with the same `message`, `code` and constructor logic.28 assert.throws(() => {29 throw error;30 }, properties);31 }32};3334export const assertThrows = (synchronousFunction, expectation) => {35 let error;36 assert.throws(synchronousFunction, thrownError => {37 error = thrownError;38 return true;39 });4041 checkExpectation(error, expectation);42 return error;43};4445export const assertRejects = async (promise, expectation) => {46 let error;47 await assert.rejects(promise, thrownError => {48 error = thrownError;49 return true;50 });5152 checkExpectation(error, expectation);53 return error;54};5556/*57Like `t.like()`, this compares a subset of the properties of an object, whatever its prototype. Nested plain objects are compared the same way, unless they are empty. Any other value must be deeply equal, including arrays, which is stricter than `t.like()`.58`assert.partialDeepStrictEqual()` is not used: it requires the prototype to be the same, which never holds when the value is an error, and an empty array matches any array.59The properties are read directly, so non-enumerable ones like `error.cause` are included.60*/61export const assertLike = (value, expectedSubset, path = 'value') => {62 for (const [key, expectedValue] of Object.entries(expectedSubset)) {63 const keyPath = `${path}.${key}`;64 if (isPlainObject(expectedValue) && Object.keys(expectedValue).length > 0) {65 assertLike(value[key], expectedValue, keyPath);66 } else {67 assert.deepEqual(value[key], expectedValue, `${keyPath} is not like the expected value`);68 }69 }70};
modified:test/helpers/convert.js+30 added-28 removed
1import {text} from 'node:stream/consumers';2import {finished} from 'node:stream/promises';3import assert from 'node:assert/strict';4import getStream from 'get-stream';5import isPlainObj from 'is-plain-obj';6import {execa} from '../../index.js';7import {assertRejects} from './assert.js';8import {foobarString} from './input.js';910export const arrayFromAsync = async (asyncIterable, lines = []) => {11 for await (const line of asyncIterable) {
4 unmodified lines
16};1718export const finishedStream = stream => finished(stream, {cleanup: true});1918export const assertWritableAborted = (t, writable) => {19 t.false(writable.writableEnded);20 t.is(writable.errored, null);21 t.false(writable.writable);20export const assertWritableAborted = writable => {21 assert.equal(writable.writableEnded, false);22 assert.equal(writable.errored, null);23 assert.equal(writable.writable, false);24};2524export const assertReadableAborted = (t, readable) => {25 t.false(readable.readableEnded);26 t.is(readable.errored, null);27 t.false(readable.readable);26export const assertReadableAborted = readable => {27 assert.equal(readable.readableEnded, false);28 assert.equal(readable.errored, null);29 assert.equal(readable.readable, false);30};3130export const assertProcessNormalExit = (t, error, exitCode = 0) => {31 t.is(error.exitCode, exitCode);32 t.is(error.signal, undefined);32export const assertProcessNormalExit = (error, exitCode = 0) => {33 assert.equal(error.exitCode, exitCode);34 assert.equal(error.signal, undefined);35};3635export const assertStreamOutput = async (t, stream, expectedOutput = foobarString) => {36 t.is(await text(stream), expectedOutput);37export const assertStreamOutput = async (stream, expectedOutput = foobarString) => {38 assert.equal(await text(stream), expectedOutput);39};4039export const assertStreamDataEvents = async (t, stream, expectedOutput = foobarString) => {40 t.is(await getStream(stream), expectedOutput);41export const assertStreamDataEvents = async (stream, expectedOutput = foobarString) => {42 assert.equal(await getStream(stream), expectedOutput);43};4443export const assertIterableChunks = async (t, asyncIterable, expectedChunks) => {44 t.deepEqual(await arrayFromAsync(asyncIterable), expectedChunks);45export const assertIterableChunks = async (asyncIterable, expectedChunks) => {46 assert.deepEqual(await arrayFromAsync(asyncIterable), expectedChunks);47};4847export const assertStreamChunks = async (t, stream, expectedOutput) => {48 t.deepEqual(await stream.toArray(), expectedOutput);49export const assertStreamChunks = async (stream, expectedOutput) => {50 assert.deepEqual(await stream.toArray(), expectedOutput);51};5251export const assertSubprocessOutput = async (t, subprocess, expectedOutput = foobarString, fdNumber = 1) => {53export const assertSubprocessOutput = async (subprocess, expectedOutput = foobarString, fdNumber = 1) => {54 const result = await subprocess;53 t.deepEqual(result.stdio[fdNumber], expectedOutput);55 assert.deepEqual(result.stdio[fdNumber], expectedOutput);56};5756export const assertStreamError = (t, stream, error) => assertPromiseError(t, finishedStream(stream), error);58export const assertStreamError = (stream, error) => assertPromiseError(finishedStream(stream), error);5958export const assertStreamReadError = (t, stream, error) => assertPromiseError(t, text(stream), error);60export const assertStreamReadError = (stream, error) => assertPromiseError(text(stream), error);6160export const assertSubprocessError = (t, subprocess, error) => assertPromiseError(t, subprocess, error);62export const assertSubprocessError = (subprocess, error) => assertPromiseError(subprocess, error);6362export const assertPromiseError = async (t, promise, error) => {63 const thrownError = await t.throwsAsync(promise);64export const assertPromiseError = async (promise, error) => {65 const thrownError = await assertRejects(promise);6667 if (isPlainObj(error) && error.cause !== undefined) {66 t.is(thrownError.cause, error.cause);68 assert.equal(thrownError.cause, error.cause);69 } else {68 t.is(thrownError, error);70 assert.equal(thrownError, error);71 }7273 return thrownError;74};
6 unmodified lines
modified:test/helpers/fs.js+1 added-5 removed
8 unmodified lines
9 if (fdNumber === 1) {10 return process.stdout;11 }1213 if (fdNumber === 2) {14 return process.stderr;15 }1617 return createWriteStream(undefined, {fd: fdNumber});13 return fdNumber === 2 ? process.stderr : createWriteStream(undefined, {fd: fdNumber});14};
modified:test/helpers/listeners.js+3 added-2 removed
1import assert from 'node:assert/strict';2import process from 'node:process';33export const assertMaxListeners = t => {4export const assertMaxListeners = () => {5 let warning;6 const captureWarning = warningArgument => {7 warning = warningArgument;8 };910 process.once('warning', captureWarning);11 return () => {11 t.is(warning, undefined);12 assert.equal(warning, undefined);13 process.removeListener('warning', captureWarning);14 };15};
modified:test/helpers/max-buffer.js+3 added-2 removed
1import assert from 'node:assert/strict';2import {execa, execaSync} from '../../index.js';34export const maxBuffer = 10;55export const assertErrorMessage = (t, shortMessage, {execaMethod = execa, length = maxBuffer, fdNumber = 1, unit = 'characters'} = {}) => {6export const assertErrorMessage = (shortMessage, {execaMethod = execa, length = maxBuffer, fdNumber = 1, unit = 'characters'} = {}) => {7 const expectedUnit = execaMethod === execaSync ? 'bytes' : unit;7 t.true(shortMessage.includes(`${STREAM_NAMES[fdNumber]} was larger than ${length} ${expectedUnit}`));8 assert.ok(shortMessage.includes(`${STREAM_NAMES[fdNumber]} was larger than ${length} ${expectedUnit}`));9};1011const STREAM_NAMES = ['stdin', 'stdout', 'stderr', 'stdio[3]'];
modified:test/helpers/override-promise.js+1 added-1 removed
1// Can't use `test.before`, because `ava` needs `Promise`.1// Can't use `test.before()`, because the test runner itself needs `Promise`.2const nativePromise = Promise;3// eslint-disable-next-line unicorn/no-global-object-property-assignment -- intentionally mocking the global `Promise`4globalThis.Promise = class BrokenPromise {5 then() { // eslint-disable-line unicorn/no-thenable
8 unmodified lines
modified:test/helpers/pipe.js+24 added-21 removed
1export const assertPipeError = async (t, pipePromise, message) => {2 const error = await t.throwsAsync(pipePromise);1import assert from 'node:assert/strict';2import {assertRejects} from './assert.js';34 t.is(error.command, 'source.pipe(destination)');5 t.is(error.escapedCommand, error.command);4export const assertPipeError = async (pipePromise, message) => {5 const error = await assertRejects(pipePromise);67 t.is(typeof error.cwd, 'string');8 t.true(error.failed);9 t.false(error.timedOut);10 t.false(error.isCanceled);11 t.false(error.isTerminated);12 t.is(error.exitCode, undefined);13 t.is(error.signal, undefined);14 t.is(error.signalDescription, undefined);15 t.is(error.stdout, undefined);16 t.is(error.stderr, undefined);17 t.is(error.all, undefined);18 t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));19 t.deepEqual(error.pipedFrom, []);7 assert.equal(error.command, 'source.pipe(destination)');8 assert.equal(error.escapedCommand, error.command);921 t.true(error.shortMessage.includes(`Command failed: ${error.command}`));22 t.true(error.shortMessage.includes(error.originalMessage));23 t.true(error.message.includes(error.shortMessage));10 assert.equal(typeof error.cwd, 'string');11 assert.equal(error.failed, true);12 assert.equal(error.timedOut, false);13 assert.equal(error.isCanceled, false);14 assert.equal(error.isTerminated, false);15 assert.equal(error.exitCode, undefined);16 assert.equal(error.signal, undefined);17 assert.equal(error.signalDescription, undefined);18 assert.equal(error.stdout, undefined);19 assert.equal(error.stderr, undefined);20 assert.equal(error.all, undefined);21 assert.deepEqual(error.stdio, Array.from({length: error.stdio.length}));22 assert.deepEqual(error.pipedFrom, []);2324 assert.ok(error.shortMessage.includes(`Command failed: ${error.command}`));25 assert.ok(error.shortMessage.includes(error.originalMessage));26 assert.ok(error.message.includes(error.shortMessage));2725 t.true(error.originalMessage.includes(message));28 assert.ok(error.originalMessage.includes(message));29};
modified:test/helpers/stdio.js+4 added-7 removed
1import assert from 'node:assert/strict';2import process, {platform} from 'node:process';3import {noopReadable} from './stream.js';45export const identity = value => value;
16 unmodified lines
22export const prematureClose = {code: 'ERR_STREAM_PREMATURE_CLOSE'};2324const isWindows = platform === 'win32';2525export const assertEpipe = (t, stderr, fdNumber = 1) => {26export const assertEpipe = (stderr, fdNumber = 1) => {27 if (fdNumber === 1 && !isWindows) {27 t.true(stderr.includes('EPIPE'));28 assert.ok(stderr.includes('EPIPE'));29 }30};3132export const parseStdioOption = stdioOption => {
1 unmodified line
34 if (typeof optionValue === 'string' && optionValue in process) {35 return process[optionValue];36 }3737 if (Array.isArray(optionValue) && typeof optionValue[0] === 'string' && optionValue[0] in process) {38 return [process[optionValue[0]], ...optionValue.slice(1)];39 }4041 return optionValue;38 return Array.isArray(optionValue) && typeof optionValue[0] === 'string' && optionValue[0] in process ? [process[optionValue[0]], ...optionValue.slice(1)] : optionValue;39};
modified:test/helpers/verbose.js+10 added-9 removed
1import assert from 'node:assert/strict';2import {platform} from 'node:process';3import {stripVTControlCharacters} from 'node:util';4import {replaceSymbols} from 'figures';5import {foobarString} from './input.js';
2 unmodified lines
89const isWindows = platform === 'win32';10export const QUOTE = isWindows ? '"' : '\'';1111export const runErrorSubprocess = async (t, verbose, isSync = false, options = {}) => {12export const runErrorSubprocess = async (verbose, isSync = false, options = {}) => {13 const {expectExitCode = true, ...subprocessOptions} = options;14 const {stderr, nestedResult} = await nestedSubprocess('noop-fail.js', ['1', foobarString], {verbose, isSync, ...subprocessOptions});14 t.true(nestedResult instanceof Error);15 assert.ok(nestedResult instanceof Error);16 if (expectExitCode) {16 t.true(stderr.includes('exit code 2'));17 assert.ok(stderr.includes('exit code 2'));18 }1920 return stderr;21};2222export const runWarningSubprocess = async (t, isSync) => {23export const runWarningSubprocess = async isSync => {24 const {stderr, nestedResult} = await nestedSubprocess('noop-fail.js', ['1', foobarString], {verbose: 'short', reject: false, isSync});24 t.true(nestedResult instanceof Error);25 t.true(stderr.includes('exit code 2'));25 assert.ok(nestedResult instanceof Error);26 assert.ok(stderr.includes('exit code 2'));27 return stderr;28};2929export const runEarlyErrorSubprocess = async (t, isSync) => {30export const runEarlyErrorSubprocess = async isSync => {31 const {stderr, nestedResult} = await nestedSubprocess('noop.js', [foobarString], {verbose: 'short', cwd: true, isSync});31 t.true(nestedResult instanceof Error);32 t.true(nestedResult.message.startsWith('The "cwd" option must'));32 assert.ok(nestedResult instanceof Error);33 assert.ok(nestedResult.message.startsWith('The "cwd" option must'));34 return stderr;35};3637export const runVerboseSubprocess = ({
68 unmodified lines
modified:test/io/input-option.js+64 added-61 removed
1import assert from 'node:assert/strict';2import {Buffer} from 'node:buffer';3import {Writable} from 'node:stream';3import test from 'ava';4import test from 'node:test';5import {assertThrows} from '../helpers/assert.js';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {9 runExeca,
12 unmodified lines
22import {noopGenerator} from '../helpers/generator.js';2324setFixtureDirectory();2524const testInput = async (t, input, execaMethod) => {26const testInput = async (input, execaMethod) => {27 const {stdout} = await execaMethod('stdin.js', {input});26 t.is(stdout, 'foobar');28 assert.equal(stdout, 'foobar');29};3029test('input option can be a String', testInput, 'foobar', runExeca);30test('input option can be a Uint8Array', testInput, foobarUint8Array, runExeca);31test('input option can be a Buffer', testInput, foobarBuffer, runExeca);32test('input option can be a String - sync', testInput, 'foobar', runExecaSync);33test('input option can be a Uint8Array - sync', testInput, foobarUint8Array, runExecaSync);34test('input option can be a Buffer - sync', testInput, foobarBuffer, runExecaSync);35test('input option can be used with $', testInput, 'foobar', runScript);36test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);31test('input option can be a String', () => testInput('foobar', runExeca));32test('input option can be a Uint8Array', () => testInput(foobarUint8Array, runExeca));33test('input option can be a Buffer', () => testInput(foobarBuffer, runExeca));34test('input option can be a String - sync', () => testInput('foobar', runExecaSync));35test('input option can be a Uint8Array - sync', () => testInput(foobarUint8Array, runExecaSync));36test('input option can be a Buffer - sync', () => testInput(foobarBuffer, runExecaSync));37test('input option can be used with $', () => testInput('foobar', runScript));38test('input option can be used with $.sync', () => testInput('foobar', runScriptSync));3938const testInputIgnoresInheritedStdin = async (t, optionName, stdioOption, isSync) => {40const testInputIgnoresInheritedStdin = async (optionName, stdioOption, isSync) => {41 const {stdout} = await execa('nested-input-inherit.js', [optionName, JSON.stringify(stdioOption), `${isSync}`], {input: foobarString});40 t.is(stdout, foobarString);42 assert.equal(stdout, foobarString);43};4443test('input option ignores stdin "inherit"', testInputIgnoresInheritedStdin, 'stdin', 'inherit', false);44test('input option ignores stdin ["inherit"]', testInputIgnoresInheritedStdin, 'stdin', ['inherit'], false);45test('input option ignores stdio "inherit"', testInputIgnoresInheritedStdin, 'stdio', 'inherit', false);46test('input option ignores stdio[0] "inherit"', testInputIgnoresInheritedStdin, 'stdio', ['inherit', 'inherit', 'pipe'], false);47test.serial('input option ignores stdin "inherit" - sync', testInputIgnoresInheritedStdin, 'stdin', 'inherit', true);48test.serial('input option ignores stdin ["inherit"] - sync', testInputIgnoresInheritedStdin, 'stdin', ['inherit'], true);49test.serial('input option ignores stdio "inherit" - sync', testInputIgnoresInheritedStdin, 'stdio', 'inherit', true);50test.serial('input option ignores stdio[0] "inherit" - sync', testInputIgnoresInheritedStdin, 'stdio', ['inherit', 'inherit', 'pipe'], true);45test('input option ignores stdin "inherit"', () => testInputIgnoresInheritedStdin('stdin', 'inherit', false));46test('input option ignores stdin ["inherit"]', () => testInputIgnoresInheritedStdin('stdin', ['inherit'], false));47test('input option ignores stdio "inherit"', () => testInputIgnoresInheritedStdin('stdio', 'inherit', false));48test('input option ignores stdio[0] "inherit"', () => testInputIgnoresInheritedStdin('stdio', ['inherit', 'inherit', 'pipe'], false));49test('input option ignores stdin "inherit" - sync', () => testInputIgnoresInheritedStdin('stdin', 'inherit', true));50test('input option ignores stdin ["inherit"] - sync', () => testInputIgnoresInheritedStdin('stdin', ['inherit'], true));51test('input option ignores stdio "inherit" - sync', () => testInputIgnoresInheritedStdin('stdio', 'inherit', true));52test('input option ignores stdio[0] "inherit" - sync', () => testInputIgnoresInheritedStdin('stdio', ['inherit', 'inherit', 'pipe'], true));5352const testInvalidInput = async (t, input, execaMethod) => {53 t.throws(() => {54const testInvalidInput = async (input, execaMethod) => {55 assertThrows(() => {56 execaMethod('empty.js', {input});57 }, {message: /a string, a Uint8Array/});58};5958test('input option cannot be an ArrayBuffer', testInvalidInput, foobarArrayBuffer, execa);59test('input option cannot be a DataView', testInvalidInput, foobarDataView, execa);60test('input option cannot be a Uint16Array', testInvalidInput, foobarUint16Array, execa);61test('input option cannot be 0', testInvalidInput, 0, execa);62test('input option cannot be false', testInvalidInput, false, execa);63test('input option cannot be null', testInvalidInput, null, execa);64test('input option cannot be a non-Readable stream', testInvalidInput, new Writable(), execa);65test('input option cannot be an ArrayBuffer - sync', testInvalidInput, foobarArrayBuffer, execaSync);66test('input option cannot be a DataView - sync', testInvalidInput, foobarDataView, execaSync);67test('input option cannot be a Uint16Array - sync', testInvalidInput, foobarUint16Array, execaSync);68test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);69test('input option cannot be false - sync', testInvalidInput, false, execaSync);70test('input option cannot be null - sync', testInvalidInput, null, execaSync);71test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);60test('input option cannot be an ArrayBuffer', () => testInvalidInput(foobarArrayBuffer, execa));61test('input option cannot be a DataView', () => testInvalidInput(foobarDataView, execa));62test('input option cannot be a Uint16Array', () => testInvalidInput(foobarUint16Array, execa));63test('input option cannot be 0', () => testInvalidInput(0, execa));64test('input option cannot be false', () => testInvalidInput(false, execa));65test('input option cannot be null', () => testInvalidInput(null, execa));66test('input option cannot be a non-Readable stream', () => testInvalidInput(new Writable(), execa));67test('input option cannot be an ArrayBuffer - sync', () => testInvalidInput(foobarArrayBuffer, execaSync));68test('input option cannot be a DataView - sync', () => testInvalidInput(foobarDataView, execaSync));69test('input option cannot be a Uint16Array - sync', () => testInvalidInput(foobarUint16Array, execaSync));70test('input option cannot be 0 - sync', () => testInvalidInput(0, execaSync));71test('input option cannot be false - sync', () => testInvalidInput(false, execaSync));72test('input option cannot be null - sync', () => testInvalidInput(null, execaSync));73test('input option cannot be a non-Readable stream - sync', () => testInvalidInput(new Writable(), execaSync));7475/*74String input is encoded with the `encoding` option, so it round-trips with subprocesses echoing it back.76The `encoding` option only applies to the output: string input is always encoded with UTF-8, like with a binary encoding.77Since the subprocess echoes its input, its output is those UTF-8 bytes decoded as UTF-16.78This must not depend on whether a `stdin` transform happens to be present.79*/80const nonAsciiString = '🦄🦄';81const getUtf16Output = input => Buffer.from(input).toString('utf16le');8279const testStringEncoding = async (t, options, execaMethod) => {83const testStringEncoding = async (options, execaMethod) => {84 const {stdout} = await execaMethod('stdin.js', {...options, input: nonAsciiString, encoding: 'utf16le'});81 t.is(stdout, nonAsciiString);85 assert.equal(stdout, getUtf16Output(nonAsciiString));86};8784test('input option string is encoded with encoding "utf16le" without transforms', testStringEncoding, {}, execa);85test('input option string is encoded with encoding "utf16le" without transforms - sync', testStringEncoding, {}, execaSync);86test('input option string is encoded with encoding "utf16le" with transforms', testStringEncoding, {stdin: noopGenerator()}, execa);87test('input option string is encoded with encoding "utf16le" with transforms - sync', testStringEncoding, {stdin: noopGenerator()}, execaSync);88test('input option string is encoded with UTF-8 with encoding "utf16le" without transforms', () => testStringEncoding({}, execa));89test('input option string is encoded with UTF-8 with encoding "utf16le" without transforms - sync', () => testStringEncoding({}, execaSync));90test('input option string is encoded with UTF-8 with encoding "utf16le" with transforms', () => testStringEncoding({stdin: noopGenerator()}, execa));91test('input option string is encoded with UTF-8 with encoding "utf16le" with transforms - sync', () => testStringEncoding({stdin: noopGenerator()}, execaSync));9289/*90Sources other than the `input` option also pass strings to the subprocess, which must be encoded with the `encoding` option too.91*/92const testIterableInputEncoding = async (t, execaMethod) => {93// Sources other than the `input` option also pass strings to the subprocess, which are encoded with UTF-8 too94const testIterableInputEncoding = async execaMethod => {95 const input = [`${nonAsciiString}aaa\n`, `${nonAsciiString}bbb\n`];96 const {stdout} = await execaMethod('stdin.js', {94 stdin: [[`${nonAsciiString}aaa\n`], [`${nonAsciiString}bbb\n`]],97 stdin: input.map(chunk => [chunk]),98 encoding: 'utf16le',99 stripFinalNewline: false,100 });98 t.is(stdout, `${nonAsciiString}aaa\n${nonAsciiString}bbb\n`);101 assert.equal(stdout, getUtf16Output(input.join('')));102};103101test('Iterable string input is encoded with encoding "utf16le"', testIterableInputEncoding, execa);102test('Iterable string input is encoded with encoding "utf16le" - sync', testIterableInputEncoding, execaSync);104test('Iterable string input is encoded with UTF-8 with encoding "utf16le"', () => testIterableInputEncoding(execa));105test('Iterable string input is encoded with UTF-8 with encoding "utf16le" - sync', () => testIterableInputEncoding(execaSync));106104const testAsyncIterableInputEncoding = async t => {107const testAsyncIterableInputEncoding = async () => {108 const chunks = async function * () {109 yield nonAsciiString;110 };111112 const {stdout} = await execa('stdin.js', {stdin: [chunks()], encoding: 'utf16le'});110 t.is(stdout, nonAsciiString);113 assert.equal(stdout, getUtf16Output(nonAsciiString));114};115113test('Async iterable string input is encoded with encoding "utf16le"', testAsyncIterableInputEncoding);116test('Async iterable string input is encoded with UTF-8 with encoding "utf16le"', () => testAsyncIterableInputEncoding());117118/*119The `encoding` option does not change how string input is encoded when it is a binary encoding: those describe how output bytes are serialized, so input keeps using UTF-8.120*/118const testBinaryEncodingInput = async (t, encoding, execaMethod) => {121const testBinaryEncodingInput = async (encoding, execaMethod) => {122 const {stdout} = await execaMethod('stdin.js', {input: nonAsciiString, encoding});120 t.is(stdout, Buffer.from(nonAsciiString).toString(encoding));123 assert.equal(stdout, Buffer.from(nonAsciiString).toString(encoding));124};125123test('String input stays UTF-8 with encoding "latin1"', testBinaryEncodingInput, 'latin1', execa);124test('String input stays UTF-8 with encoding "latin1" - sync', testBinaryEncodingInput, 'latin1', execaSync);125test('String input stays UTF-8 with encoding "hex"', testBinaryEncodingInput, 'hex', execa);126test('String input stays UTF-8 with encoding "hex" - sync', testBinaryEncodingInput, 'hex', execaSync);126test('String input stays UTF-8 with encoding "latin1"', () => testBinaryEncodingInput('latin1', execa));127test('String input stays UTF-8 with encoding "latin1" - sync', () => testBinaryEncodingInput('latin1', execaSync));128test('String input stays UTF-8 with encoding "hex"', () => testBinaryEncodingInput('hex', execa));129test('String input stays UTF-8 with encoding "hex" - sync', () => testBinaryEncodingInput('hex', execaSync));
modified:test/io/input-sync.js+48 added-30 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import {openSync, closeSync} from 'node:fs';3import process from 'node:process';4import test from 'node:test';5import {assertThrows} from '../helpers/assert.js';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {getStdio} from '../helpers/stdio.js';9import {noopGenerator, serializeGenerator} from '../helpers/generator.js';10import {foobarObject, foobarObjectString} from '../helpers/input.js';11import {nestedSubprocess} from '../helpers/nested.js';1213setFixtureDirectory();1415const getFd3InputMessage = type => `not \`stdio[3]\`, can be ${type}`;1612const testFd3InputSync = (t, stdioOption, expectedMessage) => {13 const {message} = t.throws(() => {17const testFd3InputSync = (stdioOption, expectedMessage) => {18 const {message} = assertThrows(() => {19 execaSync('empty.js', getStdio(3, stdioOption));20 });16 t.true(message.includes(expectedMessage));21 assert.ok(message.includes(expectedMessage));22};2319test('Cannot use Uint8Array with stdio[*], sync', testFd3InputSync, new Uint8Array(), getFd3InputMessage('a Uint8Array'));20test('Cannot use iterable with stdio[*], sync', testFd3InputSync, [[]], getFd3InputMessage('an iterable'));24test('Cannot use Uint8Array with stdio[*], sync', () => testFd3InputSync(new Uint8Array(), getFd3InputMessage('a Uint8Array')));25test('Cannot use iterable with stdio[*], sync', () => testFd3InputSync([[]], getFd3InputMessage('an iterable')));2627/*28With asynchronous methods, all `stdin` sources are merged into a single stream before being transformed, so transform state (including line splitting) spans all sources.29Synchronous methods must apply the transform pipeline once over the merged sources, not once per source.30*/26const testMultipleSources = async (t, execaMethod) => {31const testMultipleSources = async execaMethod => {32 const {stdout} = await execaMethod('stdin.js', {33 stdin: [['a'], ['b\n'], noopGenerator()],34 });30 t.is(stdout, 'ab');35 assert.equal(stdout, 'ab');36};3733test('Multiple stdin sources are transformed as a single stream', testMultipleSources, execa);34test('Multiple stdin sources are transformed as a single stream, sync', testMultipleSources, execaSync);38test('Multiple stdin sources are transformed as a single stream', () => testMultipleSources(execa));39test('Multiple stdin sources are transformed as a single stream, sync', () => testMultipleSources(execaSync));4041// The generator's `final` function must run once overall, not once per source42const finalCountGenerator = {43 * transform(value) {
3 unmodified lines
47 yield '[F]';48 },49};5046const testMultipleSourcesFinal = async (t, execaMethod) => {51const testMultipleSourcesFinal = async execaMethod => {52 const {stdout} = await execaMethod('stdin.js', {53 stdin: [['a'], ['b\n'], finalCountGenerator],54 });50 t.is(stdout, 'ab\n[F]');55 assert.equal(stdout, 'ab\n[F]');56};5753test('Generator "final" runs once with multiple stdin sources', testMultipleSourcesFinal, execa);54test('Generator "final" runs once with multiple stdin sources, sync', testMultipleSourcesFinal, execaSync);58test('Generator "final" runs once with multiple stdin sources', () => testMultipleSourcesFinal(execa));59test('Generator "final" runs once with multiple stdin sources, sync', () => testMultipleSourcesFinal(execaSync));6061// Without transforms, multiple sources are simply concatenated, like a single source with multiple chunks57const testMultipleSourcesNoTransform = async (t, execaMethod) => {62const testMultipleSourcesNoTransform = async execaMethod => {63 const {stdout} = await execaMethod('stdin.js', {stdin: [['a'], ['b\n']]});59 t.is(stdout, 'ab');64 assert.equal(stdout, 'ab');65};6662test('Multiple stdin sources are concatenated without transforms', testMultipleSourcesNoTransform, execa);63test('Multiple stdin sources are concatenated without transforms, sync', testMultipleSourcesNoTransform, execaSync);67test('Multiple stdin sources are concatenated without transforms', () => testMultipleSourcesNoTransform(execa));68test('Multiple stdin sources are concatenated without transforms, sync', () => testMultipleSourcesNoTransform(execaSync));6970// A `\r\n` sequence split across two sources must still be detected, like across two chunks of a single source66const testWindowsNewlineSpanningSources = async (t, execaMethod) => {71const testWindowsNewlineSpanningSources = async execaMethod => {72 const {stdout} = await execaMethod('stdin.js', {73 stdin: [['x\r'], ['\ny'], noopGenerator()],74 stripFinalNewline: false,75 });71 t.is(stdout, 'x\r\ny\r\n');76 assert.equal(stdout, 'x\r\ny\r\n');77};7874test('Windows newlines can span multiple stdin sources', testWindowsNewlineSpanningSources, execa);75test('Windows newlines can span multiple stdin sources, sync', testWindowsNewlineSpanningSources, execaSync);79test('Windows newlines can span multiple stdin sources', () => testWindowsNewlineSpanningSources(execa));80test('Windows newlines can span multiple stdin sources, sync', () => testWindowsNewlineSpanningSources(execaSync));8182// The `input` option is one more source going through the same transforms, in the order the sources were passed78const testInputOptionWithStdinSource = async (t, execaMethod) => {83const testInputOptionWithStdinSource = async execaMethod => {84 const {stdout} = await execaMethod('stdin.js', {85 stdin: [['a'], noopGenerator()],86 input: 'b',87 });83 t.is(stdout, 'ab');88 assert.equal(stdout, 'ab');89};9086test('The input option is transformed together with stdin sources', testInputOptionWithStdinSource, execa);87test('The input option is transformed together with stdin sources, sync', testInputOptionWithStdinSource, execaSync);91test('The input option is transformed together with stdin sources', () => testInputOptionWithStdinSource(execa));92test('The input option is transformed together with stdin sources, sync', () => testInputOptionWithStdinSource(execaSync));9394// Object inputs are serialized no matter how many sources they come from90const testMultipleObjectSources = async (t, execaMethod) => {95const testMultipleObjectSources = async execaMethod => {96 const {stdout} = await execaMethod('stdin.js', {97 stdin: [[foobarObject], [foobarObject], serializeGenerator(true)],98 });94 t.is(stdout, `${foobarObjectString}\n${foobarObjectString}`);99 assert.equal(stdout, `${foobarObjectString}\n${foobarObjectString}`);100};10197test('Multiple object stdin sources are serialized', testMultipleObjectSources, execa);98test('Multiple object stdin sources are serialized, sync', testMultipleObjectSources, execaSync);102test('Multiple object stdin sources are serialized', () => testMultipleObjectSources(execa));103test('Multiple object stdin sources are serialized, sync', () => testMultipleObjectSources(execaSync));104105// Like `inputFile`, the inherited file descriptor is read lazily, so that a read failure is reported like any other error, including with `reject: false`106if (process.platform !== 'win32') {107 test('Failing to read stdin: ["inherit", "pipe"] is reported as an Execa error, sync', async () => {108 const directoryFd = openSync('.', 'r');109 try {110 const {nestedResult} = await nestedSubprocess('empty.js', {isSync: true, stdin: ['inherit', 'pipe'], reject: false}, {stdin: directoryFd});111 assert.ok(nestedResult.message.startsWith('Command failed with EISDIR'));112 } finally {113 closeSync(directoryFd);114 }115 });116}
modified:test/io/iterate.js+103 added-102 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {getDefaultHighWaterMark} from 'node:stream';3import test from 'ava';4import test from 'node:test';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {7 assertStreamOutput,8 assertIterableChunks,
42 unmodified lines
51 subprocess.stdin.end(output);52 return subprocess;53};5454const assertChunks = async (t, streamOrIterable, expectedChunks, methodName) => {55const assertChunks = async (streamOrIterable, expectedChunks, methodName) => {56 const assertMethod = methodName === 'iterable' ? assertIterableChunks : assertStreamChunks;56 await assertMethod(t, streamOrIterable, expectedChunks);57 await assertMethod(streamOrIterable, expectedChunks);58};5960// eslint-disable-next-line max-params60const testText = async (t, expectedChunks, methodName, binary, preserveNewlines, encoding) => {61const testText = async (expectedChunks, methodName, binary, preserveNewlines, encoding) => {62 const subprocess = getReadWriteSubprocess({encoding});63 const input = encoding === 'utf16le' ? complexFullUtf16 : complexFull;64 subprocess.stdin.end(input);65 const stream = subprocess[methodName]({binary, preserveNewlines});6666 await assertChunks(t, stream, expectedChunks, methodName);67 await assertChunks(stream, expectedChunks, methodName);68 const expectedOutput = encoding === 'hex'69 ? singleComplexHex70 : stringToUint8Arrays(complexFull, encoding === 'buffer');70 await assertSubprocessOutput(t, subprocess, expectedOutput);71 await assertSubprocessOutput(subprocess, expectedOutput);72};7373test('.iterable() can use "binary: true"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'utf8');74test('.iterable() can use "binary: true" + "encoding: utf16le"', testText, [complexFullUtf16Uint8Array], 'iterable', true, undefined, 'utf16le');75test('.iterable() can use "binary: true" + "encoding: "buffer"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'buffer');76test('.iterable() can use "binary: true" + "encoding: "hex"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'hex');77test('.iterable() can use "binary: undefined"', testText, complexChunks, 'iterable', undefined, undefined, 'utf8');78test('.iterable() can use "binary: undefined" + "encoding: utf16le"', testText, complexChunks, 'iterable', undefined, undefined, 'utf16le');79test('.iterable() can use "binary: undefined" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'buffer');80test('.iterable() can use "binary: undefined" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'hex');81test('.iterable() can use "binary: false"', testText, complexChunks, 'iterable', false, undefined, 'utf8');82test('.iterable() can use "binary: false" + "encoding: utf16le"', testText, complexChunks, 'iterable', false, undefined, 'utf16le');83test('.iterable() can use "binary: false" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'buffer');84test('.iterable() can use "binary: false" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'hex');85test('.iterable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'iterable', false, true, 'utf8');86test('.iterable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'iterable', false, false, 'utf8');87test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined, 'utf8');88test('.readable() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', true, undefined, 'utf16le');89test('.readable() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', true, undefined, 'buffer');90test('.readable() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'readable', true, undefined, 'hex');91test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'utf8');92test('.readable() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', undefined, undefined, 'utf16le');93test('.readable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'buffer');94test('.readable() can use "binary: undefined" + "encoding: hex"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'hex');95test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined, 'utf8');96test('.readable() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'readable', false, undefined, 'utf16le');97test('.readable() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', false, undefined, 'buffer');98test('.readable() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'readable', false, undefined, 'hex');99test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true, 'utf8');100test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false, 'utf8');101test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined, 'utf8');102test('.duplex() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', true, undefined, 'utf16le');103test('.duplex() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', true, undefined, 'buffer');104test('.duplex() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', true, undefined, 'hex');105test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'utf8');106test('.duplex() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', undefined, undefined, 'utf16le');107test('.duplex() can use "binary: undefined" + "encoding: "buffer"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'buffer');108test('.duplex() can use "binary: undefined" + "encoding: "hex"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'hex');109test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf8');110test('.duplex() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf16le');111test('.duplex() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', false, undefined, 'buffer');112test('.duplex() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', false, undefined, 'hex');113test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true, 'utf8');114test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false, 'utf8');74test('.iterable() can use "binary: true"', () => testText([singleComplexUint8Array], 'iterable', true, undefined, 'utf8'));75test('.iterable() can use "binary: true" + "encoding: utf16le"', () => testText([complexFullUtf16Uint8Array], 'iterable', true, undefined, 'utf16le'));76test('.iterable() can use "binary: true" + "encoding: "buffer"', () => testText([singleComplexUint8Array], 'iterable', true, undefined, 'buffer'));77test('.iterable() can use "binary: true" + "encoding: "hex"', () => testText([singleComplexUint8Array], 'iterable', true, undefined, 'hex'));78test('.iterable() can use "binary: undefined"', () => testText(complexChunks, 'iterable', undefined, undefined, 'utf8'));79test('.iterable() can use "binary: undefined" + "encoding: utf16le"', () => testText(complexChunks, 'iterable', undefined, undefined, 'utf16le'));80test('.iterable() can use "binary: undefined" + "encoding: buffer"', () => testText([singleComplexUint8Array], 'iterable', undefined, undefined, 'buffer'));81test('.iterable() can use "binary: undefined" + "encoding: hex"', () => testText([singleComplexUint8Array], 'iterable', undefined, undefined, 'hex'));82test('.iterable() can use "binary: false"', () => testText(complexChunks, 'iterable', false, undefined, 'utf8'));83test('.iterable() can use "binary: false" + "encoding: utf16le"', () => testText(complexChunks, 'iterable', false, undefined, 'utf16le'));84test('.iterable() can use "binary: false" + "encoding: buffer"', () => testText([singleComplexUint8Array], 'iterable', false, undefined, 'buffer'));85test('.iterable() can use "binary: false" + "encoding: hex"', () => testText([singleComplexUint8Array], 'iterable', false, undefined, 'hex'));86test('.iterable() can use "binary: false" + "preserveNewlines: true"', () => testText(complexChunksEnd, 'iterable', false, true, 'utf8'));87test('.iterable() can use "binary: false" + "preserveNewlines: false"', () => testText(complexChunks, 'iterable', false, false, 'utf8'));88test('.readable() can use "binary: true"', () => testText(singleComplexBuffer, 'readable', true, undefined, 'utf8'));89test('.readable() can use "binary: true" + "encoding: utf16le"', () => testText(singleComplexUtf16Buffer, 'readable', true, undefined, 'utf16le'));90test('.readable() can use "binary: true" + "encoding: buffer"', () => testText(singleComplexBuffer, 'readable', true, undefined, 'buffer'));91test('.readable() can use "binary: true" + "encoding: hex"', () => testText(singleComplexBuffer, 'readable', true, undefined, 'hex'));92test('.readable() can use "binary: undefined"', () => testText(singleComplexBuffer, 'readable', undefined, undefined, 'utf8'));93test('.readable() can use "binary: undefined" + "encoding: utf16le"', () => testText(singleComplexUtf16Buffer, 'readable', undefined, undefined, 'utf16le'));94test('.readable() can use "binary: undefined" + "encoding: buffer"', () => testText(singleComplexBuffer, 'readable', undefined, undefined, 'buffer'));95test('.readable() can use "binary: undefined" + "encoding: hex"', () => testText(singleComplexBuffer, 'readable', undefined, undefined, 'hex'));96test('.readable() can use "binary: false"', () => testText(complexChunksEnd, 'readable', false, undefined, 'utf8'));97test('.readable() can use "binary: false" + "encoding: utf16le"', () => testText(complexChunksEnd, 'readable', false, undefined, 'utf16le'));98test('.readable() can use "binary: false" + "encoding: buffer"', () => testText(singleComplexBuffer, 'readable', false, undefined, 'buffer'));99test('.readable() can use "binary: false" + "encoding: hex"', () => testText(singleComplexBuffer, 'readable', false, undefined, 'hex'));100test('.readable() can use "binary: false" + "preserveNewlines: true"', () => testText(complexChunksEnd, 'readable', false, true, 'utf8'));101test('.readable() can use "binary: false" + "preserveNewlines: false"', () => testText(complexChunks, 'readable', false, false, 'utf8'));102test('.duplex() can use "binary: true"', () => testText(singleComplexBuffer, 'duplex', true, undefined, 'utf8'));103test('.duplex() can use "binary: true" + "encoding: utf16le"', () => testText(singleComplexUtf16Buffer, 'duplex', true, undefined, 'utf16le'));104test('.duplex() can use "binary: true" + "encoding: buffer"', () => testText(singleComplexBuffer, 'duplex', true, undefined, 'buffer'));105test('.duplex() can use "binary: true" + "encoding: hex"', () => testText(singleComplexBuffer, 'duplex', true, undefined, 'hex'));106test('.duplex() can use "binary: undefined"', () => testText(singleComplexBuffer, 'duplex', undefined, undefined, 'utf8'));107test('.duplex() can use "binary: undefined" + "encoding: utf16le"', () => testText(singleComplexUtf16Buffer, 'duplex', undefined, undefined, 'utf16le'));108test('.duplex() can use "binary: undefined" + "encoding: "buffer"', () => testText(singleComplexBuffer, 'duplex', undefined, undefined, 'buffer'));109test('.duplex() can use "binary: undefined" + "encoding: "hex"', () => testText(singleComplexBuffer, 'duplex', undefined, undefined, 'hex'));110test('.duplex() can use "binary: false"', () => testText(complexChunksEnd, 'duplex', false, undefined, 'utf8'));111test('.duplex() can use "binary: false" + "encoding: utf16le"', () => testText(complexChunksEnd, 'duplex', false, undefined, 'utf16le'));112test('.duplex() can use "binary: false" + "encoding: buffer"', () => testText(singleComplexBuffer, 'duplex', false, undefined, 'buffer'));113test('.duplex() can use "binary: false" + "encoding: hex"', () => testText(singleComplexBuffer, 'duplex', false, undefined, 'hex'));114test('.duplex() can use "binary: false" + "preserveNewlines: true"', () => testText(complexChunksEnd, 'duplex', false, true, 'utf8'));115test('.duplex() can use "binary: false" + "preserveNewlines: false"', () => testText(complexChunks, 'duplex', false, false, 'utf8'));116116const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {117const testTextOutput = async (expectedOutput, methodName, preserveNewlines) => {118 const subprocess = getSubprocess(methodName, complexFull);119 const stream = subprocess[methodName]({binary: false, preserveNewlines});120120 await assertStreamOutput(t, stream, expectedOutput);121 await assertSubprocessOutput(t, subprocess, complexFull);121 await assertStreamOutput(stream, expectedOutput);122 await assertSubprocessOutput(subprocess, complexFull);123};124124test('.readable() "binary: false" keeps output as is', testTextOutput, complexFull, 'readable', undefined);125test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'readable', true);126test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'readable', false);127test('.duplex() "binary: false" keeps output as is', testTextOutput, complexFull, 'duplex', undefined);128test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'duplex', true);129test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'duplex', false);125test('.readable() "binary: false" keeps output as is', () => testTextOutput(complexFull, 'readable', undefined));126test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', () => testTextOutput(complexFull, 'readable', true));127test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', () => testTextOutput(noNewlinesFull, 'readable', false));128test('.duplex() "binary: false" keeps output as is', () => testTextOutput(complexFull, 'duplex', undefined));129test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', () => testTextOutput(complexFull, 'duplex', true));130test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', () => testTextOutput(noNewlinesFull, 'duplex', false));131132// eslint-disable-next-line max-params132const testObjectMode = async (t, expectedChunks, methodName, encoding, initialObjectMode, finalObjectMode, binary, options) => {133const testObjectMode = async (expectedChunks, methodName, encoding, initialObjectMode, finalObjectMode, binary, options) => {134 const subprocess = getSubprocess(methodName, simpleFull, options);135 if (encoding !== null) {136 subprocess.stdout.setEncoding(encoding);137 }138138 t.is(subprocess.stdout.readableEncoding, encoding);139 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);140 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));139 assert.equal(subprocess.stdout.readableEncoding, encoding);140 assert.equal(subprocess.stdout.readableObjectMode, initialObjectMode);141 assert.equal(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));142143 const stream = subprocess[methodName]({binary, preserveNewlines: true});144145 if (methodName !== 'iterable') {145 t.is(stream.readableEncoding, encoding);146 t.is(stream.readableObjectMode, finalObjectMode);147 t.is(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));146 assert.equal(stream.readableEncoding, encoding);147 assert.equal(stream.readableObjectMode, finalObjectMode);148 assert.equal(stream.readableHighWaterMark, getDefaultHighWaterMark(finalObjectMode));149 }150150 t.is(subprocess.stdout.readableEncoding, encoding);151 t.is(subprocess.stdout.readableObjectMode, initialObjectMode);152 t.is(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));151 assert.equal(subprocess.stdout.readableEncoding, encoding);152 assert.equal(subprocess.stdout.readableObjectMode, initialObjectMode);153 assert.equal(subprocess.stdout.readableHighWaterMark, getDefaultHighWaterMark(initialObjectMode));154154 await assertChunks(t, stream, expectedChunks, methodName);155 await assertChunks(stream, expectedChunks, methodName);156 await subprocess;157};158158test('.iterable() uses Uint8Arrays with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);159test('.iterable() uses Uint8Arrays with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true);160test('.iterable() uses Uint8Arrays with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});161test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()});162test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);163test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);164test('.iterable() uses Uint8Arrays in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});165test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()});166test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);167test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);168test('.readable() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});169test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()});170test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);171test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);172test('.readable() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'});173test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()});174test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);175test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);176test('.duplex() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});177test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()});178test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);179test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);180test('.duplex() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'});181test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()});159test('.iterable() uses Uint8Arrays with "binary: true"', () => testObjectMode(simpleChunksUint8Array, 'iterable', null, false, false, true));160test('.iterable() uses Uint8Arrays with "binary: true" and .setEncoding("utf8")', () => testObjectMode(simpleChunksUint8Array, 'iterable', 'utf8', false, false, true));161test('.iterable() uses Uint8Arrays with "binary: true", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunksUint8Array, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'}));162test('.iterable() uses strings in objectMode with "binary: true" and object transforms', () => testObjectMode(foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()}));163test('.iterable() uses strings in objectMode with "binary: false"', () => testObjectMode(simpleLines, 'iterable', null, false, true, false));164test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', () => testObjectMode(simpleLines, 'iterable', 'utf8', false, true, false));165test('.iterable() uses Uint8Arrays in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunksUint8Array, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'}));166test('.iterable() uses strings in objectMode with "binary: false" and object transforms', () => testObjectMode(foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()}));167test('.readable() uses Buffers with "binary: true"', () => testObjectMode(simpleChunksBuffer, 'readable', null, false, false, true));168test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', () => testObjectMode(simpleChunks, 'readable', 'utf8', false, false, true));169test('.readable() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'}));170test('.readable() uses strings in objectMode with "binary: true" and object transforms', () => testObjectMode(foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()}));171test('.readable() uses strings in objectMode with "binary: false"', () => testObjectMode(simpleLines, 'readable', null, false, true, false));172test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', () => testObjectMode(simpleLines, 'readable', 'utf8', false, true, false));173test('.readable() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'}));174test('.readable() uses strings in objectMode with "binary: false" and object transforms', () => testObjectMode(foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()}));175test('.duplex() uses Buffers with "binary: true"', () => testObjectMode(simpleChunksBuffer, 'duplex', null, false, false, true));176test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', () => testObjectMode(simpleChunks, 'duplex', 'utf8', false, false, true));177test('.duplex() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'}));178test('.duplex() uses strings in objectMode with "binary: true" and object transforms', () => testObjectMode(foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()}));179test('.duplex() uses strings in objectMode with "binary: false"', () => testObjectMode(simpleLines, 'duplex', null, false, true, false));180test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', () => testObjectMode(simpleLines, 'duplex', 'utf8', false, true, false));181test('.duplex() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'}));182test('.duplex() uses strings in objectMode with "binary: false" and object transforms', () => testObjectMode(foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()}));183183const testObjectSplit = async (t, methodName) => {184const testObjectSplit = async methodName => {185 const subprocess = getSubprocess(methodName, foobarString, {stdout: getOutputGenerator(simpleFull)(true)});186 const stream = subprocess[methodName]({binary: false});186 await assertChunks(t, stream, [simpleFull], methodName);187 await assertChunks(stream, [simpleFull], methodName);188 await subprocess;189};190190test('.iterable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'iterable');191test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');192test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');191test('.iterable() "binary: false" does not split lines of strings produced by object transforms', () => testObjectSplit('iterable'));192test('.readable() "binary: false" does not split lines of strings produced by object transforms', () => testObjectSplit('readable'));193test('.duplex() "binary: false" does not split lines of strings produced by object transforms', () => testObjectSplit('duplex'));194194const testMultibyteCharacters = async (t, methodName) => {195const testMultibyteCharacters = async methodName => {196 const subprocess = getReadWriteSubprocess();197 const stream = subprocess[methodName]({binary: false});197 const assertPromise = assertChunks(t, stream, [`${multibyteChar}${brokenSymbol}`], methodName);198 const assertPromise = assertChunks(stream, [`${multibyteChar}${brokenSymbol}`], methodName);199 subprocess.stdin.write(multibyteUint8Array.slice(0, breakingLength));200 await once(subprocess.stdout, 'data');201 subprocess.stdin.end();202 await assertPromise;203};204204test('.iterable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'iterable');205test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');206test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');205test('.iterable() "binary: false" handles partial multibyte characters', () => testMultibyteCharacters('iterable'));206test('.readable() "binary: false" handles partial multibyte characters', () => testMultibyteCharacters('readable'));207test('.duplex() "binary: false" handles partial multibyte characters', () => testMultibyteCharacters('duplex'));
modified:test/io/max-buffer.js+291 added-264 removed
1import assert from 'node:assert/strict';2import {Buffer} from 'node:buffer';2import test from 'ava';3import {readFile, rm} from 'node:fs/promises';4import test from 'node:test';5import getStream from 'get-stream';6import tempfile from 'tempfile';7import {assertThrows, assertRejects} from '../helpers/assert.js';8import {execa, execaSync} from '../../index.js';9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10import {fullStdio} from '../helpers/stdio.js';11import {getEarlyErrorSubprocess} from '../helpers/early-error.js';
4 unmodified lines
1617const maxBufferMessage = {message: /maxBuffer exceeded/};18const maxBufferCodeSync = {code: 'ENOBUFS'};1916const runMaxBuffer = async (t, execaMethod, fdNumber, options) => {20const runMaxBuffer = async (execaMethod, fdNumber, options) => {21 const error = execaMethod === execa18 ? await t.throwsAsync(getMaxBufferSubprocess(execaMethod, fdNumber, options), maxBufferMessage)19 : t.throws(() => {22 ? await assertRejects(getMaxBufferSubprocess(execaMethod, fdNumber, options), maxBufferMessage)23 : assertThrows(() => {24 getMaxBufferSubprocess(execaMethod, fdNumber, options);25 }, maxBufferCodeSync);22 t.true(error.isMaxBuffer);23 t.is(error.maxBufferInfo, undefined);26 assert.equal(error.isMaxBuffer, true);27 assert.equal(error.maxBufferInfo, undefined);28 return error;29};3031const getMaxBufferSubprocess = (execaMethod, fdNumber, {length = maxBuffer, ...options} = {}) =>32 execaMethod('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, ...options});3334const getExpectedOutput = (length = maxBuffer) => '.'.repeat(length);3532const testMaxBufferSuccess = async (t, execaMethod, fdNumber, all) => {36const testMaxBufferSuccess = async (execaMethod, fdNumber, all) => {37 const {isMaxBuffer} = await getMaxBufferSubprocess(execaMethod, fdNumber, {all, length: maxBuffer - 1});34 t.false(isMaxBuffer);38 assert.equal(isMaxBuffer, false);39};4037test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, execa, 1, false);38test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, execa, 2, false);39test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, execa, 3, false);40test('maxBuffer does not affect all if too high', testMaxBufferSuccess, execa, 1, true);41test('maxBuffer does not affect stdout if too high, sync', testMaxBufferSuccess, execaSync, 1, false);42test('maxBuffer does not affect stderr if too high, sync', testMaxBufferSuccess, execaSync, 2, false);43test('maxBuffer does not affect stdio[*] if too high, sync', testMaxBufferSuccess, execaSync, 3, false);44test('maxBuffer does not affect all if too high, sync', testMaxBufferSuccess, execaSync, 1, true);41test('maxBuffer does not affect stdout if too high', () => testMaxBufferSuccess(execa, 1, false));42test('maxBuffer does not affect stderr if too high', () => testMaxBufferSuccess(execa, 2, false));43test('maxBuffer does not affect stdio[*] if too high', () => testMaxBufferSuccess(execa, 3, false));44test('maxBuffer does not affect all if too high', () => testMaxBufferSuccess(execa, 1, true));45test('maxBuffer does not affect stdout if too high, sync', () => testMaxBufferSuccess(execaSync, 1, false));46test('maxBuffer does not affect stderr if too high, sync', () => testMaxBufferSuccess(execaSync, 2, false));47test('maxBuffer does not affect stdio[*] if too high, sync', () => testMaxBufferSuccess(execaSync, 3, false));48test('maxBuffer does not affect all if too high, sync', () => testMaxBufferSuccess(execaSync, 1, true));4946const testGracefulExit = async (t, fixtureName, expectedExitCode) => {47 const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = await t.throwsAsync(50const testGracefulExit = async (fixtureName, expectedExitCode) => {51 const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = await assertRejects(52 execa(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer}),53 maxBufferMessage,54 );51 t.true(isMaxBuffer);52 assertErrorMessage(t, shortMessage);53 t.is(exitCode, expectedExitCode);54 t.is(signal, undefined);55 t.is(stdout, getExpectedOutput());55 assert.equal(isMaxBuffer, true);56 assertErrorMessage(shortMessage);57 assert.equal(exitCode, expectedExitCode);58 assert.equal(signal, undefined);59 assert.equal(stdout, getExpectedOutput());60};6158test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);59test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);62test('maxBuffer terminates stream gracefully, more writes', () => testGracefulExit('noop-repeat.js', 1));63test('maxBuffer terminates stream gracefully, no more writes', () => testGracefulExit('noop-fd.js', 0));6461const testGracefulExitSync = (t, fixtureName) => {62 const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = t.throws(() => {65const testGracefulExitSync = fixtureName => {66 const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = assertThrows(() => {67 execaSync(fixtureName, ['1', '.'.repeat(maxBuffer + 1)], {maxBuffer, killSignal: 'SIGINT'});68 }, maxBufferCodeSync);65 t.true(isMaxBuffer);66 assertErrorMessage(t, shortMessage, {execaMethod: execaSync});67 t.is(exitCode, undefined);68 t.is(signal, 'SIGINT');69 t.is(stdout, getExpectedOutput());69 assert.equal(isMaxBuffer, true);70 assertErrorMessage(shortMessage, {execaMethod: execaSync});71 assert.equal(exitCode, undefined);72 assert.equal(signal, 'SIGINT');73 assert.equal(stdout, getExpectedOutput());74};7572test('maxBuffer terminate stream with killSignal, more writes, sync', testGracefulExitSync, 'noop-repeat.js');73test('maxBuffer terminate stream with killSignal, no more writes, sync', testGracefulExitSync, 'noop-fd.js');76test('maxBuffer terminate stream with killSignal, more writes, sync', () => testGracefulExitSync('noop-repeat.js'));77test('maxBuffer terminate stream with killSignal, no more writes, sync', () => testGracefulExitSync('noop-fd.js'));7875const testMaxBufferLimit = async (t, execaMethod, fdNumber, all) => {79const testMaxBufferLimit = async (execaMethod, fdNumber, all) => {80 const length = all && execaMethod === execa ? maxBuffer * 2 : maxBuffer;77 const {shortMessage, all: allOutput, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {all, length});78 assertErrorMessage(t, shortMessage, {execaMethod, fdNumber});79 t.is(all ? allOutput : stdio[fdNumber], getExpectedOutput(length));81 const {shortMessage, all: allOutput, stdio} = await runMaxBuffer(execaMethod, fdNumber, {all, length});82 assertErrorMessage(shortMessage, {execaMethod, fdNumber});83 assert.equal(all ? allOutput : stdio[fdNumber], getExpectedOutput(length));84};8582test('maxBuffer truncates stdout', testMaxBufferLimit, execa, 1, false);83test('maxBuffer truncates stderr', testMaxBufferLimit, execa, 2, false);84test('maxBuffer truncates stdio[*]', testMaxBufferLimit, execa, 3, false);85test('maxBuffer truncates all', testMaxBufferLimit, execa, 1, true);86test('maxBuffer truncates stdout, sync', testMaxBufferLimit, execaSync, 1, false);87test('maxBuffer truncates stderr, sync', testMaxBufferLimit, execaSync, 2, false);88test('maxBuffer truncates stdio[*], sync', testMaxBufferLimit, execaSync, 3, false);89test('maxBuffer truncates all, sync', testMaxBufferLimit, execaSync, 1, true);86test('maxBuffer truncates stdout', () => testMaxBufferLimit(execa, 1, false));87test('maxBuffer truncates stderr', () => testMaxBufferLimit(execa, 2, false));88test('maxBuffer truncates stdio[*]', () => testMaxBufferLimit(execa, 3, false));89test('maxBuffer truncates all', () => testMaxBufferLimit(execa, 1, true));90test('maxBuffer truncates stdout, sync', () => testMaxBufferLimit(execaSync, 1, false));91test('maxBuffer truncates stderr, sync', () => testMaxBufferLimit(execaSync, 2, false));92test('maxBuffer truncates stdio[*], sync', () => testMaxBufferLimit(execaSync, 3, false));93test('maxBuffer truncates all, sync', () => testMaxBufferLimit(execaSync, 1, true));9495const MAX_BUFFER_DEFAULT = 1e8;9693const testMaxBufferDefault = async (t, execaMethod, fdNumber, maxBuffer) => {97const testMaxBufferDefault = async (execaMethod, fdNumber, maxBuffer) => {98 const length = MAX_BUFFER_DEFAULT;95 const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {length: MAX_BUFFER_DEFAULT + 1, maxBuffer});96 assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, length});97 t.is(stdio[fdNumber], getExpectedOutput(length));99 const {shortMessage, stdio} = await runMaxBuffer(execaMethod, fdNumber, {length: MAX_BUFFER_DEFAULT + 1, maxBuffer});100 assertErrorMessage(shortMessage, {execaMethod, fdNumber, length});101 assert.equal(stdio[fdNumber], getExpectedOutput(length));102};103100test('maxBuffer has a default value with stdout', testMaxBufferDefault, execa, 1, undefined);101test('maxBuffer has a default value with stderr', testMaxBufferDefault, execa, 2, undefined);102test('maxBuffer has a default value with stdio[*]', testMaxBufferDefault, execa, 3, undefined);103test('maxBuffer has a default value with stdout, sync', testMaxBufferDefault, execaSync, 1, undefined);104test('maxBuffer has a default value with stderr, sync', testMaxBufferDefault, execaSync, 2, undefined);105test('maxBuffer has a default value with stdio[*], sync', testMaxBufferDefault, execaSync, 3, undefined);106test('maxBuffer has a default value with stdout with fd-specific options', testMaxBufferDefault, execa, 1, {stderr: 1e9});107test('maxBuffer has a default value with stderr with fd-specific options', testMaxBufferDefault, execa, 2, {stdout: 1e9});108test('maxBuffer has a default value with stdio[*] with fd-specific options', testMaxBufferDefault, execa, 3, {stdout: 1e9});109test('maxBuffer has a default value with stdout with empty fd-specific options', testMaxBufferDefault, execa, 1, {});104test('maxBuffer has a default value with stdout', () => testMaxBufferDefault(execa, 1, undefined));105test('maxBuffer has a default value with stderr', () => testMaxBufferDefault(execa, 2, undefined));106test('maxBuffer has a default value with stdio[*]', () => testMaxBufferDefault(execa, 3, undefined));107test('maxBuffer has a default value with stdout, sync', () => testMaxBufferDefault(execaSync, 1, undefined));108test('maxBuffer has a default value with stderr, sync', () => testMaxBufferDefault(execaSync, 2, undefined));109test('maxBuffer has a default value with stdio[*], sync', () => testMaxBufferDefault(execaSync, 3, undefined));110test('maxBuffer has a default value with stdout with fd-specific options', () => testMaxBufferDefault(execa, 1, {stderr: 1e9}));111test('maxBuffer has a default value with stderr with fd-specific options', () => testMaxBufferDefault(execa, 2, {stdout: 1e9}));112test('maxBuffer has a default value with stdio[*] with fd-specific options', () => testMaxBufferDefault(execa, 3, {stdout: 1e9}));113test('maxBuffer has a default value with stdout with empty fd-specific options', () => testMaxBufferDefault(execa, 1, {}));114111const testFdSpecific = async (t, fdNumber, fdName, execaMethod) => {115const testFdSpecific = async (fdNumber, fdName, execaMethod) => {116 const length = 1;113 const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {maxBuffer: {[fdName]: length}});114 assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, length});115 t.is(stdio[fdNumber], getExpectedOutput(length));117 const {shortMessage, stdio} = await runMaxBuffer(execaMethod, fdNumber, {maxBuffer: {[fdName]: length}});118 assertErrorMessage(shortMessage, {execaMethod, fdNumber, length});119 assert.equal(stdio[fdNumber], getExpectedOutput(length));120};121118test('maxBuffer truncates file descriptors with fd-specific options, stdout', testFdSpecific, 1, 'stdout', execa);119test('maxBuffer truncates file descriptors with fd-specific options, fd1', testFdSpecific, 1, 'fd1', execa);120test('maxBuffer truncates file descriptors with fd-specific options, stderr', testFdSpecific, 2, 'stderr', execa);121test('maxBuffer truncates file descriptors with fd-specific options, fd2', testFdSpecific, 2, 'fd2', execa);122test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', testFdSpecific, 1, 'all', execa);123test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', testFdSpecific, 2, 'all', execa);124test('maxBuffer truncates file descriptors with fd-specific options, fd3', testFdSpecific, 3, 'fd3', execa);125test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', testFdSpecific, 1, 'stdout', execaSync);126test('maxBuffer.stderr is used for stderr with fd-specific options, stderr, sync', testFdSpecific, 2, 'stderr', execaSync);127test('maxBuffer.fd3 is used for stdio[*] with fd-specific options, fd3, sync', testFdSpecific, 3, 'fd3', execaSync);122test('maxBuffer truncates file descriptors with fd-specific options, stdout', () => testFdSpecific(1, 'stdout', execa));123test('maxBuffer truncates file descriptors with fd-specific options, fd1', () => testFdSpecific(1, 'fd1', execa));124test('maxBuffer truncates file descriptors with fd-specific options, stderr', () => testFdSpecific(2, 'stderr', execa));125test('maxBuffer truncates file descriptors with fd-specific options, fd2', () => testFdSpecific(2, 'fd2', execa));126test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', () => testFdSpecific(1, 'all', execa));127test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', () => testFdSpecific(2, 'all', execa));128test('maxBuffer truncates file descriptors with fd-specific options, fd3', () => testFdSpecific(3, 'fd3', execa));129test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', () => testFdSpecific(1, 'stdout', execaSync));130test('maxBuffer.stderr is used for stderr with fd-specific options, stderr, sync', () => testFdSpecific(2, 'stderr', execaSync));131test('maxBuffer.fd3 is used for stdio[*] with fd-specific options, fd3, sync', () => testFdSpecific(3, 'fd3', execaSync));132129test('maxBuffer does not affect other file descriptors with fd-specific options', async t => {133test('maxBuffer does not affect other file descriptors with fd-specific options', async () => {134 const {isMaxBuffer} = await getMaxBufferSubprocess(execa, 2, {maxBuffer: {stdout: 1}});131 t.false(isMaxBuffer);135 assert.equal(isMaxBuffer, false);136});137134test('maxBuffer.fd3 is invalid without stdio[3], even with ipc', t => {135 const {message} = t.throws(() => {138test('maxBuffer.fd3 is invalid without stdio[3], even with ipc', () => {139 const {message} = assertThrows(() => {140 execa('ipc-send-twice.js', {ipc: true, maxBuffer: {fd3: 1}});141 });138 t.true(message.includes('"maxBuffer.fd3" is invalid: that file descriptor does not exist.'));142 assert.ok(message.includes('"maxBuffer.fd3" is invalid: that file descriptor does not exist.'));143});144141test('maxBuffer.fd3 and maxBuffer.ipc are distinct', async t => {145test('maxBuffer.fd3 and maxBuffer.ipc are distinct', async () => {146 const {isMaxBuffer, ipcOutput} = await execa('ipc-send-twice.js', {147 ipc: true,148 stdio: ['ignore', 'pipe', 'pipe', 'pipe'],149 maxBuffer: {150 fd3: 1,151 ipc: 2,152 },153 });150 t.false(isMaxBuffer);151 t.deepEqual(ipcOutput, foobarArray);154 assert.equal(isMaxBuffer, false);155 assert.deepEqual(ipcOutput, foobarArray);156});157154test('maxBuffer.stdout is used for other file descriptors with fd-specific options, sync', async t => {158test('maxBuffer.stdout is used for other file descriptors with fd-specific options, sync', async () => {159 const length = 1;156 const {shortMessage, stderr} = await runMaxBuffer(t, execaSync, 2, {maxBuffer: {stdout: length}});157 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});158 t.is(stderr, getExpectedOutput(length));160 const {shortMessage, stderr} = await runMaxBuffer(execaSync, 2, {maxBuffer: {stdout: length}});161 assertErrorMessage(shortMessage, {execaMethod: execaSync, fdNumber: 2, length});162 assert.equal(stderr, getExpectedOutput(length));163});164165// `spawnSync()`'s native `maxBuffer` is `maxBuffer.stdout`, so a lower limit on another file descriptor is only enforced from the output, after the subprocess exits162test('maxBuffer.stderr is used when lower than maxBuffer.stdout, sync', t => {166test('maxBuffer.stderr is used when lower than maxBuffer.stdout, sync', () => {167 const length = 3;164 const error = t.throws(() => {168 const error = assertThrows(() => {169 execaSync('noop-both.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer: {stdout: 1e8, stderr: length}});170 }, maxBufferCodeSync);167 t.true(error.isMaxBuffer);168 t.is(error.maxBufferInfo, undefined);169 assertErrorMessage(t, error.shortMessage, {execaMethod: execaSync, fdNumber: 2, length});170 t.is(error.stdout, getExpectedOutput(maxBuffer + 1));171 t.is(error.stderr, getExpectedOutput(length));172 t.is(error.signal, undefined);173 t.is(error.exitCode, 0);171 assert.equal(error.isMaxBuffer, true);172 assert.equal(error.maxBufferInfo, undefined);173 assertErrorMessage(error.shortMessage, {execaMethod: execaSync, fdNumber: 2, length});174 assert.equal(error.stdout, getExpectedOutput(maxBuffer + 1));175 assert.equal(error.stderr, getExpectedOutput(length));176 assert.equal(error.signal, undefined);177 assert.equal(error.exitCode, 0);178});179176test('maxBuffer.stderr is used when lower than maxBuffer.stdout', async t => {180test('maxBuffer.stderr is used when lower than maxBuffer.stdout', async () => {181 const length = 3;178 const error = await t.throwsAsync(execa('noop-both.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer: {stdout: 1e8, stderr: length}}));179 t.true(error.isMaxBuffer);180 assertErrorMessage(t, error.shortMessage, {fdNumber: 2, length});181 t.is(error.stdout, getExpectedOutput(maxBuffer + 1));182 t.is(error.stderr, getExpectedOutput(length));183 t.is(error.signal, undefined);184 t.is(error.exitCode, 0);182 const error = await assertRejects(execa('noop-both.js', ['.'.repeat(maxBuffer + 1)], {maxBuffer: {stdout: 1e8, stderr: length}}));183 assert.equal(error.isMaxBuffer, true);184 assertErrorMessage(error.shortMessage, {fdNumber: 2, length});185 assert.equal(error.stdout, getExpectedOutput(maxBuffer + 1));186 assert.equal(error.stderr, getExpectedOutput(length));187 assert.equal(error.signal, undefined);188 assert.equal(error.exitCode, 0);189});190187test('maxBuffer is not hit when under each file descriptor\'s value, sync', t => {191test('maxBuffer is not hit when under each file descriptor\'s value, sync', () => {192 const length = 9;193 const {isMaxBuffer, stdout, stderr} = execaSync('noop-both.js', ['.'.repeat(length)], {maxBuffer: {stdout: 1e8, stderr: 10}});190 t.false(isMaxBuffer);191 t.is(stdout, getExpectedOutput(length));192 t.is(stderr, getExpectedOutput(length));194 assert.equal(isMaxBuffer, false);195 assert.equal(stdout, getExpectedOutput(length));196 assert.equal(stderr, getExpectedOutput(length));197});198199// Like with asynchronous methods, a file descriptor which is not buffered is not limited by its own `maxBuffer` value.200// With synchronous methods, it still counts towards `maxBuffer.stdout`, which limits the total output.201const testMaxBufferNoBuffer = async execaMethod => {202 const filePath = tempfile();203 const length = 3;204 const {isMaxBuffer, stderr} = await execaMethod('noop-both.js', ['.'.repeat(length + 1)], {buffer: {stderr: false}, maxBuffer: {stderr: length}, stderr: ['pipe', {file: filePath}]});205 assert.equal(isMaxBuffer, false);206 assert.equal(stderr, undefined);207 assert.equal(await readFile(filePath, 'utf8'), `${'.'.repeat(length + 1)}\n`);208 await rm(filePath);209};210211test('maxBuffer.stderr is ignored with buffer: false', () => testMaxBufferNoBuffer(execa));212test('maxBuffer.stderr is ignored with buffer: false, sync', () => testMaxBufferNoBuffer(execaSync));213214// `spawnSync()`'s native `maxBuffer` limits the total output of all file descriptors, even when none of them is over its own limit215test('maxBuffer.stdout limits the total output, sync', () => {216 const length = 10;217 const {isMaxBuffer, shortMessage} = execaSync('noop-both.js', ['.'.repeat(length / 2)], {maxBuffer: length, reject: false});218 assert.equal(isMaxBuffer, true);219 assert.ok(shortMessage.startsWith(`Command's output was larger than ${length} bytes`));220});221195const testAll = async (t, shouldFail) => {222const testAll = async shouldFail => {223 const difference = shouldFail ? 0 : 1;224 const maxBufferStdout = 2;225 const maxBufferStderr = 4 - difference;226 const {isMaxBuffer, shortMessage, stdout, stderr, all} = await execa(
5 unmodified lines
232 stripFinalNewline: false,233 reject: false,234 },235 );209 t.is(isMaxBuffer, shouldFail);236 assert.equal(isMaxBuffer, shouldFail);237 if (shouldFail) {211 assertErrorMessage(t, shortMessage, {fdNumber: 2, length: maxBufferStderr});238 assertErrorMessage(shortMessage, {fdNumber: 2, length: maxBufferStderr});239 }240214 t.is(stdout, '\n'.repeat(maxBufferStdout));215 t.is(stderr, '\n'.repeat(maxBufferStderr));216 t.is(all, '\n'.repeat(maxBufferStdout + maxBufferStderr));241 assert.equal(stdout, '\n'.repeat(maxBufferStdout));242 assert.equal(stderr, '\n'.repeat(maxBufferStderr));243 assert.equal(all, '\n'.repeat(maxBufferStdout + maxBufferStderr));244};245219test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', testAll, false);220test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', testAll, true);246test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', () => testAll(false));247test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', () => testAll(true));248222const testInvalidFd = async (t, fdName, execaMethod) => {223 const {message} = t.throws(() => {249const testInvalidFd = async (fdName, execaMethod) => {250 const {message} = assertThrows(() => {251 execaMethod('empty.js', {maxBuffer: {[fdName]: 0}});252 });226 t.true(message.includes(`"maxBuffer.${fdName}" is invalid`));253 assert.ok(message.includes(`"maxBuffer.${fdName}" is invalid`));254};255229test('maxBuffer.stdin is invalid', testInvalidFd, 'stdin', execa);230test('maxBuffer.fd0 is invalid', testInvalidFd, 'fd0', execa);231test('maxBuffer.other is invalid', testInvalidFd, 'other', execa);232test('maxBuffer.fd10 is invalid', testInvalidFd, 'fd10', execa);233test('maxBuffer.stdin is invalid, sync', testInvalidFd, 'stdin', execaSync);234test('maxBuffer.fd0 is invalid, sync', testInvalidFd, 'fd0', execaSync);235test('maxBuffer.other is invalid, sync', testInvalidFd, 'other', execaSync);236test('maxBuffer.fd10 is invalid, sync', testInvalidFd, 'fd10', execaSync);256test('maxBuffer.stdin is invalid', () => testInvalidFd('stdin', execa));257test('maxBuffer.fd0 is invalid', () => testInvalidFd('fd0', execa));258test('maxBuffer.other is invalid', () => testInvalidFd('other', execa));259test('maxBuffer.fd10 is invalid', () => testInvalidFd('fd10', execa));260test('maxBuffer.stdin is invalid, sync', () => testInvalidFd('stdin', execaSync));261test('maxBuffer.fd0 is invalid, sync', () => testInvalidFd('fd0', execaSync));262test('maxBuffer.other is invalid, sync', () => testInvalidFd('other', execaSync));263test('maxBuffer.fd10 is invalid, sync', () => testInvalidFd('fd10', execaSync));264265// These tests need the subprocess to have written its output before the timeout kills it, which is only guaranteed if the timeout leaves room for the subprocess to start. On a busy machine, starting Node.js can take over a second.266const SYNC_TIMEOUT = 1e4;267268// A file descriptor limit lower than `maxBuffer.stdout` does not stop the subprocess with synchronous methods, so the subprocess can still time out afterwards242const testMaxBufferTimeoutSync = (t, fdNumber, fdName) => {269const testMaxBufferTimeoutSync = (fdNumber, fdName) => {270 const length = 3;244 const error = t.throws(() => {271 const error = assertThrows(() => {272 execaSync('max-buffer-forever.js', [`${fdNumber}`, `${maxBuffer}`], {...fullStdio, timeout: SYNC_TIMEOUT, maxBuffer: {[fdName]: length}});273 }, {code: 'ETIMEDOUT'});247 t.true(error.timedOut);248 t.false(error.isMaxBuffer);249 t.is(error.maxBufferInfo, undefined);250 t.false(Object.hasOwn(error.cause, 'maxBufferInfo'));251 t.true(error.shortMessage.startsWith(`Command timed out after ${SYNC_TIMEOUT} milliseconds`));252 t.is(error.stdio[fdNumber], getExpectedOutput(length));274 assert.equal(error.timedOut, true);275 assert.equal(error.isMaxBuffer, false);276 assert.equal(error.maxBufferInfo, undefined);277 assert.ok(!Object.hasOwn(error.cause, 'maxBufferInfo'));278 assert.ok(error.shortMessage.startsWith(`Command timed out after ${SYNC_TIMEOUT} milliseconds`));279 assert.equal(error.stdio[fdNumber], getExpectedOutput(length));280};281255test('timeout is reported instead of maxBuffer.stderr, sync', testMaxBufferTimeoutSync, 2, 'stderr');256test('timeout is reported instead of maxBuffer.fd3, sync', testMaxBufferTimeoutSync, 3, 'fd3');282test('timeout is reported instead of maxBuffer.stderr, sync', () => testMaxBufferTimeoutSync(2, 'stderr'));283test('timeout is reported instead of maxBuffer.fd3, sync', () => testMaxBufferTimeoutSync(3, 'fd3'));284258test('timeout does not truncate output under maxBuffer.stderr, sync', t => {259 const {timedOut, isMaxBuffer, stderr} = t.throws(() => {285test('timeout does not truncate output under maxBuffer.stderr, sync', () => {286 const {timedOut, isMaxBuffer, stderr} = assertThrows(() => {287 execaSync('max-buffer-forever.js', ['2', `${maxBuffer}`], {timeout: SYNC_TIMEOUT, maxBuffer: {stderr: maxBuffer}});288 }, {code: 'ETIMEDOUT'});262 t.true(timedOut);263 t.false(isMaxBuffer);264 t.is(stderr, getExpectedOutput(maxBuffer));289 assert.equal(timedOut, true);290 assert.equal(isMaxBuffer, false);291 assert.equal(stderr, getExpectedOutput(maxBuffer));292});293294// `maxBuffer.stdout` is enforced by `spawnSync()` itself, which stops the subprocess before it can time out268test('maxBuffer.stdout is reported before timeout, sync', t => {295test('maxBuffer.stdout is reported before timeout, sync', () => {296 const length = 3;270 const error = t.throws(() => {297 const error = assertThrows(() => {298 execaSync('max-buffer-forever.js', ['1', `${maxBuffer}`], {timeout: SYNC_TIMEOUT, maxBuffer: {stdout: length}});299 }, maxBufferCodeSync);273 t.false(error.timedOut);274 t.true(error.isMaxBuffer);275 t.is(error.maxBufferInfo, undefined);276 assertErrorMessage(t, error.shortMessage, {execaMethod: execaSync, length});277 t.is(error.stdout, getExpectedOutput(length));300 assert.equal(error.timedOut, false);301 assert.equal(error.isMaxBuffer, true);302 assert.equal(error.maxBufferInfo, undefined);303 assertErrorMessage(error.shortMessage, {execaMethod: execaSync, length});304 assert.equal(error.stdout, getExpectedOutput(length));305});306280test('maxBuffer.stderr is reported with a non-zero exit code, sync', t => {307test('maxBuffer.stderr is reported with a non-zero exit code, sync', () => {308 const length = 3;282 const error = t.throws(() => {309 const error = assertThrows(() => {310 execaSync('noop-both-fail.js', ['.'.repeat(maxBuffer)], {maxBuffer: {stdout: 1e8, stderr: length}});311 });285 t.true(error.isMaxBuffer);286 t.is(error.maxBufferInfo, undefined);287 assertErrorMessage(t, error.shortMessage, {execaMethod: execaSync, fdNumber: 2, length});288 t.is(error.exitCode, 1);289 t.is(error.stdout, getExpectedOutput(maxBuffer));290 t.is(error.stderr, getExpectedOutput(length));312 assert.equal(error.isMaxBuffer, true);313 assert.equal(error.maxBufferInfo, undefined);314 assertErrorMessage(error.shortMessage, {execaMethod: execaSync, fdNumber: 2, length});315 assert.equal(error.exitCode, 1);316 assert.equal(error.stdout, getExpectedOutput(maxBuffer));317 assert.equal(error.stderr, getExpectedOutput(length));318});319293test('maxBuffer.stderr works with reject false, sync', t => {320test('maxBuffer.stderr works with reject false, sync', () => {321 const length = 3;322 const {failed, isMaxBuffer, maxBufferInfo, shortMessage, stderr} = execaSync('noop-fd.js', ['2', '.'.repeat(maxBuffer)], {maxBuffer: {stdout: 1e8, stderr: length}, reject: false});296 t.true(failed);297 t.true(isMaxBuffer);298 t.is(maxBufferInfo, undefined);299 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});300 t.is(stderr, getExpectedOutput(length));323 assert.equal(failed, true);324 assert.equal(isMaxBuffer, true);325 assert.equal(maxBufferInfo, undefined);326 assertErrorMessage(shortMessage, {execaMethod: execaSync, fdNumber: 2, length});327 assert.equal(stderr, getExpectedOutput(length));328});329303test('maxBuffer.stderr works with lines, sync', t => {330test('maxBuffer.stderr works with lines, sync', () => {331 const length = 3;305 const {isMaxBuffer, stderr} = t.throws(() => {332 const {isMaxBuffer, stderr} = assertThrows(() => {333 execaSync('noop-both.js', ['.'.repeat(maxBuffer)], {maxBuffer: {stdout: 1e8, stderr: length}, lines: true});334 }, maxBufferCodeSync);308 t.true(isMaxBuffer);309 t.deepEqual(stderr, [getExpectedOutput(length)]);335 assert.equal(isMaxBuffer, true);336 assert.deepEqual(stderr, [getExpectedOutput(length)]);337});338312test('maxBuffer.stdout is an upper bound for maxBuffer.stderr, sync', t => {339test('maxBuffer.stdout is an upper bound for maxBuffer.stderr, sync', () => {340 const length = 3;314 const {isMaxBuffer, shortMessage, stderr} = t.throws(() => {341 const {isMaxBuffer, shortMessage, stderr} = assertThrows(() => {342 execaSync('noop-fd.js', ['2', '.'.repeat(maxBuffer)], {maxBuffer: {stdout: length, stderr: 1e8}});343 }, maxBufferCodeSync);317 t.true(isMaxBuffer);318 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, fdNumber: 2, length});319 t.is(stderr, getExpectedOutput(length));344 assert.equal(isMaxBuffer, true);345 assertErrorMessage(shortMessage, {execaMethod: execaSync, fdNumber: 2, length});346 assert.equal(stderr, getExpectedOutput(length));347});348322test('maxBuffer.stderr is not reported on spawn errors, sync', t => {323 const {code, isMaxBuffer} = t.throws(() => {349test('maxBuffer.stderr is not reported on spawn errors, sync', () => {350 const {code, isMaxBuffer} = assertThrows(() => {351 execaSync('non-existent-command', {maxBuffer: {stderr: 1}});352 });326 t.is(code, 'ENOENT');327 t.false(isMaxBuffer);353 assert.equal(code, 'ENOENT');354 assert.equal(isMaxBuffer, false);355});356330const testMaxBufferEncoding = async (t, execaMethod, fdNumber) => {331 const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {encoding: 'buffer'});332 assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, unit: 'bytes'});357const testMaxBufferEncoding = async (execaMethod, fdNumber) => {358 const {shortMessage, stdio} = await runMaxBuffer(execaMethod, fdNumber, {encoding: 'buffer'});359 assertErrorMessage(shortMessage, {execaMethod, fdNumber, unit: 'bytes'});360 const stream = stdio[fdNumber];334 t.true(stream instanceof Uint8Array);335 t.is(Buffer.from(stream).toString(), getExpectedOutput());361 assert.ok(stream instanceof Uint8Array);362 assert.equal(Buffer.from(stream).toString(), getExpectedOutput());363};364338test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, execa, 1);339test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, execa, 2);340test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, execa, 3);341test('maxBuffer works with encoding buffer and stdout, sync', testMaxBufferEncoding, execaSync, 1);342test('maxBuffer works with encoding buffer and stderr, sync', testMaxBufferEncoding, execaSync, 2);343test('maxBuffer works with encoding buffer and stdio[*], sync', testMaxBufferEncoding, execaSync, 3);365test('maxBuffer works with encoding buffer and stdout', () => testMaxBufferEncoding(execa, 1));366test('maxBuffer works with encoding buffer and stderr', () => testMaxBufferEncoding(execa, 2));367test('maxBuffer works with encoding buffer and stdio[*]', () => testMaxBufferEncoding(execa, 3));368test('maxBuffer works with encoding buffer and stdout, sync', () => testMaxBufferEncoding(execaSync, 1));369test('maxBuffer works with encoding buffer and stderr, sync', () => testMaxBufferEncoding(execaSync, 2));370test('maxBuffer works with encoding buffer and stdio[*], sync', () => testMaxBufferEncoding(execaSync, 3));371345const testMaxBufferHex = async (t, fdNumber) => {372const testMaxBufferHex = async fdNumber => {373 const length = maxBuffer / 2;347 const {shortMessage, stdio} = await runMaxBuffer(t, execa, fdNumber, {length, encoding: 'hex'});348 assertErrorMessage(t, shortMessage, {fdNumber});349 t.is(stdio[fdNumber], Buffer.from(getExpectedOutput(length)).toString('hex'));374 const {shortMessage, stdio} = await runMaxBuffer(execa, fdNumber, {length, encoding: 'hex'});375 assertErrorMessage(shortMessage, {fdNumber});376 assert.equal(stdio[fdNumber], Buffer.from(getExpectedOutput(length)).toString('hex'));377};378352test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);353test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);354test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);379test('maxBuffer works with other encodings and stdout', () => testMaxBufferHex(1));380test('maxBuffer works with other encodings and stderr', () => testMaxBufferHex(2));381test('maxBuffer works with other encodings and stdio[*]', () => testMaxBufferHex(3));382356const testMaxBufferHexSync = async (t, fdNumber) => {383const testMaxBufferHexSync = async fdNumber => {384 const length = maxBuffer / 2;385 const {isMaxBuffer, stdio} = await getMaxBufferSubprocess(execaSync, fdNumber, {length, encoding: 'hex'});359 t.false(isMaxBuffer);360 t.is(stdio[fdNumber], Buffer.from(getExpectedOutput(length + 1)).toString('hex'));386 assert.equal(isMaxBuffer, false);387 assert.equal(stdio[fdNumber], Buffer.from(getExpectedOutput(length + 1)).toString('hex'));388};389363test('maxBuffer ignores other encodings and stdout, sync', testMaxBufferHexSync, 1);364test('maxBuffer ignores other encodings and stderr, sync', testMaxBufferHexSync, 2);365test('maxBuffer ignores other encodings and stdio[*], sync', testMaxBufferHexSync, 3);390test('maxBuffer ignores other encodings and stdout, sync', () => testMaxBufferHexSync(1));391test('maxBuffer ignores other encodings and stderr, sync', () => testMaxBufferHexSync(2));392test('maxBuffer ignores other encodings and stdio[*], sync', () => testMaxBufferHexSync(3));393367const testNoMaxBuffer = async (t, fdNumber, buffer) => {394const testNoMaxBuffer = async (fdNumber, buffer) => {395 const subprocess = getMaxBufferSubprocess(execa, fdNumber, {buffer});396 const [{isMaxBuffer, stdio}, output] = await Promise.all([397 subprocess,398 getStream(subprocess.stdio[fdNumber]),399 ]);373 t.false(isMaxBuffer);374 t.is(stdio[fdNumber], undefined);375 t.is(output, getExpectedOutput(maxBuffer + 1));400 assert.equal(isMaxBuffer, false);401 assert.equal(stdio[fdNumber], undefined);402 assert.equal(output, getExpectedOutput(maxBuffer + 1));403};404378test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1, false);379test('do not buffer stdout when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 1, {stdout: false});380test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2, false);381test('do not buffer stderr when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 2, {stderr: false});382test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3, false);383test('do not buffer stdio[*] when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 3, {fd3: false});405test('do not buffer stdout when `buffer` set to `false`', () => testNoMaxBuffer(1, false));406test('do not buffer stdout when `buffer` set to `false`, fd-specific', () => testNoMaxBuffer(1, {stdout: false}));407test('do not buffer stderr when `buffer` set to `false`', () => testNoMaxBuffer(2, false));408test('do not buffer stderr when `buffer` set to `false`, fd-specific', () => testNoMaxBuffer(2, {stderr: false}));409test('do not buffer stdio[*] when `buffer` set to `false`', () => testNoMaxBuffer(3, false));410test('do not buffer stdio[*] when `buffer` set to `false`, fd-specific', () => testNoMaxBuffer(3, {fd3: false}));411385const testNoMaxBufferSync = (t, fdNumber, buffer) => {412const testNoMaxBufferSync = (fdNumber, buffer) => {413 const {isMaxBuffer, stdio} = getMaxBufferSubprocess(execaSync, fdNumber, {buffer});387 t.false(isMaxBuffer);388 t.is(stdio[fdNumber], undefined);414 assert.equal(isMaxBuffer, false);415 assert.equal(stdio[fdNumber], undefined);416};417418// @todo: add tests for fd3 once the following Node.js bug is fixed.419// https://github.com/nodejs/node/issues/52422393test('do not buffer stdout when `buffer` set to `false`, sync', testNoMaxBufferSync, 1, false);394test('do not buffer stdout when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 1, {stdout: false});395test('do not buffer stderr when `buffer` set to `false`, sync', testNoMaxBufferSync, 2, false);396test('do not buffer stderr when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 2, {stderr: false});420test('do not buffer stdout when `buffer` set to `false`, sync', () => testNoMaxBufferSync(1, false));421test('do not buffer stdout when `buffer` set to `false`, fd-specific, sync', () => testNoMaxBufferSync(1, {stdout: false}));422test('do not buffer stderr when `buffer` set to `false`, sync', () => testNoMaxBufferSync(2, false));423test('do not buffer stderr when `buffer` set to `false`, fd-specific, sync', () => testNoMaxBufferSync(2, {stderr: false}));424398const testNoMaxBufferSyncObjectPipe = (t, fdNumber, fdName, stdioOption) => {425const testNoMaxBufferSyncObjectPipe = (fdNumber, fdName, stdioOption) => {426 const {isMaxBuffer, stdio} = execaSync('max-buffer.js', [`${fdNumber}`, `${maxBuffer + 1}`], {427 [fdName]: stdioOption,428 buffer: false,429 maxBuffer,430 });404 t.false(isMaxBuffer);405 t.is(stdio[fdNumber], undefined);431 assert.equal(isMaxBuffer, false);432 assert.equal(stdio[fdNumber], undefined);433};434408test('do not buffer stdout object pipe when `buffer` set to `false`, sync', testNoMaxBufferSyncObjectPipe, 1, 'stdout', {value: 'pipe'});409test('do not buffer stdout object pipe with input false when `buffer` set to `false`, sync', testNoMaxBufferSyncObjectPipe, 1, 'stdout', {value: 'pipe', input: false});410test('do not buffer stdout object pipe with input true when `buffer` set to `false`, sync', testNoMaxBufferSyncObjectPipe, 1, 'stdout', {value: 'pipe', input: true});411test('do not buffer stderr object pipe with input true when `buffer` set to `false`, sync', testNoMaxBufferSyncObjectPipe, 2, 'stderr', {value: 'pipe', input: true});435test('do not buffer stdout object pipe when `buffer` set to `false`, sync', () => testNoMaxBufferSyncObjectPipe(1, 'stdout', {value: 'pipe'}));436test('do not buffer stdout object pipe with input false when `buffer` set to `false`, sync', () => testNoMaxBufferSyncObjectPipe(1, 'stdout', {value: 'pipe', input: false}));437test('do not buffer stdout object pipe with input true when `buffer` set to `false`, sync', () => testNoMaxBufferSyncObjectPipe(1, 'stdout', {value: 'pipe', input: true}));438test('do not buffer stderr object pipe with input true when `buffer` set to `false`, sync', () => testNoMaxBufferSyncObjectPipe(2, 'stderr', {value: 'pipe', input: true}));439413const testMaxBufferAbort = async (t, fdNumber) => {440const testMaxBufferAbort = async fdNumber => {441 const subprocess = getMaxBufferSubprocess(execa, fdNumber);442 const [{isMaxBuffer, shortMessage}] = await Promise.all([416 t.throwsAsync(subprocess, maxBufferMessage),417 t.throwsAsync(getStream(subprocess.stdio[fdNumber]), {code: 'ERR_STREAM_PREMATURE_CLOSE'}),443 assertRejects(subprocess, maxBufferMessage),444 assertRejects(getStream(subprocess.stdio[fdNumber]), {code: 'ERR_STREAM_PREMATURE_CLOSE'}),445 ]);419 t.true(isMaxBuffer);420 assertErrorMessage(t, shortMessage, {execaMethod: execa, fdNumber});446 assert.equal(isMaxBuffer, true);447 assertErrorMessage(shortMessage, {execaMethod: execa, fdNumber});448};449423test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);424test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);425test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);450test('abort stream when hitting maxBuffer with stdout', () => testMaxBufferAbort(1));451test('abort stream when hitting maxBuffer with stderr', () => testMaxBufferAbort(2));452test('abort stream when hitting maxBuffer with stdio[*]', () => testMaxBufferAbort(3));453427test('error.isMaxBuffer is false on early errors', async t => {454test('error.isMaxBuffer is false on early errors', async () => {455 const {failed, isMaxBuffer} = await getEarlyErrorSubprocess({reject: false, maxBuffer: 1});429 t.true(failed);430 t.false(isMaxBuffer);456 assert.equal(failed, true);457 assert.equal(isMaxBuffer, false);458});459433test('maxBuffer works with result.ipcOutput', async t => {460test('maxBuffer works with result.ipcOutput', async () => {461 const {462 isMaxBuffer,463 shortMessage,464 message,465 stderr,466 ipcOutput,440 } = await t.throwsAsync(execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: 1}}));441 t.true(isMaxBuffer);442 t.is(shortMessage, 'Command\'s IPC output was larger than 1 messages: ipc-send-twice.js\nmaxBuffer exceeded');443 t.true(message.endsWith(`\n\n${foobarArray[0]}`));444 t.is(stderr, '');445 t.deepEqual(ipcOutput, [foobarArray[0]]);467 } = await assertRejects(execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: 1}}));468 assert.equal(isMaxBuffer, true);469 assert.equal(shortMessage, 'Command\'s IPC output was larger than 1 messages: ipc-send-twice.js\nmaxBuffer exceeded');470 assert.ok(message.endsWith(`\n\n${foobarArray[0]}`));471 assert.equal(stderr, '');472 assert.deepEqual(ipcOutput, [foobarArray[0]]);473});474448test('maxBuffer is ignored with result.ipcOutput if buffer is false', async t => {475test('maxBuffer is ignored with result.ipcOutput if buffer is false', async () => {476 const {ipcOutput} = await execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: 1}, buffer: false});450 t.deepEqual(ipcOutput, []);477 assert.deepEqual(ipcOutput, []);478});479480/*481`result.ipcOutput` is counted in messages, which are indivisible, so any `maxBuffer` value the count cannot land on exactly must still be enforced.482The threshold is hit as soon as buffering one more message would exceed it, which is how the stream-based `maxBuffer` behaves too.483*/457const testIpcMaxBufferValue = async (t, maxBuffer, expectedOutput) => {458 const {isMaxBuffer, ipcOutput} = await t.throwsAsync(execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: maxBuffer}}));459 t.true(isMaxBuffer);460 t.deepEqual(ipcOutput, expectedOutput);484const testIpcMaxBufferValue = async (maxBuffer, expectedOutput) => {485 const {isMaxBuffer, ipcOutput} = await assertRejects(execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: maxBuffer}}));486 assert.equal(isMaxBuffer, true);487 assert.deepEqual(ipcOutput, expectedOutput);488};489463test('maxBuffer works with result.ipcOutput, negative', testIpcMaxBufferValue, -1, []);464test('maxBuffer works with result.ipcOutput, 0', testIpcMaxBufferValue, 0, []);465test('maxBuffer works with result.ipcOutput, below 1', testIpcMaxBufferValue, 0.5, []);466test('maxBuffer works with result.ipcOutput, 1', testIpcMaxBufferValue, 1, [foobarArray[0]]);467test('maxBuffer works with result.ipcOutput, fractional', testIpcMaxBufferValue, 1.5, [foobarArray[0]]);490test('maxBuffer works with result.ipcOutput, negative', () => testIpcMaxBufferValue(-1, []));491test('maxBuffer works with result.ipcOutput, 0', () => testIpcMaxBufferValue(0, []));492test('maxBuffer works with result.ipcOutput, below 1', () => testIpcMaxBufferValue(0.5, []));493test('maxBuffer works with result.ipcOutput, 1', () => testIpcMaxBufferValue(1, [foobarArray[0]]));494test('maxBuffer works with result.ipcOutput, fractional', () => testIpcMaxBufferValue(1.5, [foobarArray[0]]));495469const testIpcMaxBufferNotHit = async (t, maxBuffer) => {496const testIpcMaxBufferNotHit = async maxBuffer => {497 const {isMaxBuffer, ipcOutput} = await execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: maxBuffer}});471 t.false(isMaxBuffer);472 t.deepEqual(ipcOutput, foobarArray);498 assert.equal(isMaxBuffer, false);499 assert.deepEqual(ipcOutput, foobarArray);500};501475test('maxBuffer is not hit with result.ipcOutput, exact count', testIpcMaxBufferNotHit, 2);476test('maxBuffer is not hit with result.ipcOutput, fractional', testIpcMaxBufferNotHit, 2.5);502test('maxBuffer is not hit with result.ipcOutput, exact count', () => testIpcMaxBufferNotHit(2));503test('maxBuffer is not hit with result.ipcOutput, fractional', () => testIpcMaxBufferNotHit(2.5));504505// The same `maxBuffer` value must be interpreted the same way whether the output is buffered as messages or as characters479const testIpcMaxBufferLikeStream = async (t, maxBuffer) => {506const testIpcMaxBufferLikeStream = async maxBuffer => {507 const [ipcResult, streamResult] = await Promise.all([508 execa('ipc-send-twice.js', {ipc: true, maxBuffer: {ipc: maxBuffer}, reject: false}),509 execa('noop-fd.js', ['1', 'ab'], {maxBuffer, reject: false}),510 ]);484 t.is(ipcResult.isMaxBuffer, streamResult.isMaxBuffer);485 t.is(ipcResult.ipcOutput.length, streamResult.stdout.length);511 assert.equal(ipcResult.isMaxBuffer, streamResult.isMaxBuffer);512 assert.equal(ipcResult.ipcOutput.length, streamResult.stdout.length);513};514488test('maxBuffer with result.ipcOutput matches stdout, 0.5', testIpcMaxBufferLikeStream, 0.5);489test('maxBuffer with result.ipcOutput matches stdout, 1', testIpcMaxBufferLikeStream, 1);490test('maxBuffer with result.ipcOutput matches stdout, 1.5', testIpcMaxBufferLikeStream, 1.5);491test('maxBuffer with result.ipcOutput matches stdout, 2', testIpcMaxBufferLikeStream, 2);515test('maxBuffer with result.ipcOutput matches stdout, 0.5', () => testIpcMaxBufferLikeStream(0.5));516test('maxBuffer with result.ipcOutput matches stdout, 1', () => testIpcMaxBufferLikeStream(1));517test('maxBuffer with result.ipcOutput matches stdout, 1.5', () => testIpcMaxBufferLikeStream(1.5));518test('maxBuffer with result.ipcOutput matches stdout, 2', () => testIpcMaxBufferLikeStream(2));
modified:test/io/output-async.js+23 added-22 removed
1import assert from 'node:assert/strict';2import {once, defaultMaxListeners} from 'node:events';3import process from 'node:process';4import {setImmediate} from 'node:timers/promises';4import test from 'ava';5import test from 'node:test';6import {execa} from '../../index.js';7import {STANDARD_STREAMS} from '../helpers/stdio.js';8import {foobarString} from '../helpers/input.js';9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';
12 unmodified lines
22});2324const onStdinRemoveListener = () => once(process.stdin, 'removeListener');2525const testListenersCleanup = async (t, isMultiple) => {26const testListenersCleanup = async isMultiple => {27 const streamsPreviousListeners = getStandardStreamsListeners();28 const subprocess = execa('empty.js', getComplexStdio(isMultiple));28 t.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);29 assert.notDeepEqual(getStandardStreamsListeners(), streamsPreviousListeners);30 await Promise.all([subprocess, onStdinRemoveListener()]);31 if (isMultiple) {32 await onStdinRemoveListener();33 }3435 for (const [fdNumber, streamNewListeners] of Object.entries(getStandardStreamsListeners())) {36 const defaultListeners = Object.fromEntries(Reflect.ownKeys(streamNewListeners).map(eventName => [eventName, []]));36 t.deepEqual(streamNewListeners, {...defaultListeners, ...streamsPreviousListeners[fdNumber]});37 assert.deepEqual(streamNewListeners, {...defaultListeners, ...streamsPreviousListeners[fdNumber]});38 }39};4040test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);41test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);41test('process.std* listeners are cleaned up on success with a single input', () => testListenersCleanup(false));42test('process.std* listeners are cleaned up on success with multiple inputs', () => testListenersCleanup(true));4343test.serial('Can spawn many subprocesses in parallel', async t => {44test('Can spawn many subprocesses in parallel', async () => {45 const results = await Promise.all(Array.from({length: PARALLEL_COUNT}, () => execa('noop.js', [foobarString])));45 t.true(results.every(({stdout}) => stdout === foobarString));46 assert.ok(results.every(({stdout}) => stdout === foobarString));47});4848const testMaxListeners = async (t, isMultiple, maxListenersCount) => {49 const checkMaxListeners = assertMaxListeners(t);49const testMaxListeners = async (isMultiple, maxListenersCount) => {50 const checkMaxListeners = assertMaxListeners();5152 for (const standardStream of STANDARD_STREAMS) {53 standardStream.setMaxListeners(maxListenersCount);54 }5556 try {57 const results = await Promise.all(Array.from({length: PARALLEL_COUNT}, () => execa('empty.js', getComplexStdio(isMultiple))));57 t.true(results.every(({exitCode}) => exitCode === 0));58 assert.ok(results.every(({exitCode}) => exitCode === 0));59 } finally {60 await setImmediate();61 await setImmediate();62 checkMaxListeners();6364 for (const standardStream of STANDARD_STREAMS) {64 t.is(standardStream.getMaxListeners(), maxListenersCount);65 assert.equal(standardStream.getMaxListeners(), maxListenersCount);66 standardStream.setMaxListeners(defaultMaxListeners);67 }68 }69};7070test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);71test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);72test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);73test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Infinity);74test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);75test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);76test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);77test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);78test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Infinity);79test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);71test('No warning with maxListeners 1 and ["pipe", "inherit"]', () => testMaxListeners(false, 1));72test('No warning with maxListeners default and ["pipe", "inherit"]', () => testMaxListeners(false, defaultMaxListeners));73test('No warning with maxListeners 100 and ["pipe", "inherit"]', () => testMaxListeners(false, 100));74test('No warning with maxListeners Infinity and ["pipe", "inherit"]', () => testMaxListeners(false, Infinity));75test('No warning with maxListeners 0 and ["pipe", "inherit"]', () => testMaxListeners(false, 0));76test('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, 1));77test('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, defaultMaxListeners));78test('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, 100));79test('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, Infinity));80test('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, 0));
modified:test/io/output-sync.js+14 added-12 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows} from '../helpers/assert.js';4import {execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {throwingGenerator} from '../helpers/generator.js';7import {foobarString} from '../helpers/input.js';89setFixtureDirectory();109test('Handles errors with stdout generator, sync', t => {11test('Handles errors with stdout generator, sync', () => {12 const cause = new Error(foobarString);11 const error = t.throws(() => {13 const error = assertThrows(() => {14 execaSync('noop.js', {stdout: throwingGenerator(cause)()});15 });14 t.is(error.cause, cause);16 assert.equal(error.cause, cause);17});1817test('Handles errors with stdout generator, spawn failure, sync', t => {19test('Handles errors with stdout generator, spawn failure, sync', () => {20 const cause = new Error(foobarString);19 const error = t.throws(() => {21 const error = assertThrows(() => {22 execaSync('noop.js', {cwd: 'does_not_exist', stdout: throwingGenerator(cause)()});23 });22 t.true(error.failed);23 t.is(error.cause.code, 'ENOENT');24 assert.equal(error.failed, true);25 assert.equal(error.cause.code, 'ENOENT');26});2726test('Handles errors with stdout generator, subprocess failure, sync', t => {28test('Handles errors with stdout generator, subprocess failure, sync', () => {29 const cause = new Error(foobarString);28 const error = t.throws(() => {30 const error = assertThrows(() => {31 execaSync('noop-fail.js', ['1'], {stdout: throwingGenerator(cause)()});32 });31 t.true(error.failed);32 t.is(error.cause, cause);33 assert.equal(error.failed, true);34 assert.equal(error.cause, cause);35});
modified:test/io/pipeline.js+22 added-20 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects, assertLike} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';89setFixtureDirectory();109const testDestroyStandard = async (t, fdNumber) => {11const testDestroyStandard = async fdNumber => {12 const subprocess = execa('forever.js', {...getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']), timeout: 1});11 await t.throwsAsync(subprocess, {message: /timed out/});12 t.false(STANDARD_STREAMS[fdNumber].destroyed);13 await assertRejects(subprocess, {message: /timed out/});14 assert.ok(!STANDARD_STREAMS[fdNumber].destroyed);15};1615test('Does not destroy process.stdin on subprocess errors', testDestroyStandard, 0);16test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);17test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);17test('Does not destroy process.stdin on subprocess errors', () => testDestroyStandard(0));18test('Does not destroy process.stdout on subprocess errors', () => testDestroyStandard(1));19test('Does not destroy process.stderr on subprocess errors', () => testDestroyStandard(2));2019const testDestroyStandardSpawn = async (t, fdNumber) => {20 const error = await t.throwsAsync(getEarlyErrorSubprocess(getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe'])));21 t.like(error, expectedEarlyError);22 t.false(STANDARD_STREAMS[fdNumber].destroyed);21const testDestroyStandardSpawn = async fdNumber => {22 const error = await assertRejects(getEarlyErrorSubprocess(getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe'])));23 assertLike(error, expectedEarlyError);24 assert.ok(!STANDARD_STREAMS[fdNumber].destroyed);25};2625test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);26test('Does not destroy process.stdout on subprocess early errors', testDestroyStandardSpawn, 1);27test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);27test('Does not destroy process.stdin on subprocess early errors', () => testDestroyStandardSpawn(0));28test('Does not destroy process.stdout on subprocess early errors', () => testDestroyStandardSpawn(1));29test('Does not destroy process.stderr on subprocess early errors', () => testDestroyStandardSpawn(2));3029const testDestroyStandardStream = async (t, fdNumber) => {31const testDestroyStandardStream = async fdNumber => {32 const subprocess = execa('forever.js', getStdio(fdNumber, [STANDARD_STREAMS[fdNumber], 'pipe']));33 const cause = new Error('test');34 subprocess.stdio[fdNumber].destroy(cause);35 subprocess.kill();34 t.like(await t.throwsAsync(subprocess), {cause});35 t.false(STANDARD_STREAMS[fdNumber].destroyed);36 assertLike(await assertRejects(subprocess), {cause});37 assert.ok(!STANDARD_STREAMS[fdNumber].destroyed);38};3938test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);39test('Does not destroy process.stdout on stream subprocess errors', testDestroyStandardStream, 1);40test('Does not destroy process.stderr on stream subprocess errors', testDestroyStandardStream, 2);40test('Does not destroy process.stdin on stream subprocess errors', () => testDestroyStandardStream(0));41test('Does not destroy process.stdout on stream subprocess errors', () => testDestroyStandardStream(1));42test('Does not destroy process.stderr on stream subprocess errors', () => testDestroyStandardStream(2));
modified:test/io/strip-newline.js+42 added-42 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa, execaSync} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {fullStdio} from '../helpers/stdio.js';6import {noopGenerator} from '../helpers/generator.js';7import {foobarString} from '../helpers/input.js';89setFixtureDirectory();1010// eslint-disable-next-line max-params11const testStripFinalNewline = async (t, fdNumber, stripFinalNewline, shouldStrip, execaMethod) => {11const testStripFinalNewline = async (fdNumber, stripFinalNewline, shouldStrip, execaMethod) => {12 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, `${foobarString}\n`], {...fullStdio, stripFinalNewline});13 t.is(stdio[fdNumber], `${foobarString}${shouldStrip ? '' : '\n'}`);13 assert.equal(stdio[fdNumber], `${foobarString}${shouldStrip ? '' : '\n'}`);14};1516test('stripFinalNewline: default with stdout', testStripFinalNewline, 1, undefined, true, execa);17test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, true, execa);18test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, false, execa);19test('stripFinalNewline: default with stderr', testStripFinalNewline, 2, undefined, true, execa);20test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, true, execa);21test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, false, execa);22test('stripFinalNewline: default with stdio[*]', testStripFinalNewline, 3, undefined, true, execa);23test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, true, execa);24test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, false, execa);25test('stripFinalNewline: default with stdout, fd-specific', testStripFinalNewline, 1, {}, true, execa);26test('stripFinalNewline: true with stdout, fd-specific', testStripFinalNewline, 1, {stdout: true}, true, execa);27test('stripFinalNewline: false with stdout, fd-specific', testStripFinalNewline, 1, {stdout: false}, false, execa);28test('stripFinalNewline: default with stderr, fd-specific', testStripFinalNewline, 2, {}, true, execa);29test('stripFinalNewline: true with stderr, fd-specific', testStripFinalNewline, 2, {stderr: true}, true, execa);30test('stripFinalNewline: false with stderr, fd-specific', testStripFinalNewline, 2, {stderr: false}, false, execa);31test('stripFinalNewline: default with stdio[*], fd-specific', testStripFinalNewline, 3, {}, true, execa);32test('stripFinalNewline: true with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: true}, true, execa);33test('stripFinalNewline: false with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: false}, false, execa);34test('stripFinalNewline: default with stdout, sync', testStripFinalNewline, 1, undefined, true, execaSync);35test('stripFinalNewline: true with stdout, sync', testStripFinalNewline, 1, true, true, execaSync);36test('stripFinalNewline: false with stdout, sync', testStripFinalNewline, 1, false, false, execaSync);37test('stripFinalNewline: default with stderr, sync', testStripFinalNewline, 2, undefined, true, execaSync);38test('stripFinalNewline: true with stderr, sync', testStripFinalNewline, 2, true, true, execaSync);39test('stripFinalNewline: false with stderr, sync', testStripFinalNewline, 2, false, false, execaSync);40test('stripFinalNewline: default with stdio[*], sync', testStripFinalNewline, 3, undefined, true, execaSync);41test('stripFinalNewline: true with stdio[*], sync', testStripFinalNewline, 3, true, true, execaSync);42test('stripFinalNewline: false with stdio[*], sync', testStripFinalNewline, 3, false, false, execaSync);43test('stripFinalNewline: default with stdout, fd-specific, sync', testStripFinalNewline, 1, {}, true, execaSync);44test('stripFinalNewline: true with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: true}, true, execaSync);45test('stripFinalNewline: false with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: false}, false, execaSync);46test('stripFinalNewline: default with stderr, fd-specific, sync', testStripFinalNewline, 2, {}, true, execaSync);47test('stripFinalNewline: true with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: true}, true, execaSync);48test('stripFinalNewline: false with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: false}, false, execaSync);49test('stripFinalNewline: default with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {}, true, execaSync);50test('stripFinalNewline: true with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: true}, true, execaSync);51test('stripFinalNewline: false with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: false}, false, execaSync);16test('stripFinalNewline: default with stdout', () => testStripFinalNewline(1, undefined, true, execa));17test('stripFinalNewline: true with stdout', () => testStripFinalNewline(1, true, true, execa));18test('stripFinalNewline: false with stdout', () => testStripFinalNewline(1, false, false, execa));19test('stripFinalNewline: default with stderr', () => testStripFinalNewline(2, undefined, true, execa));20test('stripFinalNewline: true with stderr', () => testStripFinalNewline(2, true, true, execa));21test('stripFinalNewline: false with stderr', () => testStripFinalNewline(2, false, false, execa));22test('stripFinalNewline: default with stdio[*]', () => testStripFinalNewline(3, undefined, true, execa));23test('stripFinalNewline: true with stdio[*]', () => testStripFinalNewline(3, true, true, execa));24test('stripFinalNewline: false with stdio[*]', () => testStripFinalNewline(3, false, false, execa));25test('stripFinalNewline: default with stdout, fd-specific', () => testStripFinalNewline(1, {}, true, execa));26test('stripFinalNewline: true with stdout, fd-specific', () => testStripFinalNewline(1, {stdout: true}, true, execa));27test('stripFinalNewline: false with stdout, fd-specific', () => testStripFinalNewline(1, {stdout: false}, false, execa));28test('stripFinalNewline: default with stderr, fd-specific', () => testStripFinalNewline(2, {}, true, execa));29test('stripFinalNewline: true with stderr, fd-specific', () => testStripFinalNewline(2, {stderr: true}, true, execa));30test('stripFinalNewline: false with stderr, fd-specific', () => testStripFinalNewline(2, {stderr: false}, false, execa));31test('stripFinalNewline: default with stdio[*], fd-specific', () => testStripFinalNewline(3, {}, true, execa));32test('stripFinalNewline: true with stdio[*], fd-specific', () => testStripFinalNewline(3, {fd3: true}, true, execa));33test('stripFinalNewline: false with stdio[*], fd-specific', () => testStripFinalNewline(3, {fd3: false}, false, execa));34test('stripFinalNewline: default with stdout, sync', () => testStripFinalNewline(1, undefined, true, execaSync));35test('stripFinalNewline: true with stdout, sync', () => testStripFinalNewline(1, true, true, execaSync));36test('stripFinalNewline: false with stdout, sync', () => testStripFinalNewline(1, false, false, execaSync));37test('stripFinalNewline: default with stderr, sync', () => testStripFinalNewline(2, undefined, true, execaSync));38test('stripFinalNewline: true with stderr, sync', () => testStripFinalNewline(2, true, true, execaSync));39test('stripFinalNewline: false with stderr, sync', () => testStripFinalNewline(2, false, false, execaSync));40test('stripFinalNewline: default with stdio[*], sync', () => testStripFinalNewline(3, undefined, true, execaSync));41test('stripFinalNewline: true with stdio[*], sync', () => testStripFinalNewline(3, true, true, execaSync));42test('stripFinalNewline: false with stdio[*], sync', () => testStripFinalNewline(3, false, false, execaSync));43test('stripFinalNewline: default with stdout, fd-specific, sync', () => testStripFinalNewline(1, {}, true, execaSync));44test('stripFinalNewline: true with stdout, fd-specific, sync', () => testStripFinalNewline(1, {stdout: true}, true, execaSync));45test('stripFinalNewline: false with stdout, fd-specific, sync', () => testStripFinalNewline(1, {stdout: false}, false, execaSync));46test('stripFinalNewline: default with stderr, fd-specific, sync', () => testStripFinalNewline(2, {}, true, execaSync));47test('stripFinalNewline: true with stderr, fd-specific, sync', () => testStripFinalNewline(2, {stderr: true}, true, execaSync));48test('stripFinalNewline: false with stderr, fd-specific, sync', () => testStripFinalNewline(2, {stderr: false}, false, execaSync));49test('stripFinalNewline: default with stdio[*], fd-specific, sync', () => testStripFinalNewline(3, {}, true, execaSync));50test('stripFinalNewline: true with stdio[*], fd-specific, sync', () => testStripFinalNewline(3, {fd3: true}, true, execaSync));51test('stripFinalNewline: false with stdio[*], fd-specific, sync', () => testStripFinalNewline(3, {fd3: false}, false, execaSync));5253test('stripFinalNewline is not used in objectMode', async t => {53test('stripFinalNewline is not used in objectMode', async () => {54 const {stdout} = await execa('noop-fd.js', ['1', `${foobarString}\n`], {stripFinalNewline: true, stdout: noopGenerator(true, false, true)});55 t.deepEqual(stdout, [`${foobarString}\n`]);55 assert.deepEqual(stdout, [`${foobarString}\n`]);56});
modified:test/ipc/buffer-messages.js+41 added-39 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows, assertRejects} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString, foobarArray} from '../helpers/input.js';7import {PARALLEL_COUNT} from '../helpers/parallel.js';8import {fullStdio} from '../helpers/stdio.js';910setFixtureDirectory();1110const testResultIpc = async (t, options) => {12const testResultIpc = async options => {13 const {ipcOutput} = await execa('ipc-send-twice.js', {...options, ipc: true});12 t.deepEqual(ipcOutput, foobarArray);14 assert.deepEqual(ipcOutput, foobarArray);15};1615test('Sets result.ipcOutput', testResultIpc, {});16test('Sets result.ipcOutput, fd-specific buffer', testResultIpc, {buffer: {stdout: false}});17test('Sets result.ipcOutput', () => testResultIpc({}));18test('Sets result.ipcOutput, fd-specific buffer', () => testResultIpc({buffer: {stdout: false}}));1918const testResultNoBuffer = async (t, options) => {20const testResultNoBuffer = async options => {21 const {ipcOutput} = await execa('ipc-send.js', {...options, ipc: true});20 t.deepEqual(ipcOutput, []);22 assert.deepEqual(ipcOutput, []);23};2423test('Sets empty result.ipcOutput if buffer is false', testResultNoBuffer, {buffer: false});24test('Sets empty result.ipcOutput if buffer is false, fd-specific buffer', testResultNoBuffer, {buffer: {ipc: false}});25test('Sets empty result.ipcOutput if buffer is false', () => testResultNoBuffer({buffer: false}));26test('Sets empty result.ipcOutput if buffer is false, fd-specific buffer', () => testResultNoBuffer({buffer: {ipc: false}}));2726test('buffer.fd3 is invalid without stdio[3], even with ipc', t => {27 const {message} = t.throws(() => {28test('buffer.fd3 is invalid without stdio[3], even with ipc', () => {29 const {message} = assertThrows(() => {30 execa('ipc-send-twice.js', {ipc: true, buffer: {fd3: false}});31 });30 t.true(message.includes('"buffer.fd3" is invalid: that file descriptor does not exist.'));32 assert.ok(message.includes('"buffer.fd3" is invalid: that file descriptor does not exist.'));33});3433test('buffer.fd3 does not affect result.ipcOutput', async t => {35test('buffer.fd3 does not affect result.ipcOutput', async () => {36 const {ipcOutput} = await execa('ipc-send-twice.js', {ipc: true, buffer: {fd3: false}, ...fullStdio});35 t.deepEqual(ipcOutput, foobarArray);37 assert.deepEqual(ipcOutput, foobarArray);38});3938test('Can use IPC methods when buffer is false', async t => {40test('Can use IPC methods when buffer is false', async () => {41 const subprocess = execa('ipc-send.js', {ipc: true, buffer: false});40 t.is(await subprocess.getOneMessage(), foobarString);42 assert.equal(await subprocess.getOneMessage(), foobarString);43 const {ipcOutput} = await subprocess;42 t.deepEqual(ipcOutput, []);44 assert.deepEqual(ipcOutput, []);45});4645test('Sets empty result.ipcOutput if ipc is false', async t => {47test('Sets empty result.ipcOutput if ipc is false', async () => {48 const {ipcOutput} = await execa('empty.js');47 t.deepEqual(ipcOutput, []);49 assert.deepEqual(ipcOutput, []);50});5150test('Sets empty result.ipcOutput, sync', t => {52test('Sets empty result.ipcOutput, sync', () => {53 const {ipcOutput} = execaSync('empty.js');52 t.deepEqual(ipcOutput, []);54 assert.deepEqual(ipcOutput, []);55});5655const testErrorIpc = async (t, options) => {56 const {ipcOutput} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));57 t.deepEqual(ipcOutput, [foobarString]);57const testErrorIpc = async options => {58 const {ipcOutput} = await assertRejects(execa('ipc-send-fail.js', {...options, ipc: true}));59 assert.deepEqual(ipcOutput, [foobarString]);60};6160test('Sets error.ipcOutput', testErrorIpc, {});61test('Sets error.ipcOutput, fd-specific buffer', testErrorIpc, {buffer: {stdout: false}});62test('Sets error.ipcOutput', () => testErrorIpc({}));63test('Sets error.ipcOutput, fd-specific buffer', () => testErrorIpc({buffer: {stdout: false}}));6463const testErrorNoBuffer = async (t, options) => {64 const {ipcOutput} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));65 t.deepEqual(ipcOutput, []);65const testErrorNoBuffer = async options => {66 const {ipcOutput} = await assertRejects(execa('ipc-send-fail.js', {...options, ipc: true}));67 assert.deepEqual(ipcOutput, []);68};6968test('Sets empty error.ipcOutput if buffer is false', testErrorNoBuffer, {buffer: false});69test('Sets empty error.ipcOutput if buffer is false, fd-specific buffer', testErrorNoBuffer, {buffer: {ipc: false}});70test('Sets empty error.ipcOutput if buffer is false', () => testErrorNoBuffer({buffer: false}));71test('Sets empty error.ipcOutput if buffer is false, fd-specific buffer', () => testErrorNoBuffer({buffer: {ipc: false}}));7271test('Sets empty error.ipcOutput if ipc is false', async t => {72 const {ipcOutput} = await t.throwsAsync(execa('fail.js'));73 t.deepEqual(ipcOutput, []);73test('Sets empty error.ipcOutput if ipc is false', async () => {74 const {ipcOutput} = await assertRejects(execa('fail.js'));75 assert.deepEqual(ipcOutput, []);76});7776test('Sets empty error.ipcOutput, sync', t => {77 const {ipcOutput} = t.throws(() => execaSync('fail.js'));78 t.deepEqual(ipcOutput, []);78test('Sets empty error.ipcOutput, sync', () => {79 const {ipcOutput} = assertThrows(() => execaSync('fail.js'));80 assert.deepEqual(ipcOutput, []);81});8281test.serial('Can retrieve initial IPC messages under heavy load', async t => {83test('Can retrieve initial IPC messages under heavy load', async () => {84 await Promise.all(Array.from({length: PARALLEL_COUNT}, async (_, index) => {85 const {ipcOutput} = await execa('ipc-send-argv.js', [`${index}`], {ipc: true});84 t.deepEqual(ipcOutput, [`${index}`]);86 assert.deepEqual(ipcOutput, [`${index}`]);87 }));88});
modified:test/ipc/forward.js+43 added-41 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString, foobarArray} from '../helpers/input.js';7import {iterateAllMessages, isAlwaysTrue} from '../helpers/ipc.js';89setFixtureDirectory();109const testParentErrorOne = async (t, filter, buffer) => {11const testParentErrorOne = async (filter, buffer) => {12 const subprocess = execa('ipc-send.js', {ipc: true, buffer});1314 const promise = subprocess.getOneMessage({filter});15 const cause = new Error(foobarString);16 subprocess.nodeChildProcess.emit('error', cause);15 t.is(await promise, foobarString);17 assert.equal(await promise, foobarString);1817 const error = await t.throwsAsync(subprocess);18 t.is(error.exitCode, undefined);19 t.false(error.isTerminated);20 t.is(error.cause, cause);19 const error = await assertRejects(subprocess);20 assert.equal(error.exitCode, undefined);21 assert.equal(error.isTerminated, false);22 assert.equal(error.cause, cause);23 if (buffer) {22 t.deepEqual(error.ipcOutput, [foobarString]);24 assert.deepEqual(error.ipcOutput, [foobarString]);25 }26};2726test('"error" event does not interrupt subprocess.getOneMessage(), buffer false', testParentErrorOne, undefined, false);27test('"error" event does not interrupt subprocess.getOneMessage(), buffer true', testParentErrorOne, undefined, true);28test('"error" event does not interrupt subprocess.getOneMessage(), buffer false, filter', testParentErrorOne, isAlwaysTrue, false);29test('"error" event does not interrupt subprocess.getOneMessage(), buffer true, filter', testParentErrorOne, isAlwaysTrue, true);28test('"error" event does not interrupt subprocess.getOneMessage(), buffer false', () => testParentErrorOne(undefined, false));29test('"error" event does not interrupt subprocess.getOneMessage(), buffer true', () => testParentErrorOne(undefined, true));30test('"error" event does not interrupt subprocess.getOneMessage(), buffer false, filter', () => testParentErrorOne(isAlwaysTrue, false));31test('"error" event does not interrupt subprocess.getOneMessage(), buffer true, filter', () => testParentErrorOne(isAlwaysTrue, true));3231const testSubprocessErrorOne = async (t, filter, buffer) => {33const testSubprocessErrorOne = async (filter, buffer) => {34 const subprocess = execa('ipc-process-error.js', [`${filter}`], {ipc: true, buffer});35 await subprocess.sendMessage(foobarString);34 t.is(await subprocess.getOneMessage(), foobarString);36 assert.equal(await subprocess.getOneMessage(), foobarString);3738 const {ipcOutput} = await subprocess;39 if (buffer) {38 t.deepEqual(ipcOutput, [foobarString]);40 assert.deepEqual(ipcOutput, [foobarString]);41 }42};4342test('"error" event does not interrupt exports.getOneMessage(), buffer false', testSubprocessErrorOne, false, false);43test('"error" event does not interrupt exports.getOneMessage(), buffer true', testSubprocessErrorOne, false, true);44test('"error" event does not interrupt exports.getOneMessage(), buffer false, filter', testSubprocessErrorOne, true, false);45test('"error" event does not interrupt exports.getOneMessage(), buffer true, filter', testSubprocessErrorOne, true, true);44test('"error" event does not interrupt exports.getOneMessage(), buffer false', () => testSubprocessErrorOne(false, false));45test('"error" event does not interrupt exports.getOneMessage(), buffer true', () => testSubprocessErrorOne(false, true));46test('"error" event does not interrupt exports.getOneMessage(), buffer false, filter', () => testSubprocessErrorOne(true, false));47test('"error" event does not interrupt exports.getOneMessage(), buffer true, filter', () => testSubprocessErrorOne(true, true));4847const testParentErrorEach = async (t, buffer) => {49const testParentErrorEach = async buffer => {50 const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});5152 const promise = iterateAllMessages(subprocess);53 const cause = new Error(foobarString);54 subprocess.nodeChildProcess.emit('error', cause);5554 const error = await t.throwsAsync(subprocess);55 t.is(error, await t.throwsAsync(promise));56 t.is(error.exitCode, undefined);57 t.false(error.isTerminated);58 t.is(error.cause, cause);56 const error = await assertRejects(subprocess);57 assert.equal(error, await assertRejects(promise));58 assert.equal(error.exitCode, undefined);59 assert.equal(error.isTerminated, false);60 assert.equal(error.cause, cause);61 if (buffer) {60 t.deepEqual(error.ipcOutput, foobarArray);62 assert.deepEqual(error.ipcOutput, foobarArray);63 }64};6564test('"error" event does not interrupt subprocess.getEachMessage(), buffer false', testParentErrorEach, false);65test('"error" event does not interrupt subprocess.getEachMessage(), buffer true', testParentErrorEach, true);66test('"error" event does not interrupt subprocess.getEachMessage(), buffer false', () => testParentErrorEach(false));67test('"error" event does not interrupt subprocess.getEachMessage(), buffer true', () => testParentErrorEach(true));6867const testSubprocessErrorEach = async (t, filter, buffer) => {69const testSubprocessErrorEach = async (filter, buffer) => {70 const subprocess = execa('ipc-iterate-error.js', [`${filter}`], {ipc: true, buffer});71 await subprocess.sendMessage('.');70 t.is(await subprocess.getOneMessage(), '.');72 assert.equal(await subprocess.getOneMessage(), '.');73 await subprocess.sendMessage(foobarString);7475 const {ipcOutput} = await subprocess;76 if (buffer) {75 t.deepEqual(ipcOutput, ['.']);77 assert.deepEqual(ipcOutput, ['.']);78 }79};8079test('"error" event does not interrupt exports.getEachMessage(), buffer false', testSubprocessErrorEach, 'ipc-iterate-error.js', false);80test('"error" event does not interrupt exports.getEachMessage(), buffer true', testSubprocessErrorEach, 'ipc-iterate-error.js', true);81test('"error" event does not interrupt exports.getEachMessage(), buffer false', () => testSubprocessErrorEach('ipc-iterate-error.js', false));82test('"error" event does not interrupt exports.getEachMessage(), buffer true', () => testSubprocessErrorEach('ipc-iterate-error.js', true));8382test('"error" event does not interrupt result.ipcOutput', async t => {84test('"error" event does not interrupt result.ipcOutput', async () => {85 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});8687 const cause = new Error(foobarString);88 subprocess.nodeChildProcess.emit('error', cause);87 t.is(await subprocess.getOneMessage(), foobarString);89 assert.equal(await subprocess.getOneMessage(), foobarString);90 await subprocess.sendMessage(foobarString);89 t.is(await subprocess.getOneMessage(), foobarString);91 assert.equal(await subprocess.getOneMessage(), foobarString);9291 const error = await t.throwsAsync(subprocess);92 t.is(error.exitCode, undefined);93 t.false(error.isTerminated);94 t.is(error.cause, cause);95 t.deepEqual(error.ipcOutput, [foobarString, foobarString]);93 const error = await assertRejects(subprocess);94 assert.equal(error.exitCode, undefined);95 assert.equal(error.isTerminated, false);96 assert.equal(error.cause, cause);97 assert.deepEqual(error.ipcOutput, [foobarString, foobarString]);98});
modified:test/ipc/get-each.js+75 added-70 removed
1import assert from 'node:assert/strict';2import {scheduler} from 'node:timers/promises';2import test from 'ava';3import test from 'node:test';4import {assertRejects} from '../helpers/assert.js';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {foobarString, foobarArray} from '../helpers/input.js';8import {PARALLEL_COUNT} from '../helpers/parallel.js';9import {iterateAllMessages} from '../helpers/ipc.js';10/* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */1112setFixtureDirectory();1311test('Can iterate over IPC messages', async t => {14test('Can iterate over IPC messages', async () => {15 let count = 0;16 const subprocess = execa('ipc-send-twice.js', {ipc: true});17 for await (const message of subprocess.getEachMessage()) {15 t.is(message, foobarArray[count++]);18 assert.equal(message, foobarArray[count++]);19 }2021 const {ipcOutput} = await subprocess;19 t.deepEqual(ipcOutput, foobarArray);22 assert.deepEqual(ipcOutput, foobarArray);23});2422test('Can iterate over IPC messages in subprocess', async t => {25test('Can iterate over IPC messages in subprocess', async () => {26 const subprocess = execa('ipc-iterate.js', {ipc: true});2728 await subprocess.sendMessage('.');29 await subprocess.sendMessage('.');30 await subprocess.sendMessage(foobarString);3132 const {ipcOutput} = await subprocess;30 t.deepEqual(ipcOutput, ['.', '.']);33 assert.deepEqual(ipcOutput, ['.', '.']);34});3533test('subprocess.getEachMessage() can be called twice at the same time', async t => {36test('subprocess.getEachMessage() can be called twice at the same time', async () => {37 const subprocess = execa('ipc-send-twice.js', {ipc: true});35 t.deepEqual(38 assert.deepEqual(39 await Promise.all([iterateAllMessages(subprocess), iterateAllMessages(subprocess)]),40 [foobarArray, foobarArray],41 );4243 const {ipcOutput} = await subprocess;41 t.deepEqual(ipcOutput, foobarArray);44 assert.deepEqual(ipcOutput, foobarArray);45});4644const iterateAndBreak = async (t, subprocess) => {47const iterateAndBreak = async subprocess => {48 // eslint-disable-next-line no-unreachable-loop49 for await (const message of subprocess.getEachMessage()) {47 t.is(message, foobarString);50 assert.equal(message, foobarString);51 break;52 }53};5452test('Breaking in subprocess.getEachMessage() disconnects', async t => {55test('Breaking in subprocess.getEachMessage() disconnects', async () => {56 const subprocess = execa('ipc-iterate-send.js', {ipc: true});54 await iterateAndBreak(t, subprocess);57 await iterateAndBreak(subprocess);58 const {ipcOutput} = await subprocess;56 t.deepEqual(ipcOutput, [foobarString]);59 assert.deepEqual(ipcOutput, [foobarString]);60});6159test('Breaking from subprocess.getEachMessage() awaits the subprocess', async t => {62test('Breaking from subprocess.getEachMessage() awaits the subprocess', async () => {63 const subprocess = execa('ipc-send-wait-print.js', {ipc: true});61 await iterateAndBreak(t, subprocess);64 await iterateAndBreak(subprocess);6566 const {ipcOutput, stdout} = await subprocess;64 t.deepEqual(ipcOutput, [foobarString]);65 t.is(stdout, '.');67 assert.deepEqual(ipcOutput, [foobarString]);68 assert.equal(stdout, '.');69});7068test('Breaking from exports.getEachMessage() disconnects', async t => {71test('Breaking from exports.getEachMessage() disconnects', async () => {72 const subprocess = execa('ipc-iterate-break.js', {ipc: true});7371 t.is(await subprocess.getOneMessage(), foobarString);74 assert.equal(await subprocess.getOneMessage(), foobarString);75 await subprocess.sendMessage(foobarString);73 const ipcError = await t.throwsAsync(subprocess.getOneMessage());74 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));76 const ipcError = await assertRejects(subprocess.getOneMessage());77 assert.ok(ipcError.message.includes('subprocess.getOneMessage() could not complete'));7879 const {ipcOutput} = await subprocess;77 t.deepEqual(ipcOutput, [foobarString]);80 assert.deepEqual(ipcOutput, [foobarString]);81});8280const iterateAndThrow = async (t, subprocess, cause) => {83const iterateAndThrow = async (subprocess, cause) => {84 // eslint-disable-next-line no-unreachable-loop85 for await (const message of subprocess.getEachMessage()) {83 t.is(message, foobarString);86 assert.equal(message, foobarString);87 throw cause;88 }89};9088test('Throwing from subprocess.getEachMessage() disconnects', async t => {91test('Throwing from subprocess.getEachMessage() disconnects', async () => {92 const subprocess = execa('ipc-iterate-send.js', {ipc: true});9394 const cause = new Error(foobarString);92 t.is(await t.throwsAsync(iterateAndThrow(t, subprocess, cause)), cause);95 assert.equal(await assertRejects(iterateAndThrow(subprocess, cause)), cause);9697 const {ipcOutput} = await subprocess;95 t.deepEqual(ipcOutput, [foobarString]);98 assert.deepEqual(ipcOutput, [foobarString]);99});10098test('Throwing from subprocess.getEachMessage() awaits the subprocess', async t => {101test('Throwing from subprocess.getEachMessage() awaits the subprocess', async () => {102 const subprocess = execa('ipc-send-wait-print.js', {ipc: true});103 const cause = new Error(foobarString);101 t.is(await t.throwsAsync(iterateAndThrow(t, subprocess, cause)), cause);104 assert.equal(await assertRejects(iterateAndThrow(subprocess, cause)), cause);105106 const {ipcOutput, stdout} = await subprocess;104 t.deepEqual(ipcOutput, [foobarString]);105 t.is(stdout, '.');107 assert.deepEqual(ipcOutput, [foobarString]);108 assert.equal(stdout, '.');109});110108test('Throwing from exports.getEachMessage() disconnects', async t => {111test('Throwing from exports.getEachMessage() disconnects', async () => {112 const subprocess = execa('ipc-iterate-throw.js', {ipc: true});113111 t.is(await subprocess.getOneMessage(), foobarString);114 assert.equal(await subprocess.getOneMessage(), foobarString);115 await subprocess.sendMessage(foobarString);113 const ipcError = await t.throwsAsync(subprocess.getOneMessage());114 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));116 const ipcError = await assertRejects(subprocess.getOneMessage());117 assert.ok(ipcError.message.includes('subprocess.getOneMessage() could not complete'));118116 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);117 t.is(exitCode, 1);118 t.false(isTerminated);119 t.true(message.includes(`Error: ${foobarString}`));120 t.deepEqual(ipcOutput, [foobarString]);119 const {exitCode, isTerminated, message, ipcOutput} = await assertRejects(subprocess);120 assert.equal(exitCode, 1);121 assert.equal(isTerminated, false);122 assert.ok(message.includes(`Error: ${foobarString}`));123 assert.deepEqual(ipcOutput, [foobarString]);124});125123test.serial('Can send many messages at once with exports.getEachMessage()', async t => {126test('Can send many messages at once with exports.getEachMessage()', async () => {127 const subprocess = execa('ipc-iterate.js', {ipc: true});128 await Promise.all(Array.from({length: PARALLEL_COUNT}, (_, index) => subprocess.sendMessage(index)));129 await subprocess.sendMessage(foobarString);130131 const {ipcOutput} = await subprocess;129 t.deepEqual(ipcOutput, Array.from({length: PARALLEL_COUNT}, (_, index) => index));132 assert.deepEqual(ipcOutput, Array.from({length: PARALLEL_COUNT}, (_, index) => index));133});134132test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', async t => {135test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', async () => {136 const subprocess = execa('ipc-print-many-each.js', [`${PARALLEL_COUNT}`], {ipc: true});137 const indexes = Array.from({length: PARALLEL_COUNT}, (_, index) => `${index}`);138 await Promise.all(indexes.map(index => subprocess.sendMessage(index)));139140 const {stdout} = await subprocess;141 const expectedOutput = indexes.join('\n');139 t.is(stdout, expectedOutput);142 assert.equal(stdout, expectedOutput);143});144142test('Disconnecting in the current process stops exports.getEachMessage()', async t => {145test('Disconnecting in the current process stops exports.getEachMessage()', async () => {146 const subprocess = execa('ipc-iterate-print.js', {ipc: true});144 t.is(await subprocess.getOneMessage(), foobarString);147 assert.equal(await subprocess.getOneMessage(), foobarString);148 await subprocess.sendMessage('.');149 subprocess.nodeChildProcess.disconnect();150151 const {stdout} = await subprocess;149 t.is(stdout, '.');152 assert.equal(stdout, '.');153});154152test('Disconnecting in the subprocess stops subprocess.getEachMessage()', async t => {155test('Disconnecting in the subprocess stops subprocess.getEachMessage()', async () => {156 const subprocess = execa('ipc-send-disconnect.js', {ipc: true});157 for await (const message of subprocess.getEachMessage()) {155 t.is(message, foobarString);158 assert.equal(message, foobarString);159 }160161 const {ipcOutput} = await subprocess;159 t.deepEqual(ipcOutput, [foobarString]);162 assert.deepEqual(ipcOutput, [foobarString]);163});164162test('Exiting the subprocess stops subprocess.getEachMessage()', async t => {165test('Exiting the subprocess stops subprocess.getEachMessage()', async () => {166 const subprocess = execa('ipc-send.js', {ipc: true});167 for await (const message of subprocess.getEachMessage()) {165 t.is(message, foobarString);168 assert.equal(message, foobarString);169 }170171 const {ipcOutput} = await subprocess;169 t.deepEqual(ipcOutput, [foobarString]);172 assert.deepEqual(ipcOutput, [foobarString]);173});174172const testCleanupListeners = async (t, buffer) => {175const testCleanupListeners = async buffer => {176 const subprocess = execa('ipc-send.js', {ipc: true, buffer});177175 t.is(subprocess.nodeChildProcess.listenerCount('message'), 1);176 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);178 assert.equal(subprocess.nodeChildProcess.listenerCount('message'), 1);179 assert.equal(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);180181 const promise = iterateAllMessages(subprocess);179 t.is(subprocess.nodeChildProcess.listenerCount('message'), 1);180 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);181 t.deepEqual(await promise, [foobarString]);182 assert.equal(subprocess.nodeChildProcess.listenerCount('message'), 1);183 assert.equal(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);184 assert.deepEqual(await promise, [foobarString]);185183 t.is(subprocess.nodeChildProcess.listenerCount('message'), 0);184 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 0);186 assert.equal(subprocess.nodeChildProcess.listenerCount('message'), 0);187 assert.equal(subprocess.nodeChildProcess.listenerCount('disconnect'), 0);188};189187test('Cleans up subprocess.getEachMessage() listeners, buffer false', testCleanupListeners, false);188test('Cleans up subprocess.getEachMessage() listeners, buffer true', testCleanupListeners, true);190test('Cleans up subprocess.getEachMessage() listeners, buffer false', () => testCleanupListeners(false));191test('Cleans up subprocess.getEachMessage() listeners, buffer true', () => testCleanupListeners(true));192193const sendContinuousMessages = async subprocess => {194 while (subprocess.nodeChildProcess.connected) {195 for (let index = 0; index < 10; index += 1) {
4 unmodified lines
200 await scheduler.yield();201 }202};203201test.serial('Handles buffered messages when disconnecting', async t => {204test('Handles buffered messages when disconnecting', async () => {205 const subprocess = execa('ipc-send-fail.js', {ipc: true, buffer: false});206207 const promise = subprocess.getOneMessage();208 subprocess.nodeChildProcess.emit('message', foobarString);206 t.is(await promise, foobarString);209 assert.equal(await promise, foobarString);210 sendContinuousMessages(subprocess);211209 const {exitCode, isTerminated, ipcOutput} = await t.throwsAsync(iterateAllMessages(subprocess));210 t.is(exitCode, 1);211 t.false(isTerminated);212 t.deepEqual(ipcOutput, []);212 const {exitCode, isTerminated, ipcOutput} = await assertRejects(iterateAllMessages(subprocess));213 assert.equal(exitCode, 1);214 assert.equal(isTerminated, false);215 assert.deepEqual(ipcOutput, []);216});217218/* eslint-enable node-test/no-conditional-assertion */
modified:test/ipc/get-one.js+59 added-57 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString, foobarArray} from '../helpers/input.js';7import {isAlwaysTrue} from '../helpers/ipc.js';8import {PARALLEL_COUNT} from '../helpers/parallel.js';910setFixtureDirectory();1110test('subprocess.getOneMessage() can filter messages', async t => {12test('subprocess.getOneMessage() can filter messages', async () => {13 const subprocess = execa('ipc-send-twice.js', {ipc: true});14 const message = await subprocess.getOneMessage({filter: message => message === foobarArray[1]});13 t.is(message, foobarArray[1]);15 assert.equal(message, foobarArray[1]);1617 const {ipcOutput} = await subprocess;16 t.deepEqual(ipcOutput, foobarArray);18 assert.deepEqual(ipcOutput, foobarArray);19});2019test('exports.getOneMessage() can filter messages', async t => {21test('exports.getOneMessage() can filter messages', async () => {22 const subprocess = execa('ipc-echo-filter.js', {ipc: true});23 await subprocess.sendMessage(foobarArray[0]);24 await subprocess.sendMessage(foobarArray[1]);2526 const {ipcOutput} = await subprocess;25 t.deepEqual(ipcOutput, [foobarArray[1]]);27 assert.deepEqual(ipcOutput, [foobarArray[1]]);28});2928test('Throwing from subprocess.getOneMessage() filter disconnects', async t => {30test('Throwing from subprocess.getOneMessage() filter disconnects', async () => {31 const subprocess = execa('ipc-send-get.js', {ipc: true});32 const error = new Error(foobarString);31 t.is(await t.throwsAsync(subprocess.getOneMessage({33 assert.equal(await assertRejects(subprocess.getOneMessage({34 filter() {35 throw error;36 },37 })), error);3837 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);38 t.is(exitCode, 1);39 t.false(isTerminated);40 t.true(message.includes('Error: getOneMessage() could not complete'));41 t.deepEqual(ipcOutput, [foobarString]);39 const {exitCode, isTerminated, message, ipcOutput} = await assertRejects(subprocess);40 assert.equal(exitCode, 1);41 assert.equal(isTerminated, false);42 assert.ok(message.includes('Error: getOneMessage() could not complete'));43 assert.deepEqual(ipcOutput, [foobarString]);44});4544test('Throwing from exports.getOneMessage() filter disconnects', async t => {46test('Throwing from exports.getOneMessage() filter disconnects', async () => {47 const subprocess = execa('ipc-get-filter-throw.js', {ipcInput: 0});46 await t.throwsAsync(subprocess.getOneMessage(), {48 await assertRejects(subprocess.getOneMessage(), {49 message: /subprocess.getOneMessage\(\) could not complete/,50 });5150 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);51 t.is(exitCode, 1);52 t.false(isTerminated);53 t.true(message.includes(`Error: ${foobarString}`));54 t.deepEqual(ipcOutput, []);52 const {exitCode, isTerminated, message, ipcOutput} = await assertRejects(subprocess);53 assert.equal(exitCode, 1);54 assert.equal(isTerminated, false);55 assert.ok(message.includes(`Error: ${foobarString}`));56 assert.deepEqual(ipcOutput, []);57});5857test.serial('Can retrieve initial IPC messages under heavy load', async t => {59test('Can retrieve initial IPC messages under heavy load', async () => {60 await Promise.all(Array.from({length: PARALLEL_COUNT}, async (_, index) => {61 const subprocess = execa('ipc-send-argv.js', [`${index}`], {ipc: true, buffer: false});60 t.is(await subprocess.getOneMessage(), `${index}`);62 assert.equal(await subprocess.getOneMessage(), `${index}`);63 await subprocess;64 }));65});6665const testTwice = async (t, buffer, filter) => {67const testTwice = async (buffer, filter) => {68 const subprocess = execa('ipc-send.js', {ipc: true, buffer});67 t.deepEqual(69 assert.deepEqual(70 await Promise.all([subprocess.getOneMessage({filter}), subprocess.getOneMessage({filter})]),71 [foobarString, foobarString],72 );73 await subprocess;74};7574test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false, undefined);75test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true, undefined);76test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, false, isAlwaysTrue);77test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, true, isAlwaysTrue);76test('subprocess.getOneMessage() can be called twice at the same time, buffer false', () => testTwice(false, undefined));77test('subprocess.getOneMessage() can be called twice at the same time, buffer true', () => testTwice(true, undefined));78test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', () => testTwice(false, isAlwaysTrue));79test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', () => testTwice(true, isAlwaysTrue));8079const testCleanupListeners = async (t, buffer, filter) => {81const testCleanupListeners = async (buffer, filter) => {82 const subprocess = execa('ipc-send.js', {ipc: true, buffer});8382 t.is(subprocess.nodeChildProcess.listenerCount('message'), 1);83 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);84 assert.equal(subprocess.nodeChildProcess.listenerCount('message'), 1);85 assert.equal(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);8687 const promise = subprocess.getOneMessage({filter});86 t.is(subprocess.nodeChildProcess.listenerCount('message'), 1);87 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);88 assert.equal(subprocess.nodeChildProcess.listenerCount('message'), 1);89 assert.equal(subprocess.nodeChildProcess.listenerCount('disconnect'), 1);9089 t.is(await promise, foobarString);91 assert.equal(await promise, foobarString);92 await subprocess;9392 t.is(subprocess.nodeChildProcess.listenerCount('message'), 0);93 t.is(subprocess.nodeChildProcess.listenerCount('disconnect'), 0);94 assert.equal(subprocess.nodeChildProcess.listenerCount('message'), 0);95 assert.equal(subprocess.nodeChildProcess.listenerCount('disconnect'), 0);96};9796test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);97test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);98test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, false, isAlwaysTrue);99test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, true, isAlwaysTrue);98test('Cleans up subprocess.getOneMessage() listeners, buffer false', () => testCleanupListeners(false, undefined));99test('Cleans up subprocess.getOneMessage() listeners, buffer true', () => testCleanupListeners(true, undefined));100test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', () => testCleanupListeners(false, isAlwaysTrue));101test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', () => testCleanupListeners(true, isAlwaysTrue));102101const testParentDisconnect = async (t, buffer, filter) => {103const testParentDisconnect = async (buffer, filter) => {104 const subprocess = execa('ipc-get-send-get.js', [`${filter}`], {ipc: true, buffer});105 await subprocess.sendMessage(foobarString);104 t.is(await subprocess.getOneMessage(), foobarString);106 assert.equal(await subprocess.getOneMessage(), foobarString);107108 subprocess.nodeChildProcess.disconnect();109108 const {exitCode, isTerminated, message} = await t.throwsAsync(subprocess);109 t.is(exitCode, 1);110 t.false(isTerminated);110 const {exitCode, isTerminated, message} = await assertRejects(subprocess);111 assert.equal(exitCode, 1);112 assert.equal(isTerminated, false);113 if (buffer) {112 t.true(message.includes('Error: getOneMessage() could not complete'));114 assert.ok(message.includes('Error: getOneMessage() could not complete'));115 }116};117116test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false);117test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false);118test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true);119test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, false);118test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', () => testParentDisconnect(false, false));119test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', () => testParentDisconnect(true, false));120test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', () => testParentDisconnect(false, true));121test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', () => testParentDisconnect(true, false));122121const testSubprocessDisconnect = async (t, buffer, filter) => {123const testSubprocessDisconnect = async (buffer, filter) => {124 const subprocess = execa('empty.js', {ipc: true, buffer});123 const {message} = await t.throwsAsync(subprocess.getOneMessage({filter}));124 t.true(message.includes('subprocess.getOneMessage() could not complete'));125 const {message} = await assertRejects(subprocess.getOneMessage({filter}));126 assert.ok(message.includes('subprocess.getOneMessage() could not complete'));127 await subprocess;128};129128test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', testSubprocessDisconnect, false, undefined);129test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', testSubprocessDisconnect, true, undefined);130test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', testSubprocessDisconnect, false, isAlwaysTrue);131test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', testSubprocessDisconnect, true, isAlwaysTrue);130test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', () => testSubprocessDisconnect(false, undefined));131test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', () => testSubprocessDisconnect(true, undefined));132test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', () => testSubprocessDisconnect(false, isAlwaysTrue));133test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', () => testSubprocessDisconnect(true, isAlwaysTrue));
modified:test/ipc/graceful.js+127 added-125 removed
1import assert from 'node:assert/strict';2import {getEventListeners} from 'node:events';3import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import test from 'node:test';5import {assertRejects} from '../helpers/assert.js';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {foobarString} from '../helpers/input.js';910setFixtureDirectory();1110test('Graceful cancelSignal can be already aborted', async t => {11 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(execa('graceful-send.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false}));12 t.true(isCanceled);13 t.true(isGracefullyCanceled);14 t.false(isTerminated);15 t.is(exitCode, 0);16 t.deepEqual(ipcOutput, [foobarString]);12test('Graceful cancelSignal can be already aborted', async () => {13 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(execa('graceful-send.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false}));14 assert.equal(isCanceled, true);15 assert.equal(isGracefullyCanceled, true);16 assert.equal(isTerminated, false);17 assert.equal(exitCode, 0);18 assert.deepEqual(ipcOutput, [foobarString]);19});2019test('Graceful cancelSignal can be aborted', async t => {21test('Graceful cancelSignal can be aborted', async () => {22 const controller = new AbortController();23 const subprocess = execa('graceful-send-twice.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});22 t.false(await subprocess.getOneMessage());24 assert.equal(await subprocess.getOneMessage(), false);25 controller.abort(foobarString);24 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);25 t.true(isCanceled);26 t.true(isGracefullyCanceled);27 t.false(isTerminated);28 t.is(exitCode, 0);29 t.deepEqual(ipcOutput, [false, foobarString]);26 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(subprocess);27 assert.equal(isCanceled, true);28 assert.equal(isGracefullyCanceled, true);29 assert.equal(isTerminated, false);30 assert.equal(exitCode, 0);31 assert.deepEqual(ipcOutput, [false, foobarString]);32});3332test('Graceful cancelSignal can be never aborted', async t => {34test('Graceful cancelSignal can be never aborted', async () => {35 const controller = new AbortController();36 const subprocess = execa('graceful-send-fast.js', {cancelSignal: controller.signal, gracefulCancel: true});35 t.false(await subprocess.getOneMessage());37 assert.equal(await subprocess.getOneMessage(), false);38 await subprocess;39});4039test('Graceful cancelSignal can be already aborted but not used', async t => {41test('Graceful cancelSignal can be already aborted but not used', async () => {42 const subprocess = execa('ipc-send-get.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false});41 t.is(await subprocess.getOneMessage(), foobarString);43 assert.equal(await subprocess.getOneMessage(), foobarString);44 await setTimeout(1e3);45 await subprocess.sendMessage('.');44 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);45 t.true(isCanceled);46 t.true(isGracefullyCanceled);47 t.false(isTerminated);48 t.is(exitCode, 0);49 t.deepEqual(ipcOutput, [foobarString]);46 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(subprocess);47 assert.equal(isCanceled, true);48 assert.equal(isGracefullyCanceled, true);49 assert.equal(isTerminated, false);50 assert.equal(exitCode, 0);51 assert.deepEqual(ipcOutput, [foobarString]);52});5352test('Graceful cancelSignal can be aborted but not used', async t => {54test('Graceful cancelSignal can be aborted but not used', async () => {55 const controller = new AbortController();56 const subprocess = execa('ipc-send-get.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});55 t.is(await subprocess.getOneMessage(), foobarString);57 assert.equal(await subprocess.getOneMessage(), foobarString);58 controller.abort(foobarString);59 await setTimeout(1e3);60 await subprocess.sendMessage(foobarString);59 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);60 t.true(isCanceled);61 t.true(isGracefullyCanceled);62 t.false(isTerminated);63 t.is(exitCode, 0);64 t.deepEqual(ipcOutput, [foobarString]);61 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(subprocess);62 assert.equal(isCanceled, true);63 assert.equal(isGracefullyCanceled, true);64 assert.equal(isTerminated, false);65 assert.equal(exitCode, 0);66 assert.deepEqual(ipcOutput, [foobarString]);67});6867test('Graceful cancelSignal can be never aborted nor used', async t => {69test('Graceful cancelSignal can be never aborted nor used', async () => {70 const controller = new AbortController();71 const subprocess = execa('empty.js', {cancelSignal: controller.signal, gracefulCancel: true});70 t.is(getEventListeners(controller.signal, 'abort').length, 1);72 assert.equal(getEventListeners(controller.signal, 'abort').length, 1);73 await subprocess;72 t.is(getEventListeners(controller.signal, 'abort').length, 0);74 assert.equal(getEventListeners(controller.signal, 'abort').length, 0);75});7675test('Graceful cancelSignal can be aborted twice', async t => {77test('Graceful cancelSignal can be aborted twice', async () => {78 const controller = new AbortController();79 const subprocess = execa('graceful-send-twice.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});78 t.false(await subprocess.getOneMessage());80 assert.equal(await subprocess.getOneMessage(), false);81 controller.abort(foobarString);82 controller.abort('.');81 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);82 t.true(isCanceled);83 t.true(isGracefullyCanceled);84 t.false(isTerminated);85 t.is(exitCode, 0);86 t.deepEqual(ipcOutput, [false, foobarString]);83 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(subprocess);84 assert.equal(isCanceled, true);85 assert.equal(isGracefullyCanceled, true);86 assert.equal(isTerminated, false);87 assert.equal(exitCode, 0);88 assert.deepEqual(ipcOutput, [false, foobarString]);89});9089test('Graceful cancelSignal cannot be manually aborted after disconnection', async t => {91test('Graceful cancelSignal cannot be manually aborted after disconnection', async () => {92 const controller = new AbortController();93 const subprocess = execa('empty.js', {cancelSignal: controller.signal, gracefulCancel: true});94 subprocess.nodeChildProcess.disconnect();95 controller.abort(foobarString);94 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, originalMessage} = await t.throwsAsync(subprocess);95 t.false(isCanceled);96 t.false(isGracefullyCanceled);97 t.false(isTerminated);98 t.is(exitCode, 0);99 t.deepEqual(ipcOutput, []);100 t.is(originalMessage, '`cancelSignal`\'s `controller.abort()` cannot be used: the subprocess has already exited or disconnected.');96 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, originalMessage} = await assertRejects(subprocess);97 assert.equal(isCanceled, false);98 assert.equal(isGracefullyCanceled, false);99 assert.equal(isTerminated, false);100 assert.equal(exitCode, 0);101 assert.deepEqual(ipcOutput, []);102 assert.equal(originalMessage, '`cancelSignal`\'s `controller.abort()` cannot be used: the subprocess has already exited or disconnected.');103});104103test('Graceful cancelSignal can disconnect after being manually aborted', async t => {105test('Graceful cancelSignal can disconnect after being manually aborted', async () => {106 const controller = new AbortController();107 const subprocess = execa('graceful-disconnect.js', {cancelSignal: controller.signal, gracefulCancel: true});108 controller.abort(foobarString);107 t.is(await subprocess.getOneMessage(), foobarString);109 assert.equal(await subprocess.getOneMessage(), foobarString);110 subprocess.nodeChildProcess.disconnect();109 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);110 t.true(isCanceled);111 t.true(isGracefullyCanceled);112 t.false(isTerminated);113 t.is(exitCode, 0);114 t.deepEqual(ipcOutput, [foobarString]);111 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(subprocess);112 assert.equal(isCanceled, true);113 assert.equal(isGracefullyCanceled, true);114 assert.equal(isTerminated, false);115 assert.equal(exitCode, 0);116 assert.deepEqual(ipcOutput, [foobarString]);117});118117test('Graceful cancelSignal is automatically aborted on disconnection', async t => {119test('Graceful cancelSignal is automatically aborted on disconnection', async () => {120 const controller = new AbortController();121 const subprocess = execa('graceful-send-print.js', {cancelSignal: controller.signal, gracefulCancel: true});120 t.false(await subprocess.getOneMessage());122 assert.equal(await subprocess.getOneMessage(), false);123 subprocess.nodeChildProcess.disconnect();124 const {isCanceled, isGracefullyCanceled, ipcOutput, stdout} = await subprocess;123 t.false(isCanceled);124 t.false(isGracefullyCanceled);125 t.deepEqual(ipcOutput, [false]);126 t.true(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));125 assert.equal(isCanceled, false);126 assert.equal(isGracefullyCanceled, false);127 assert.deepEqual(ipcOutput, [false]);128 assert.ok(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));129});130129test('getCancelSignal() aborts if already disconnected', async t => {131test('getCancelSignal() aborts if already disconnected', async () => {132 const controller = new AbortController();133 const subprocess = execa('graceful-print.js', {cancelSignal: controller.signal, gracefulCancel: true});134 subprocess.nodeChildProcess.disconnect();135 const {isCanceled, isGracefullyCanceled, ipcOutput, stdout} = await subprocess;134 t.false(isCanceled);135 t.false(isGracefullyCanceled);136 t.deepEqual(ipcOutput, []);137 t.true(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));136 assert.equal(isCanceled, false);137 assert.equal(isGracefullyCanceled, false);138 assert.deepEqual(ipcOutput, []);139 assert.ok(stdout.includes('Error: `cancelSignal` aborted: the parent process disconnected.'));140});141140test('getCancelSignal() fails if no IPC', async t => {141 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, stderr} = await t.throwsAsync(execa('graceful-none.js'));142 t.false(isCanceled);143 t.false(isGracefullyCanceled);144 t.false(isTerminated);145 t.is(exitCode, 1);146 t.deepEqual(ipcOutput, []);147 t.true(stderr.includes('Error: `getCancelSignal()` cannot be used without setting the `gracefulCancel` option to `true`.'));142test('getCancelSignal() fails if no IPC', async () => {143 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput, stderr} = await assertRejects(execa('graceful-none.js'));144 assert.equal(isCanceled, false);145 assert.equal(isGracefullyCanceled, false);146 assert.equal(isTerminated, false);147 assert.equal(exitCode, 1);148 assert.deepEqual(ipcOutput, []);149 assert.ok(stderr.includes('Error: `getCancelSignal()` cannot be used without setting the `gracefulCancel` option to `true`.'));150});151150test('getCancelSignal() fails on every call if no IPC', async t => {152test('getCancelSignal() fails on every call if no IPC', async () => {153 const {exitCode, stdout} = await execa('graceful-none-twice.js', {stripFinalNewline: false});152 t.is(exitCode, 0);153 t.is(stdout, 'threw\nthrew\n');154 assert.equal(exitCode, 0);155 assert.equal(stdout, 'threw\nthrew\n');156});157156test.serial('getCancelSignal() hangs if cancelSignal without gracefulCancel', async t => {158test('getCancelSignal() hangs if cancelSignal without gracefulCancel', async () => {159 const controller = new AbortController();158 const {timedOut, isCanceled, isGracefullyCanceled, signal, ipcOutput} = await t.throwsAsync(execa('graceful-wait.js', {ipc: true, cancelSignal: controller.signal, timeout: 1e3}));159 t.true(timedOut);160 t.false(isCanceled);161 t.false(isGracefullyCanceled);162 t.is(signal, 'SIGTERM');163 t.deepEqual(ipcOutput, []);160 const {timedOut, isCanceled, isGracefullyCanceled, signal, ipcOutput} = await assertRejects(execa('graceful-wait.js', {ipc: true, cancelSignal: controller.signal, timeout: 1e3}));161 assert.equal(timedOut, true);162 assert.equal(isCanceled, false);163 assert.equal(isGracefullyCanceled, false);164 assert.equal(signal, 'SIGTERM');165 assert.deepEqual(ipcOutput, []);166});167166test('Subprocess cancelSignal does not keep subprocess alive', async t => {168test('Subprocess cancelSignal does not keep subprocess alive', async () => {169 const controller = new AbortController();170 const {ipcOutput} = await execa('graceful-ref.js', {cancelSignal: controller.signal, gracefulCancel: true});169 t.deepEqual(ipcOutput, []);171 assert.deepEqual(ipcOutput, []);172});173172test('Subprocess can send a message right away', async t => {174test('Subprocess can send a message right away', async () => {175 const controller = new AbortController();176 const {ipcOutput} = await execa('graceful-send-string.js', {cancelSignal: controller.signal, gracefulCancel: true});175 t.deepEqual(ipcOutput, [foobarString]);177 assert.deepEqual(ipcOutput, [foobarString]);178});179178test('Subprocess can receive a message right away', async t => {180test('Subprocess can receive a message right away', async () => {181 const controller = new AbortController();182 const {ipcOutput} = await execa('graceful-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, ipcInput: foobarString});181 t.deepEqual(ipcOutput, [foobarString]);183 assert.deepEqual(ipcOutput, [foobarString]);184});185184test('getCancelSignal() can be called twice', async t => {185 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(execa('graceful-twice.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false}));186 t.true(isCanceled);187 t.true(isGracefullyCanceled);188 t.false(isTerminated);189 t.is(exitCode, 0);190 t.deepEqual(ipcOutput, [foobarString]);186test('getCancelSignal() can be called twice', async () => {187 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(execa('graceful-twice.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false}));188 assert.equal(isCanceled, true);189 assert.equal(isGracefullyCanceled, true);190 assert.equal(isTerminated, false);191 assert.equal(exitCode, 0);192 assert.deepEqual(ipcOutput, [foobarString]);193});194193test('Graceful cancelSignal can use cancelSignal.onabort', async t => {195test('Graceful cancelSignal can use cancelSignal.onabort', async () => {196 const controller = new AbortController();197 const subprocess = execa('graceful-listener.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});196 t.is(await subprocess.getOneMessage(), '.');198 assert.equal(await subprocess.getOneMessage(), '.');199 controller.abort(foobarString);198 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);199 t.true(isCanceled);200 t.true(isGracefullyCanceled);201 t.false(isTerminated);202 t.is(exitCode, 0);203 t.deepEqual(ipcOutput, ['.', foobarString]);200 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(subprocess);201 assert.equal(isCanceled, true);202 assert.equal(isGracefullyCanceled, true);203 assert.equal(isTerminated, false);204 assert.equal(exitCode, 0);205 assert.deepEqual(ipcOutput, ['.', foobarString]);206});207206test('Graceful cancelSignal abort reason cannot be directly received', async t => {208test('Graceful cancelSignal abort reason cannot be directly received', async () => {209 const subprocess = execa('graceful-send-echo.js', {cancelSignal: AbortSignal.abort(foobarString), gracefulCancel: true, forceKillAfterDelay: false});210 await setTimeout(0);211 await subprocess.sendMessage('.');210 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await t.throwsAsync(subprocess);211 t.true(isCanceled);212 t.true(isGracefullyCanceled);213 t.false(isTerminated);214 t.is(exitCode, 0);215 t.deepEqual(ipcOutput, ['.', foobarString]);212 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, ipcOutput} = await assertRejects(subprocess);213 assert.equal(isCanceled, true);214 assert.equal(isGracefullyCanceled, true);215 assert.equal(isTerminated, false);216 assert.equal(exitCode, 0);217 assert.deepEqual(ipcOutput, ['.', foobarString]);218});219218test('error.isGracefullyCanceled is always false with execaSync()', t => {220test('error.isGracefullyCanceled is always false with execaSync()', () => {221 const {isCanceled, isGracefullyCanceled} = execaSync('empty.js');220 t.false(isCanceled);221 t.false(isGracefullyCanceled);222 assert.equal(isCanceled, false);223 assert.equal(isGracefullyCanceled, false);224});225226// Execa wraps `gracefulCancel` messages with an internal type, which is only ever sent by the current process to its subprocess.227// A subprocess must not be able to send it in the other direction, since this would abort the parent process' own `cancelSignal`, or silently drop the message.226test('Subprocess messages with the internal graceful cancellation shape are kept', async t => {228test('Subprocess messages with the internal graceful cancellation shape are kept', async () => {229 const {ipcOutput} = await execa('ipc-send-cancel-shape.js', {ipc: true});228 t.deepEqual(ipcOutput, [{type: 'execa:ipc:cancel', message: foobarString}]);230 assert.deepEqual(ipcOutput, [{type: 'execa:ipc:cancel', message: foobarString}]);231});232231test('Graceful cancelSignal is not aborted by the subprocess\' own subprocess', async t => {233test('Graceful cancelSignal is not aborted by the subprocess\' own subprocess', async () => {234 const controller = new AbortController();235 const {ipcOutput} = await execa('graceful-nested.js', {cancelSignal: controller.signal, gracefulCancel: true});234 t.deepEqual(ipcOutput, [false]);236 assert.deepEqual(ipcOutput, [false]);237});
modified:test/ipc/incoming.js+19 added-18 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {foobarString} from '../helpers/input.js';6import {isAlwaysTrue} from '../helpers/ipc.js';7import {PARALLEL_COUNT} from '../helpers/parallel.js';89setFixtureDirectory();1010const testSeriesParent = async (t, buffer, filter) => {11const testSeriesParent = async (buffer, filter) => {12 const subprocess = execa('ipc-send-many.js', [`${PARALLEL_COUNT}`], {ipc: true, buffer});1314 for (let index = 0; index < PARALLEL_COUNT; index += 1) {15 // eslint-disable-next-line no-await-in-loop15 t.is(await subprocess.getOneMessage({filter}), index);16 assert.equal(await subprocess.getOneMessage({filter}), index);17 }1819 const {ipcOutput} = await subprocess;20 if (buffer) {20 t.deepEqual(ipcOutput, Array.from({length: PARALLEL_COUNT}, (_, index) => index));21 assert.deepEqual(ipcOutput, Array.from({length: PARALLEL_COUNT}, (_, index) => index));22 }23};2424test('subprocess.getOneMessage() can be called multiple times in a row, buffer false', testSeriesParent, false, undefined);25test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', testSeriesParent, true, undefined);26test('subprocess.getOneMessage() can be called multiple times in a row, buffer false, filter', testSeriesParent, false, isAlwaysTrue);27test('subprocess.getOneMessage() can be called multiple times in a row, buffer true, filter', testSeriesParent, true, isAlwaysTrue);25test('subprocess.getOneMessage() can be called multiple times in a row, buffer false', () => testSeriesParent(false, undefined));26test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', () => testSeriesParent(true, undefined));27test('subprocess.getOneMessage() can be called multiple times in a row, buffer false, filter', () => testSeriesParent(false, isAlwaysTrue));28test('subprocess.getOneMessage() can be called multiple times in a row, buffer true, filter', () => testSeriesParent(true, isAlwaysTrue));2929const testSeriesSubprocess = async (t, filter) => {30const testSeriesSubprocess = async filter => {31 const subprocess = execa('ipc-print-many.js', [`${PARALLEL_COUNT}`, `${filter}`], {ipc: true});32 const indexes = Array.from({length: PARALLEL_COUNT}, (_, index) => `${index}`);33 await Promise.all(indexes.map(index => subprocess.sendMessage(index)));3435 const {stdout} = await subprocess;36 const expectedOutput = indexes.join('\n');36 t.is(stdout, expectedOutput);37 assert.equal(stdout, expectedOutput);38};3939test('exports.getOneMessage() can be called multiple times in a row', testSeriesSubprocess, false);40test('exports.getOneMessage() can be called multiple times in a row, filter', testSeriesSubprocess, true);40test('exports.getOneMessage() can be called multiple times in a row', () => testSeriesSubprocess(false));41test('exports.getOneMessage() can be called multiple times in a row, filter', () => testSeriesSubprocess(true));4242test('Can iterate multiple times over IPC messages in subprocess', async t => {43test('Can iterate multiple times over IPC messages in subprocess', async () => {44 const subprocess = execa('ipc-iterate-twice.js', {ipc: true});4545 t.is(await subprocess.getOneMessage(), foobarString);46 assert.equal(await subprocess.getOneMessage(), foobarString);47 await subprocess.sendMessage('.');47 t.is(await subprocess.getOneMessage(), '0.');48 assert.equal(await subprocess.getOneMessage(), '0.');49 await subprocess.sendMessage(foobarString);49 t.is(await subprocess.getOneMessage(), foobarString);50 assert.equal(await subprocess.getOneMessage(), foobarString);51 await subprocess.sendMessage('.');51 t.is(await subprocess.getOneMessage(), '1.');52 assert.equal(await subprocess.getOneMessage(), '1.');53 await subprocess.sendMessage(foobarString);5455 const {ipcOutput} = await subprocess;55 t.deepEqual(ipcOutput, [foobarString, '0.', foobarString, '1.']);56 assert.deepEqual(ipcOutput, [foobarString, '0.', foobarString, '1.']);57});
modified:test/ipc/ipc-input.js+42 added-40 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows, assertRejects} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';78setFixtureDirectory();98const testSuccess = async (t, options) => {10const testSuccess = async options => {11 const {ipcOutput} = await execa('ipc-echo.js', {ipcInput: foobarString, ...options});10 t.deepEqual(ipcOutput, [foobarString]);12 assert.deepEqual(ipcOutput, [foobarString]);13};1413test('Sends a message with the "ipcInput" option, ipc undefined', testSuccess, {});14test('Sends a message with the "ipcInput" option, ipc true', testSuccess, {ipc: true});15test('Sends a message with the "ipcInput" option, ipc undefined', () => testSuccess({}));16test('Sends a message with the "ipcInput" option, ipc true', () => testSuccess({ipc: true}));1716test('Cannot use the "ipcInput" option with "ipc" false', t => {17 t.throws(() => {18test('Cannot use the "ipcInput" option with "ipc" false', () => {19 assertThrows(() => {20 execa('empty.js', {ipcInput: foobarString, ipc: false});21 }, {message: /unless the `ipc` option is `true`/});22});2324// Any value can be sent over IPC, including falsy ones, so those must be reported as `ipcInput`, not as `ipc`23const testInvalidSyncIpcInput = (t, ipcInput) => {24 t.throws(() => {25const testInvalidSyncIpcInput = ipcInput => {26 assertThrows(() => {27 execaSync('empty.js', {ipcInput});28 }, {message: /The "ipcInput" option cannot be used with synchronous/});29};3029test('Cannot use the "ipcInput" option with execaSync()', testInvalidSyncIpcInput, foobarString);30test('Cannot use the "ipcInput" option with execaSync(), 0', testInvalidSyncIpcInput, 0);31test('Cannot use the "ipcInput" option with execaSync(), empty string', testInvalidSyncIpcInput, '');32test('Cannot use the "ipcInput" option with execaSync(), false', testInvalidSyncIpcInput, false);33test('Cannot use the "ipcInput" option with execaSync(), null', testInvalidSyncIpcInput, null);31test('Cannot use the "ipcInput" option with execaSync()', () => testInvalidSyncIpcInput(foobarString));32test('Cannot use the "ipcInput" option with execaSync(), 0', () => testInvalidSyncIpcInput(0));33test('Cannot use the "ipcInput" option with execaSync(), empty string', () => testInvalidSyncIpcInput(''));34test('Cannot use the "ipcInput" option with execaSync(), false', () => testInvalidSyncIpcInput(false));35test('Cannot use the "ipcInput" option with execaSync(), null', () => testInvalidSyncIpcInput(null));3635test('Invalid "ipcInput" option v8 format', t => {36 const {message, cause} = t.throws(() => {37test('Invalid "ipcInput" option v8 format', () => {38 const {message, cause} = assertThrows(() => {39 execa('empty.js', {ipcInput() {}});40 });39 t.is(message, 'The `ipcInput` option is not serializable with a structured clone.');40 t.is(cause.message, 'ipcInput() {} could not be cloned.');41 assert.equal(message, 'The `ipcInput` option is not serializable with a structured clone.');42 assert.equal(cause.message, 'ipcInput() {} could not be cloned.');43});4443test('Invalid "ipcInput" option JSON format', t => {44 const {message, cause} = t.throws(() => {45test('Invalid "ipcInput" option JSON format', () => {46 const {message, cause} = assertThrows(() => {47 execa('empty.js', {ipcInput: 0n, serialization: 'json'});48 });47 t.is(message, 'The `ipcInput` option is not serializable with JSON.');48 t.is(cause.message, 'Do not know how to serialize a BigInt');49 assert.equal(message, 'The `ipcInput` option is not serializable with JSON.');50 assert.equal(cause.message, 'Do not know how to serialize a BigInt');51});5253// `JSON.stringify()` returns `undefined`, instead of throwing, for values it cannot represent52const testUnrepresentableJson = (t, ipcInput) => {53 const {message} = t.throws(() => {54const testUnrepresentableJson = ipcInput => {55 const {message} = assertThrows(() => {56 execa('empty.js', {ipcInput, serialization: 'json', ipc: true});57 });56 t.is(message, 'The `ipcInput` option is not serializable with JSON.');58 assert.equal(message, 'The `ipcInput` option is not serializable with JSON.');59};6059test('Invalid "ipcInput" option JSON format, function', testUnrepresentableJson, () => {});60test('Invalid "ipcInput" option JSON format, symbol', testUnrepresentableJson, Symbol('test'));61test('Invalid "ipcInput" option JSON format, function', () => testUnrepresentableJson(() => {}));62test('Invalid "ipcInput" option JSON format, symbol', () => testUnrepresentableJson(Symbol('test')));6364// An invalid `serialization` option must not crash the `ipcInput` validation, which is keyed by it.65// `Object.prototype` properties are the trickiest values, since those are found on any object.64const testInvalidSerialization = async (t, serialization) => {65 const {code} = await t.throwsAsync(execa('empty.js', {ipcInput: foobarString, serialization}));66 t.is(code, 'ERR_INVALID_ARG_VALUE');66const testInvalidSerialization = async serialization => {67 const {code} = await assertRejects(execa('empty.js', {ipcInput: foobarString, serialization}));68 assert.equal(code, 'ERR_INVALID_ARG_VALUE');69};7069test('Invalid "serialization" option with the "ipcInput" option', testInvalidSerialization, 'invalid');70test('Invalid "serialization" option with the "ipcInput" option, __proto__', testInvalidSerialization, '__proto__');71test('Invalid "serialization" option with the "ipcInput" option, toString', testInvalidSerialization, 'toString');72test('Invalid "serialization" option with the "ipcInput" option, constructor', testInvalidSerialization, 'constructor');71test('Invalid "serialization" option with the "ipcInput" option', () => testInvalidSerialization('invalid'));72test('Invalid "serialization" option with the "ipcInput" option, __proto__', () => testInvalidSerialization('__proto__'));73test('Invalid "serialization" option with the "ipcInput" option, toString', () => testInvalidSerialization('toString'));74test('Invalid "serialization" option with the "ipcInput" option, constructor', () => testInvalidSerialization('constructor'));7574test('Handles "ipcInput" option during sending', async t => {75 const {message, cause} = await t.throwsAsync(execa('empty.js', {ipcInput: 0n}));76 t.true(message.includes('subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.'));77 t.true(cause.cause.message.includes('The "message" argument must be one of type string'));76test('Handles "ipcInput" option during sending', async () => {77 const {message, cause} = await assertRejects(execa('empty.js', {ipcInput: 0n}));78 assert.ok(message.includes('subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.'));79 assert.ok(cause.cause.message.includes('The "message" argument must be one of type string'));80});8180test.serial('Can use "ipcInput" option even if the subprocess is not listening to messages', async t => {82test('Can use "ipcInput" option even if the subprocess is not listening to messages', async () => {83 const {ipcOutput} = await execa('empty.js', {ipcInput: foobarString});82 t.deepEqual(ipcOutput, []);84 assert.deepEqual(ipcOutput, []);85});
modified:test/ipc/outgoing.js+39 added-34 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {foobarString} from '../helpers/input.js';6import {isAlwaysTrue, subprocessGetOne, subprocessGetFirst} from '../helpers/ipc.js';7import {PARALLEL_COUNT} from '../helpers/parallel.js';89setFixtureDirectory();1010const testSendHoldParent = async (t, getMessage, buffer, filter) => {11const testSendHoldParent = async (getMessage, buffer, filter) => {12 const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});1314 await subprocess.sendMessage(0);14 t.is(await subprocess.getOneMessage({filter}), 0);15 assert.equal(await subprocess.getOneMessage({filter}), 0);1617 const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index + 1);18 await Promise.all([19 ...messages.map(message => subprocess.sendMessage(message)),20 subprocess.sendMessage(foobarString),21 subprocess.nodeChildProcess.emit('message', '.'),22 ]);22 t.is(await getMessage(subprocess, {filter}), '.');23 assert.equal(await getMessage(subprocess, {filter}), '.');2425 const {ipcOutput} = await subprocess;25 if (buffer) {26 const expectedOutput = [0, '.', ...messages];27 t.deepEqual(ipcOutput, expectedOutput);26 if (!buffer) {27 return;28 }2930 const expectedOutput = [0, '.', ...messages];31 assert.deepEqual(ipcOutput, expectedOutput);32};3331test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', testSendHoldParent, subprocessGetOne, false, undefined);32test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', testSendHoldParent, subprocessGetOne, true, undefined);33test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', testSendHoldParent, subprocessGetOne, false, isAlwaysTrue);34test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', testSendHoldParent, subprocessGetOne, true, isAlwaysTrue);35test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParent, subprocessGetFirst, false, undefined);36test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParent, subprocessGetFirst, true, undefined);34test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', () => testSendHoldParent(subprocessGetOne, false, undefined));35test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', () => testSendHoldParent(subprocessGetOne, true, undefined));36test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', () => testSendHoldParent(subprocessGetOne, false, isAlwaysTrue));37test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', () => testSendHoldParent(subprocessGetOne, true, isAlwaysTrue));38test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', () => testSendHoldParent(subprocessGetFirst, false, undefined));39test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', () => testSendHoldParent(subprocessGetFirst, true, undefined));4038const testSendHoldSubprocess = async (t, filter, isGetEach) => {41const testSendHoldSubprocess = async (filter, isGetEach) => {42 const {ipcOutput} = await execa('ipc-iterate-back.js', [`${filter}`, `${isGetEach}`], {ipcInput: 0});43 const expectedOutput = [...Array.from({length: PARALLEL_COUNT + 1}, (_, index) => index), '.'];41 t.deepEqual(ipcOutput, expectedOutput);44 assert.deepEqual(ipcOutput, expectedOutput);45};4644test('Multiple parallel exports.sendMessage() + exports.getOneMessage()', testSendHoldSubprocess, false, false);45test('Multiple parallel exports.sendMessage() + exports.getOneMessage(), filter', testSendHoldSubprocess, true, false);46test('Multiple parallel exports.sendMessage() + exports.getEachMessage()', testSendHoldSubprocess, false, true);47test('Multiple parallel exports.sendMessage() + exports.getOneMessage()', () => testSendHoldSubprocess(false, false));48test('Multiple parallel exports.sendMessage() + exports.getOneMessage(), filter', () => testSendHoldSubprocess(true, false));49test('Multiple parallel exports.sendMessage() + exports.getEachMessage()', () => testSendHoldSubprocess(false, true));5048const testSendHoldParentSerial = async (t, getMessage, buffer, filter) => {51const testSendHoldParentSerial = async (getMessage, buffer, filter) => {52 const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});5354 await subprocess.sendMessage(0);52 t.is(await subprocess.getOneMessage({filter}), 0);55 assert.equal(await subprocess.getOneMessage({filter}), 0);5657 const promise = subprocess.sendMessage(1);58 subprocess.nodeChildProcess.emit('message', '.');59 await promise;
6 unmodified lines
6667 await subprocess.sendMessage(foobarString);6869 const {ipcOutput} = await subprocess;67 if (buffer) {68 const expectedOutput = [0, '.', 1, ...messages];69 t.deepEqual(ipcOutput, expectedOutput);70 if (!buffer) {71 return;72 }7374 const expectedOutput = [0, '.', 1, ...messages];75 assert.deepEqual(ipcOutput, expectedOutput);76};7773test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', testSendHoldParentSerial, subprocessGetOne, false, undefined);74test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', testSendHoldParentSerial, subprocessGetOne, true, undefined);75test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', testSendHoldParentSerial, subprocessGetOne, false, isAlwaysTrue);76test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', testSendHoldParentSerial, subprocessGetOne, true, isAlwaysTrue);77test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParentSerial, subprocessGetFirst, false, undefined);78test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParentSerial, subprocessGetFirst, true, undefined);78test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', () => testSendHoldParentSerial(subprocessGetOne, false, undefined));79test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', () => testSendHoldParentSerial(subprocessGetOne, true, undefined));80test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', () => testSendHoldParentSerial(subprocessGetOne, false, isAlwaysTrue));81test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', () => testSendHoldParentSerial(subprocessGetOne, true, isAlwaysTrue));82test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', () => testSendHoldParentSerial(subprocessGetFirst, false, undefined));83test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', () => testSendHoldParentSerial(subprocessGetFirst, true, undefined));8480const testSendHoldSubprocessSerial = async (t, filter, isGetEach) => {85const testSendHoldSubprocessSerial = async (filter, isGetEach) => {86 const {ipcOutput} = await execa('ipc-iterate-back-serial.js', [`${filter}`, `${isGetEach}`], {ipcInput: 0});87 const expectedOutput = [...Array.from({length: PARALLEL_COUNT + 2}, (_, index) => index), '.'];83 t.deepEqual(ipcOutput, expectedOutput);88 assert.deepEqual(ipcOutput, expectedOutput);89};9086test('Multiple serial exports.sendMessage() + exports.getOneMessage()', testSendHoldSubprocessSerial, false, false);87test('Multiple serial exports.sendMessage() + exports.getOneMessage(), filter', testSendHoldSubprocessSerial, true, false);88test('Multiple serial exports.sendMessage() + exports.getEachMessage()', testSendHoldSubprocessSerial, false, true);91test('Multiple serial exports.sendMessage() + exports.getOneMessage()', () => testSendHoldSubprocessSerial(false, false));92test('Multiple serial exports.sendMessage() + exports.getOneMessage(), filter', () => testSendHoldSubprocessSerial(true, false));93test('Multiple serial exports.sendMessage() + exports.getEachMessage()', () => testSendHoldSubprocessSerial(false, true));
modified:test/ipc/pending.js+36 added-35 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import test from 'node:test';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {foobarString} from '../helpers/input.js';89setFixtureDirectory();1010const testBufferInitial = async (t, buffer) => {11const testBufferInitial = async buffer => {12 const subprocess = execa('ipc-echo-wait.js', {buffer, ipcInput: foobarString});12 t.is(await subprocess.getOneMessage(), foobarString);13 assert.equal(await subprocess.getOneMessage(), foobarString);1415 const {ipcOutput} = await subprocess;15 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);16 assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);17};1818test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);19test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);19test('Buffers initial message to subprocess, buffer false', () => testBufferInitial(false));20test('Buffers initial message to subprocess, buffer true', () => testBufferInitial(true));2121const testBufferInitialSend = async (t, buffer) => {22const testBufferInitialSend = async buffer => {23 const subprocess = execa('ipc-send-echo-wait.js', {buffer, ipcInput: foobarString});23 t.is(await subprocess.getOneMessage(), '.');24 t.is(await subprocess.getOneMessage(), foobarString);24 assert.equal(await subprocess.getOneMessage(), '.');25 assert.equal(await subprocess.getOneMessage(), foobarString);2627 const {ipcOutput} = await subprocess;27 t.deepEqual(ipcOutput, buffer ? ['.', foobarString] : []);28 assert.deepEqual(ipcOutput, buffer ? ['.', foobarString] : []);29};3030test('sendMessage() does not empty the initial message buffering, buffer false', testBufferInitialSend, false);31test('sendMessage() does not empty the initial message buffering, buffer true', testBufferInitialSend, true);31test('sendMessage() does not empty the initial message buffering, buffer false', () => testBufferInitialSend(false));32test('sendMessage() does not empty the initial message buffering, buffer true', () => testBufferInitialSend(true));3333const testBufferInitialStrict = async (t, buffer) => {34const testBufferInitialStrict = async buffer => {35 const subprocess = execa('ipc-send-echo-strict.js', {buffer, ipcInput: foobarString});35 t.is(await subprocess.getOneMessage(), '.');36 assert.equal(await subprocess.getOneMessage(), '.');37 await setTimeout(1e3);38 const promise = subprocess.getOneMessage();39 await subprocess.sendMessage('..');39 t.is(await promise, '..');40 assert.equal(await promise, '..');4142 const {ipcOutput} = await subprocess;42 t.deepEqual(ipcOutput, buffer ? ['.', '..'] : []);43 assert.deepEqual(ipcOutput, buffer ? ['.', '..'] : []);44};4545test('sendMessage() with "strict" empties the initial message buffering, buffer false', testBufferInitialStrict, false);46test('sendMessage() with "strict" empties the initial message buffering, buffer true', testBufferInitialStrict, true);46test('sendMessage() with "strict" empties the initial message buffering, buffer false', () => testBufferInitialStrict(false));47test('sendMessage() with "strict" empties the initial message buffering, buffer true', () => testBufferInitialStrict(true));4848const testNoBufferInitial = async (t, buffer) => {49const testNoBufferInitial = async buffer => {50 const subprocess = execa('ipc-send-print.js', {ipc: true, buffer});51 const [chunk] = await once(subprocess.stdout, 'data');51 t.is(chunk.toString(), '.');52 assert.equal(chunk.toString(), '.');53 await setTimeout(1e3);53 t.is(await Promise.race([setTimeout(0), subprocess.getOneMessage()]), undefined);54 assert.equal(await Promise.race([setTimeout(0), subprocess.getOneMessage()]), undefined);55 await subprocess.sendMessage('.');5657 const {ipcOutput} = await subprocess;57 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);58 assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);59};6060test.serial('Does not buffer initial message to current process, buffer false', testNoBufferInitial, false);61test.serial('Does not buffer initial message to current process, buffer true', testNoBufferInitial, true);61test('Does not buffer initial message to current process, buffer false', () => testNoBufferInitial(false));62test('Does not buffer initial message to current process, buffer true', () => testNoBufferInitial(true));6363const testReplay = async (t, buffer) => {64const testReplay = async buffer => {65 const subprocess = execa('ipc-replay.js', {buffer, ipcInput: foobarString});65 t.is(await subprocess.getOneMessage(), foobarString);66 assert.equal(await subprocess.getOneMessage(), foobarString);67 await subprocess.sendMessage('.');68 await setTimeout(2e3);69 await subprocess.sendMessage(foobarString);69 t.is(await subprocess.getOneMessage(), foobarString);70 assert.equal(await subprocess.getOneMessage(), foobarString);7172 const {ipcOutput} = await subprocess;72 t.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);73 assert.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);74};7575test.serial('Does not replay missed messages in subprocess, buffer false', testReplay, false);76test.serial('Does not replay missed messages in subprocess, buffer true', testReplay, true);76test('Does not replay missed messages in subprocess, buffer false', () => testReplay(false));77test('Does not replay missed messages in subprocess, buffer true', () => testReplay(true));7878const testFastSend = async (t, buffer) => {79const testFastSend = async buffer => {80 const subprocess = execa('ipc-send-native.js', {ipc: true, buffer});80 t.is(await subprocess.getOneMessage(), '.');81 assert.equal(await subprocess.getOneMessage(), '.');8283 const {ipcOutput} = await subprocess;83 t.deepEqual(ipcOutput, buffer ? ['.'] : []);84 assert.deepEqual(ipcOutput, buffer ? ['.'] : []);85};8686test('Subprocess can send messages right away, buffer false', testFastSend, false);87test('Subprocess can send messages right away, buffer true', testFastSend, true);87test('Subprocess can send messages right away, buffer false', () => testFastSend(false));88test('Subprocess can send messages right away, buffer true', () => testFastSend(true));
modified:test/ipc/reference.js+57 added-54 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';7import {PARALLEL_COUNT} from '../helpers/parallel.js';89setFixtureDirectory();109const testReference = async (t, fixtureName) => {10 const {timedOut} = await t.throwsAsync(execa(fixtureName, {ipc: true, timeout: 1e3}));11 t.true(timedOut);11const testReference = async fixtureName => {12 const {timedOut} = await assertRejects(execa(fixtureName, {ipc: true, timeout: 1e3}));13 assert.equal(timedOut, true);14};1514test('exports.getOneMessage() keeps the subprocess alive', testReference, 'ipc-get-ref.js');15test('exports.getEachMessage() keeps the subprocess alive', testReference, 'ipc-iterate-ref.js');16test('exports.getOneMessage() keeps the subprocess alive', () => testReference('ipc-get-ref.js'));17test('exports.getEachMessage() keeps the subprocess alive', () => testReference('ipc-iterate-ref.js'));1817const testUnreference = async (t, fixtureName) => {19const testUnreference = async fixtureName => {20 const {ipcOutput} = await execa(fixtureName, {ipc: true});19 t.deepEqual(ipcOutput, []);21 assert.deepEqual(ipcOutput, []);22};2322test('exports.getOneMessage() does not keep the subprocess alive, reference false', testUnreference, 'ipc-get-unref.js');23test('exports.getEachMessage() does not keep the subprocess alive, reference false', testUnreference, 'ipc-iterate-unref.js');24test('exports.getOneMessage() does not keep the subprocess alive, reference false', () => testUnreference('ipc-get-unref.js'));25test('exports.getEachMessage() does not keep the subprocess alive, reference false', () => testUnreference('ipc-iterate-unref.js'));2625test('exports.sendMessage() keeps the subprocess alive', async t => {27test('exports.sendMessage() keeps the subprocess alive', async () => {28 const {ipcOutput} = await execa('ipc-send-repeat.js', [`${PARALLEL_COUNT}`], {ipc: true});29 const expectedOutput = Array.from({length: PARALLEL_COUNT}, (_, index) => index);28 t.deepEqual(ipcOutput, expectedOutput);30 assert.deepEqual(ipcOutput, expectedOutput);31});3231test('process.send() keeps the subprocess alive', async t => {33test('process.send() keeps the subprocess alive', async () => {34 const {ipcOutput, stdout} = await execa('ipc-process-send.js', {ipc: true});33 t.deepEqual(ipcOutput, [foobarString]);34 t.is(stdout, '.');35 assert.deepEqual(ipcOutput, [foobarString]);36 assert.equal(stdout, '.');37});3837test('process.send() keeps the subprocess alive, after getOneMessage()', async t => {39test('process.send() keeps the subprocess alive, after getOneMessage()', async () => {40 const {ipcOutput, stdout} = await execa('ipc-process-send-get.js', {ipcInput: 0});39 t.deepEqual(ipcOutput, [foobarString]);40 t.is(stdout, '.');41 assert.deepEqual(ipcOutput, [foobarString]);42 assert.equal(stdout, '.');43});4443test('process.send() keeps the subprocess alive, after sendMessage()', async t => {45test('process.send() keeps the subprocess alive, after sendMessage()', async () => {46 const {ipcOutput, stdout} = await execa('ipc-process-send-send.js', {ipc: true});45 t.deepEqual(ipcOutput, ['.', foobarString]);46 t.is(stdout, '.');47 assert.deepEqual(ipcOutput, ['.', foobarString]);48 assert.equal(stdout, '.');49});5049test('process.once("message") keeps the subprocess alive', async t => {51test('process.once("message") keeps the subprocess alive', async () => {52 const subprocess = execa('ipc-once-message.js', {ipc: true});51 t.is(await subprocess.getOneMessage(), '.');53 assert.equal(await subprocess.getOneMessage(), '.');54 await subprocess.sendMessage(foobarString);5556 const {ipcOutput, stdout} = await subprocess;55 t.deepEqual(ipcOutput, ['.']);56 t.is(stdout, foobarString);57 assert.deepEqual(ipcOutput, ['.']);58 assert.equal(stdout, foobarString);59});6059test('process.once("message") keeps the subprocess alive, after sendMessage()', async t => {61test('process.once("message") keeps the subprocess alive, after sendMessage()', async () => {62 const subprocess = execa('ipc-once-message-send.js', {ipc: true});61 t.is(await subprocess.getOneMessage(), '.');63 assert.equal(await subprocess.getOneMessage(), '.');64 await subprocess.sendMessage(foobarString);6566 const {ipcOutput, stdout} = await subprocess;65 t.deepEqual(ipcOutput, ['.']);66 t.is(stdout, foobarString);67 assert.deepEqual(ipcOutput, ['.']);68 assert.equal(stdout, foobarString);69});7069test('process.once("message") keeps the subprocess alive, after getOneMessage()', async t => {71test('process.once("message") keeps the subprocess alive, after getOneMessage()', async () => {72 const subprocess = execa('ipc-once-message-get.js', {ipc: true});73 await subprocess.sendMessage('.');72 t.is(await subprocess.getOneMessage(), '.');74 assert.equal(await subprocess.getOneMessage(), '.');75 await subprocess.sendMessage(foobarString);7677 const {ipcOutput, stdout} = await subprocess;76 t.deepEqual(ipcOutput, ['.']);77 t.is(stdout, foobarString);78 assert.deepEqual(ipcOutput, ['.']);79 assert.equal(stdout, foobarString);80});8180test('process.once("disconnect") keeps the subprocess alive', async t => {82test('process.once("disconnect") keeps the subprocess alive', async () => {83 const subprocess = execa('ipc-once-disconnect.js', {ipc: true});82 t.is(await subprocess.getOneMessage(), '.');84 assert.equal(await subprocess.getOneMessage(), '.');85 subprocess.nodeChildProcess.disconnect();8687 const {ipcOutput, stdout} = await subprocess;86 t.deepEqual(ipcOutput, ['.']);87 t.is(stdout, '.');88 assert.deepEqual(ipcOutput, ['.']);89 assert.equal(stdout, '.');90});9190test('process.once("disconnect") keeps the subprocess alive, after sendMessage()', async t => {92test('process.once("disconnect") keeps the subprocess alive, after sendMessage()', async () => {93 const subprocess = execa('ipc-once-disconnect-send.js', {ipc: true});92 t.is(await subprocess.getOneMessage(), '.');93 t.is(await subprocess.getOneMessage(), '.');94 assert.equal(await subprocess.getOneMessage(), '.');95 // eslint-disable-next-line node-test/no-duplicate-assertions -- the same message is read twice on purpose96 assert.equal(await subprocess.getOneMessage(), '.');97 subprocess.nodeChildProcess.disconnect();9899 const {ipcOutput, stdout} = await subprocess;97 t.deepEqual(ipcOutput, ['.', '.']);98 t.is(stdout, '.');100 assert.deepEqual(ipcOutput, ['.', '.']);101 assert.equal(stdout, '.');102});103101test('process.once("disconnect") does not keep the subprocess alive, after getOneMessage()', async t => {104test('process.once("disconnect") does not keep the subprocess alive, after getOneMessage()', async () => {105 const subprocess = execa('ipc-once-disconnect-get.js', {ipc: true});106 await subprocess.sendMessage('.');104 t.is(await subprocess.getOneMessage(), '.');107 assert.equal(await subprocess.getOneMessage(), '.');108 subprocess.nodeChildProcess.disconnect();109110 const {ipcOutput, stdout} = await subprocess;108 t.deepEqual(ipcOutput, ['.']);109 t.is(stdout, '.');111 assert.deepEqual(ipcOutput, ['.']);112 assert.equal(stdout, '.');113});114112test('Can call subprocess.disconnect() right away', async t => {115test('Can call subprocess.disconnect() right away', async () => {116 const subprocess = execa('ipc-send.js', {ipc: true});117 subprocess.nodeChildProcess.disconnect();115 t.is(subprocess.nodeChildProcess.channel, null);118 assert.equal(subprocess.nodeChildProcess.channel, null);119117 await t.throwsAsync(subprocess.getOneMessage(), {120 await assertRejects(subprocess.getOneMessage(), {121 message: /subprocess.getOneMessage\(\) could not complete/,122 });120 await t.throwsAsync(subprocess, {123 await assertRejects(subprocess, {124 message: /Error: sendMessage\(\) cannot be used/,125 });126});127125test('Can call process.disconnect() right away', async t => {126 const {stdout, stderr} = await t.throwsAsync(execa('ipc-disconnect-get.js', {ipc: true}));127 t.is(stdout, 'null');128 t.true(stderr.includes('Error: getOneMessage() cannot be used'));128test('Can call process.disconnect() right away', async () => {129 const {stdout, stderr} = await assertRejects(execa('ipc-disconnect-get.js', {ipc: true}));130 assert.equal(stdout, 'null');131 assert.ok(stderr.includes('Error: getOneMessage() cannot be used'));132});
modified:test/ipc/send.js+60 added-58 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';7import {PARALLEL_COUNT} from '../helpers/parallel.js';8import {mockSendIoError} from '../helpers/ipc.js';910setFixtureDirectory();1110test('Can exchange IPC messages', async t => {12test('Can exchange IPC messages', async () => {13 const subprocess = execa('ipc-echo.js', {ipc: true});14 await subprocess.sendMessage(foobarString);13 t.is(await subprocess.getOneMessage(), foobarString);15 assert.equal(await subprocess.getOneMessage(), foobarString);16 await subprocess;17});1817test.serial('Can exchange IPC messages under heavy load', async t => {19test('Can exchange IPC messages under heavy load', async () => {20 await Promise.all(Array.from({length: PARALLEL_COUNT}, async (_, index) => {21 const subprocess = execa('ipc-echo.js', {ipc: true});22 await subprocess.sendMessage(index);21 t.is(await subprocess.getOneMessage(), index);23 assert.equal(await subprocess.getOneMessage(), index);24 await subprocess;25 }));26});2726test('The "serialization" option defaults to "advanced"', async t => {28test('The "serialization" option defaults to "advanced"', async () => {29 const subprocess = execa('ipc-echo.js', {ipc: true});30 await subprocess.sendMessage([0n]);31 const message = await subprocess.getOneMessage();30 t.is(message[0], 0n);32 assert.equal(message[0], 0n);33 await subprocess;34});3534test('Can use "serialization: json" option', async t => {36test('Can use "serialization: json" option', async () => {37 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});38 const date = new Date();39 await subprocess.sendMessage(date);38 t.is(await subprocess.getOneMessage(), date.toJSON());40 assert.equal(await subprocess.getOneMessage(), date.toJSON());41 await subprocess;42});4342test('Validates JSON payload with serialization: "json"', async t => {44test('Validates JSON payload with serialization: "json"', async () => {45 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json'});44 await t.throwsAsync(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});45 await t.throwsAsync(subprocess);46 await assertRejects(subprocess.sendMessage([0n]), {message: /serialize a BigInt/});47 await assertRejects(subprocess);48});4950const BIG_PAYLOAD_SIZE = '.'.repeat(1e6);5150test('Handles backpressure', async t => {52test('Handles backpressure', async () => {53 const subprocess = execa('ipc-iterate.js', {ipc: true});54 await subprocess.sendMessage(BIG_PAYLOAD_SIZE);53 t.true(subprocess.nodeChildProcess.send(foobarString));54 t.is(await subprocess.getOneMessage(), BIG_PAYLOAD_SIZE);55 assert.ok(subprocess.nodeChildProcess.send(foobarString));56 assert.equal(await subprocess.getOneMessage(), BIG_PAYLOAD_SIZE);57 const {ipcOutput} = await subprocess;56 t.deepEqual(ipcOutput, [BIG_PAYLOAD_SIZE]);58 assert.deepEqual(ipcOutput, [BIG_PAYLOAD_SIZE]);59});6059test('Disconnects IPC on exports.sendMessage() error', async t => {61test('Disconnects IPC on exports.sendMessage() error', async () => {62 const subprocess = execa('ipc-get-send-get.js', ['false'], {ipc: true});63 await subprocess.sendMessage(foobarString);62 t.is(await subprocess.getOneMessage(), foobarString);64 assert.equal(await subprocess.getOneMessage(), foobarString);6564 const {message, cause} = await t.throwsAsync(subprocess.sendMessage(0n));65 t.is(message, 'subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.');66 t.true(cause.message.includes('The "message" argument must be one of type string'));66 const {message, cause} = await assertRejects(subprocess.sendMessage(0n));67 assert.equal(message, 'subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.');68 assert.ok(cause.message.includes('The "message" argument must be one of type string'));6968 const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);69 t.is(exitCode, 1);70 t.false(isTerminated);71 t.true(stderr.includes('Error: getOneMessage() could not complete'));70 const {exitCode, isTerminated, stderr} = await assertRejects(subprocess);71 assert.equal(exitCode, 1);72 assert.equal(isTerminated, false);73 assert.ok(stderr.includes('Error: getOneMessage() could not complete'));74});7574test('Disconnects IPC on subprocess.sendMessage() error', async t => {76test('Disconnects IPC on subprocess.sendMessage() error', async () => {77 const subprocess = execa('ipc-send-error.js', {ipc: true});76 const ipcError = await t.throwsAsync(subprocess.getOneMessage());77 t.true(ipcError.message.includes('subprocess.getOneMessage() could not complete'));78 const ipcError = await assertRejects(subprocess.getOneMessage());79 assert.ok(ipcError.message.includes('subprocess.getOneMessage() could not complete'));8079 const {exitCode, isTerminated, stderr} = await t.throwsAsync(subprocess);80 t.is(exitCode, 1);81 t.false(isTerminated);82 t.true(stderr.includes('Error: sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.'));83 t.true(stderr.includes('The "message" argument must be one of type string'));81 const {exitCode, isTerminated, stderr} = await assertRejects(subprocess);82 assert.equal(exitCode, 1);83 assert.equal(isTerminated, false);84 assert.ok(stderr.includes('Error: sendMessage()\'s argument type is invalid: the message cannot be serialized: 0.'));85 assert.ok(stderr.includes('The "message" argument must be one of type string'));86});8788// EPIPE happens based on timing conditions, so we must repeat it until it happens87const findEpipeError = async t => {89const findEpipeError = async () => {90 while (true) {91 // eslint-disable-next-line no-await-in-loop90 const error = await t.throwsAsync(getEpipeError());92 const error = await assertRejects(getEpipeError());93 if (error.cause?.code === 'EPIPE') {94 return error;95 }96 }
7 unmodified lines
104 await subprocess.sendMessage('.');105 }106};107106test.serial('Can send messages while the subprocess is closing', async t => {107 const {message} = await findEpipeError(t);108 t.is(message, 'subprocess.sendMessage() cannot be used: the subprocess is disconnecting.');108test('Can send messages while the subprocess is closing', async () => {109 const {message} = await findEpipeError();110 assert.equal(message, 'subprocess.sendMessage() cannot be used: the subprocess is disconnecting.');111});112111test('subprocess.sendMessage() handles I/O errors', async t => {113test('subprocess.sendMessage() handles I/O errors', async () => {114 const subprocess = execa('ipc-echo.js', {ipc: true});115 const error = mockSendIoError(subprocess);114 t.is(await t.throwsAsync(subprocess.sendMessage('.')), error);116 assert.equal(await assertRejects(subprocess.sendMessage('.')), error);117116 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);117 t.is(exitCode, 1);118 t.false(isTerminated);119 t.true(message.includes('Error: getOneMessage()'));120 t.deepEqual(ipcOutput, []);118 const {exitCode, isTerminated, message, ipcOutput} = await assertRejects(subprocess);119 assert.equal(exitCode, 1);120 assert.equal(isTerminated, false);121 assert.ok(message.includes('Error: getOneMessage()'));122 assert.deepEqual(ipcOutput, []);123});124123test('Does not hold message events on I/O errors', async t => {125test('Does not hold message events on I/O errors', async () => {126 const subprocess = execa('ipc-echo.js', {ipc: true});127 const error = mockSendIoError(subprocess);128 const promise = subprocess.sendMessage('.');129 subprocess.nodeChildProcess.emit('message', '.');128 t.is(await t.throwsAsync(promise), error);130 assert.equal(await assertRejects(promise), error);131130 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(subprocess);131 t.is(exitCode, 1);132 t.false(isTerminated);133 t.true(message.includes('Error: getOneMessage()'));134 t.deepEqual(ipcOutput, ['.']);132 const {exitCode, isTerminated, message, ipcOutput} = await assertRejects(subprocess);133 assert.equal(exitCode, 1);134 assert.equal(isTerminated, false);135 assert.ok(message.includes('Error: getOneMessage()'));136 assert.deepEqual(ipcOutput, ['.']);137});138137test('exports.sendMessage() handles I/O errors', async t => {138 const {exitCode, isTerminated, message, ipcOutput} = await t.throwsAsync(execa('ipc-send-io-error.js', {ipc: true}));139 t.is(exitCode, 1);140 t.false(isTerminated);141 t.true(message.includes(`Error: ${foobarString}`));142 t.deepEqual(ipcOutput, []);139test('exports.sendMessage() handles I/O errors', async () => {140 const {exitCode, isTerminated, message, ipcOutput} = await assertRejects(execa('ipc-send-io-error.js', {ipc: true}));141 assert.equal(exitCode, 1);142 assert.equal(isTerminated, false);143 assert.ok(message.includes(`Error: ${foobarString}`));144 assert.deepEqual(ipcOutput, []);145});
modified:test/ipc/strict.js+146 added-127 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';2import test from 'ava';3import {setTimeout} from 'node:timers/promises';4import test from 'node:test';5import {assertRejects} from '../helpers/assert.js';6import {execa} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {foobarString} from '../helpers/input.js';9import {assertMaxListeners} from '../helpers/listeners.js';
1 unmodified line
11import {PARALLEL_COUNT} from '../helpers/parallel.js';1213setFixtureDirectory();1412const testStrictSuccessParentOne = async (t, buffer) => {15const testStrictSuccessParentOne = async buffer => {16 const subprocess = execa('ipc-echo.js', {ipc: true, buffer});17 await subprocess.sendMessage(foobarString, {strict: true});15 t.is(await subprocess.getOneMessage(), foobarString);18 assert.equal(await subprocess.getOneMessage(), foobarString);1920 const {ipcOutput} = await subprocess;18 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);21 assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);22};2321test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer false', testStrictSuccessParentOne, false);22test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer true', testStrictSuccessParentOne, true);24test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer false', () => testStrictSuccessParentOne(false));25test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer true', () => testStrictSuccessParentOne(true));2624const testStrictSuccessParentEach = async (t, buffer) => {27const testStrictSuccessParentEach = async buffer => {28 const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});29 await subprocess.sendMessage('.', {strict: true});27 t.is(await subprocess.getOneMessage(), '.');30 assert.equal(await subprocess.getOneMessage(), '.');31 await subprocess.sendMessage(foobarString);3233 const {ipcOutput} = await subprocess;31 t.deepEqual(ipcOutput, buffer ? ['.'] : []);34 assert.deepEqual(ipcOutput, buffer ? ['.'] : []);35};3634test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer false', testStrictSuccessParentEach, false);35test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer true', testStrictSuccessParentEach, true);37test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer false', () => testStrictSuccessParentEach(false));38test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer true', () => testStrictSuccessParentEach(true));3937const testStrictMissingParent = async (t, buffer) => {40const testStrictMissingParent = async buffer => {41 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString, buffer});42 const promise = subprocess.getOneMessage();43 const secondPromise = subprocess.sendMessage(foobarString, {strict: true});41 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));42 t.is(message, 'subprocess.sendMessage() failed: the subprocess is not listening to incoming messages.');43 t.is(await promise, foobarString);44 const {message} = await assertRejects(subprocess.sendMessage(foobarString, {strict: true}));45 assert.equal(message, 'subprocess.sendMessage() failed: the subprocess is not listening to incoming messages.');46 assert.equal(await promise, foobarString);47 await secondPromise;4849 const {ipcOutput} = await subprocess;47 t.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);50 assert.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);51};5250test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer false', testStrictMissingParent, false);51test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer true', testStrictMissingParent, true);53test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer false', () => testStrictMissingParent(false));54test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer true', () => testStrictMissingParent(true));5553const testStrictExit = async (t, buffer) => {56const testStrictExit = async buffer => {57 const subprocess = execa('ipc-send.js', {ipc: true, buffer});55 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));56 t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');58 const {message} = await assertRejects(subprocess.sendMessage(foobarString, {strict: true}));59 assert.equal(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');6061 const {ipcOutput} = await subprocess;59 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);62 assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);63};6462test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer false', testStrictExit, false);63test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer true', testStrictExit, true);65test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer false', () => testStrictExit(false));66test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer true', () => testStrictExit(true));6765const testStrictSuccessSubprocess = async (t, getMessage, buffer) => {68const testStrictSuccessSubprocess = async (getMessage, buffer) => {69 const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer});67 t.is(await getMessage(subprocess), foobarString);70 assert.equal(await getMessage(subprocess), foobarString);7172 const {ipcOutput} = await subprocess;70 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);73 assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);74};7573test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer false', testStrictSuccessSubprocess, subprocessGetOne, false);74test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer true', testStrictSuccessSubprocess, subprocessGetOne, true);75test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer false', testStrictSuccessSubprocess, subprocessGetFirst, false);76test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer true', testStrictSuccessSubprocess, subprocessGetFirst, true);76test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer false', () => testStrictSuccessSubprocess(subprocessGetOne, false));77test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer true', () => testStrictSuccessSubprocess(subprocessGetOne, true));78test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer false', () => testStrictSuccessSubprocess(subprocessGetFirst, false));79test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer true', () => testStrictSuccessSubprocess(subprocessGetFirst, true));8078test('exports.sendMessage() "strict" succeeds if the current process uses result.ipcOutput', async t => {81test('exports.sendMessage() "strict" succeeds if the current process uses result.ipcOutput', async () => {82 const {ipcOutput} = await execa('ipc-send-strict.js', {ipc: true});80 t.deepEqual(ipcOutput, [foobarString]);83 assert.deepEqual(ipcOutput, [foobarString]);84});8583test('exports.sendMessage() "strict" fails if the current process is not listening, buffer false', async t => {84 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}}));85 t.is(exitCode, 1);86 t.false(isTerminated);87 t.true(stderr.includes('Error: sendMessage() failed: the parent process is not listening to incoming messages.'));88 t.deepEqual(ipcOutput, []);86test('exports.sendMessage() "strict" fails if the current process is not listening, buffer false', async () => {87 const {exitCode, isTerminated, stderr, ipcOutput} = await assertRejects(execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}}));88 assert.equal(exitCode, 1);89 assert.equal(isTerminated, false);90 assert.ok(stderr.includes('Error: sendMessage() failed: the parent process is not listening to incoming messages.'));91 assert.deepEqual(ipcOutput, []);92});9391test.serial('Multiple subprocess.sendMessage() "strict" at once', async t => {92 const checkMaxListeners = assertMaxListeners(t);94test('Multiple subprocess.sendMessage() "strict" at once', async () => {95 const checkMaxListeners = assertMaxListeners();9697 const subprocess = execa('ipc-iterate.js', {ipc: true});98 const messages = Array.from({length: PARALLEL_COUNT}, (_, index) => index);99 await Promise.all(messages.map(message => subprocess.sendMessage(message, {strict: true})));100 await subprocess.sendMessage(foobarString);101102 const {ipcOutput} = await subprocess;100 t.deepEqual(ipcOutput, messages);103 assert.deepEqual(ipcOutput, messages);104105 checkMaxListeners();106});107105test('subprocess.sendMessage() "strict" fails if the subprocess uses once()', async t => {108test('subprocess.sendMessage() "strict" fails if the subprocess uses once()', async () => {109 const subprocess = execa('ipc-once-message.js', {ipc: true});107 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));108 t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');110 const {message} = await assertRejects(subprocess.sendMessage(foobarString, {strict: true}));111 assert.equal(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');112113 const {ipcOutput} = await subprocess;111 t.deepEqual(ipcOutput, ['.']);114 assert.deepEqual(ipcOutput, ['.']);115});116114test('exports.sendMessage() "strict" fails if the current process uses once() and buffer false', async t => {117test('exports.sendMessage() "strict" fails if the current process uses once() and buffer false', async () => {118 const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}});119 const [message] = await once(subprocess.nodeChildProcess, 'message');117 t.deepEqual(message, {120 assert.deepEqual(message, {121 id: 0,122 type: 'execa:ipc:request',123 message: foobarString,124 hasListeners: false,125 });126124 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);125 t.is(exitCode, 1);126 t.false(isTerminated);127 t.true(stderr.includes('Error: sendMessage() failed: the parent process is not listening to incoming messages.'));128 t.deepEqual(ipcOutput, []);127 const {exitCode, isTerminated, stderr, ipcOutput} = await assertRejects(subprocess);128 assert.equal(exitCode, 1);129 assert.equal(isTerminated, false);130 assert.ok(stderr.includes('Error: sendMessage() failed: the parent process is not listening to incoming messages.'));131 assert.deepEqual(ipcOutput, []);132});133131test('subprocess.sendMessage() "strict" failure disconnects', async t => {134test('subprocess.sendMessage() "strict" failure disconnects', async () => {135 const subprocess = execa('ipc-echo-twice-wait.js', {ipcInput: foobarString});136 const promise = subprocess.getOneMessage();137 const secondPromise = subprocess.sendMessage(foobarString, {strict: true});135 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));136 t.is(message, 'subprocess.sendMessage() failed: the subprocess is not listening to incoming messages.');137 t.is(await promise, foobarString);138 const {message} = await assertRejects(subprocess.sendMessage(foobarString, {strict: true}));139 assert.equal(message, 'subprocess.sendMessage() failed: the subprocess is not listening to incoming messages.');140 assert.equal(await promise, foobarString);141 await secondPromise;142140 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);141 t.is(exitCode, 1);142 t.false(isTerminated);143 t.true(stderr.includes('Error: sendMessage() cannot be used: the parent process has already exited or disconnected.'));144 t.deepEqual(ipcOutput, [foobarString, foobarString]);143 const {exitCode, isTerminated, stderr, ipcOutput} = await assertRejects(subprocess);144 assert.equal(exitCode, 1);145 assert.equal(isTerminated, false);146 assert.ok(stderr.includes('Error: sendMessage() cannot be used: the parent process has already exited or disconnected.'));147 assert.deepEqual(ipcOutput, [foobarString, foobarString]);148});149147test('exports.sendMessage() "strict" failure disconnects', async t => {148 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(execa('ipc-send-strict-catch.js', {ipc: true, buffer: {ipc: false}}));149 t.is(exitCode, 1);150 t.false(isTerminated);151 t.true(stderr.includes('Error: sendMessage() cannot be used: the parent process has already exited or disconnected.'));152 t.deepEqual(ipcOutput, []);150test('exports.sendMessage() "strict" failure disconnects', async () => {151 const {exitCode, isTerminated, stderr, ipcOutput} = await assertRejects(execa('ipc-send-strict-catch.js', {ipc: true, buffer: {ipc: false}}));152 assert.equal(exitCode, 1);153 assert.equal(isTerminated, false);154 assert.ok(stderr.includes('Error: sendMessage() cannot be used: the parent process has already exited or disconnected.'));155 assert.deepEqual(ipcOutput, []);156});157155const testIoErrorParent = async (t, getMessage) => {158const testIoErrorParent = async getMessage => {159 const subprocess = execa('ipc-send-strict.js', {ipc: true});160 const cause = mockSendIoError(subprocess);158 const error = await t.throwsAsync(getMessage(subprocess));159 t.true(error.message.includes('subprocess.sendMessage() failed when sending an acknowledgment response to the subprocess.'));160 t.is(getMessage === subprocessGetOne ? error.cause : error.cause.cause, cause);161 const error = await assertRejects(getMessage(subprocess));162 assert.ok(error.message.includes('subprocess.sendMessage() failed when sending an acknowledgment response to the subprocess.'));163 assert.equal(getMessage === subprocessGetOne ? error.cause : error.cause.cause, cause);164162 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);163 t.is(exitCode, 1);164 t.false(isTerminated);165 t.true(stderr.includes('Error: sendMessage() failed: the parent process exited without listening to incoming messages.'));166 t.deepEqual(ipcOutput, []);165 const {exitCode, isTerminated, stderr, ipcOutput} = await assertRejects(subprocess);166 assert.equal(exitCode, 1);167 assert.equal(isTerminated, false);168 assert.ok(stderr.includes('Error: sendMessage() failed: the parent process exited without listening to incoming messages.'));169 assert.deepEqual(ipcOutput, []);170};171169test('subprocess.getOneMessage() acknowledgment I/O error', testIoErrorParent, subprocessGetOne);170test('subprocess.getEachMessage() acknowledgment I/O error', testIoErrorParent, subprocessGetFirst);172test('subprocess.getOneMessage() acknowledgment I/O error', () => testIoErrorParent(subprocessGetOne));173test('subprocess.getEachMessage() acknowledgment I/O error', () => testIoErrorParent(subprocessGetFirst));174172const testIoErrorSubprocess = async (t, fixtureName) => {175const testIoErrorSubprocess = async fixtureName => {176 const subprocess = execa(fixtureName, {ipc: true});174 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));175 t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');177 const {message} = await assertRejects(subprocess.sendMessage(foobarString, {strict: true}));178 assert.equal(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');179177 const {exitCode, isTerminated, stdout, stderr, ipcOutput} = await t.throwsAsync(subprocess);178 t.is(exitCode, 1);179 t.false(isTerminated);180 t.is(stdout, '');181 t.true(stderr.includes('Error: sendMessage() failed when sending an acknowledgment response to the parent process.'));182 t.true(stderr.includes(`Error: ${foobarString}`));183 t.deepEqual(ipcOutput, []);180 const {exitCode, isTerminated, stdout, stderr, ipcOutput} = await assertRejects(subprocess);181 assert.equal(exitCode, 1);182 assert.equal(isTerminated, false);183 assert.equal(stdout, '');184 assert.ok(stderr.includes('Error: sendMessage() failed when sending an acknowledgment response to the parent process.'));185 assert.ok(stderr.includes(`Error: ${foobarString}`));186 assert.deepEqual(ipcOutput, []);187};188186test('exports.getOneMessage() acknowledgment I/O error', testIoErrorSubprocess, 'ipc-get-io-error.js');187test('exports.getEachMessage() acknowledgment I/O error', testIoErrorSubprocess, 'ipc-iterate-io-error.js');189test('exports.getOneMessage() acknowledgment I/O error', () => testIoErrorSubprocess('ipc-get-io-error.js'));190test('exports.getEachMessage() acknowledgment I/O error', () => testIoErrorSubprocess('ipc-iterate-io-error.js'));191189test('Opposite sendMessage() "strict", buffer true', async t => {192test('Opposite sendMessage() "strict", buffer true', async () => {193 const subprocess = execa('ipc-send-strict-get.js', {ipc: true});194 await subprocess.sendMessage(foobarString, {strict: true});195196 const {ipcOutput} = await subprocess;194 t.deepEqual(ipcOutput, [foobarString, foobarString]);197 assert.deepEqual(ipcOutput, [foobarString, foobarString]);198});199197test('Opposite sendMessage() "strict", current process listening, buffer false', async t => {200test('Opposite sendMessage() "strict", current process listening, buffer false', async () => {201 const subprocess = execa('ipc-send-strict-get.js', {ipc: true, buffer: {ipc: false}});202 const [message] = await Promise.all([203 subprocess.getOneMessage(),204 subprocess.sendMessage(foobarString, {strict: true}),205 ]);203 t.is(message, foobarString);204 t.is(await subprocess.getOneMessage(), foobarString);206 assert.equal(message, foobarString);207 assert.equal(await subprocess.getOneMessage(), foobarString);208209 const {ipcOutput} = await subprocess;207 t.deepEqual(ipcOutput, []);210 assert.deepEqual(ipcOutput, []);211});212210test('Opposite sendMessage() "strict", subprocess listening, buffer false', async t => {213test('Opposite sendMessage() "strict", subprocess listening, buffer false', async () => {214 const subprocess = execa('ipc-send-strict-listen.js', {ipc: true, buffer: {ipc: false}});215 await subprocess.sendMessage(foobarString, {strict: true});213 t.is(await subprocess.getOneMessage(), foobarString);216 assert.equal(await subprocess.getOneMessage(), foobarString);217218 const {ipcOutput} = await subprocess;216 t.deepEqual(ipcOutput, []);219 assert.deepEqual(ipcOutput, []);220});221219test('Opposite sendMessage() "strict", not listening, buffer false', async t => {222test('Opposite sendMessage() "strict", not listening, buffer false', async () => {223 const subprocess = execa('ipc-send-strict.js', {ipc: true, buffer: {ipc: false}});221 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));222 t.true(message.startsWith('subprocess.sendMessage() failed: the subprocess is sending a message too, instead of listening to incoming messages.'));224 const {message} = await assertRejects(subprocess.sendMessage(foobarString, {strict: true}));225 assert.ok(message.startsWith('subprocess.sendMessage() failed: the subprocess is sending a message too, instead of listening to incoming messages.'));226224 const {exitCode, isTerminated, stderr, ipcOutput} = await t.throwsAsync(subprocess);225 t.is(exitCode, 1);226 t.false(isTerminated);227 t.true(stderr.includes('Error: sendMessage() failed: the parent process is sending a message too, instead of listening to incoming messages.'));228 t.deepEqual(ipcOutput, []);227 const {exitCode, isTerminated, stderr, ipcOutput} = await assertRejects(subprocess);228 assert.equal(exitCode, 1);229 assert.equal(isTerminated, false);230 assert.ok(stderr.includes('Error: sendMessage() failed: the parent process is sending a message too, instead of listening to incoming messages.'));231 assert.deepEqual(ipcOutput, []);232});233231test('Ignores "strict" responses with an Object.prototype property as id', async t => {234test('Ignores "strict" responses with an Object.prototype property as id', async () => {235 const {ipcOutput} = await execa('ipc-send-strict-proto.js', {ipc: true});233 t.deepEqual(ipcOutput, []);236 assert.deepEqual(ipcOutput, []);237});238239// `forever.js` does not use Execa, so it never acknowledges the message240test('Ignores "strict" responses sent by another subprocess', async () => {241 const subprocess = execa('forever.js', {ipc: true});242 const sendPromise = subprocess.sendMessage(foobarString, {strict: true});243244 try {245 const {ipcOutput} = await execa('ipc-send-strict-forged.js', {ipc: true});246 assert.deepEqual(ipcOutput, []);247 assert.equal(await Promise.race([sendPromise.then(() => 'resolved'), setTimeout(500, 'pending')]), 'pending');248 } finally {249 subprocess.kill();250 }251252 await Promise.all([assertRejects(sendPromise), assertRejects(subprocess)]);253});254236const testStrictJson = async (t, buffer) => {255const testStrictJson = async buffer => {256 const subprocess = execa('ipc-echo.js', {ipc: true, serialization: 'json', buffer});257 await subprocess.sendMessage(foobarString, {strict: true});239 t.is(await subprocess.getOneMessage(), foobarString);258 assert.equal(await subprocess.getOneMessage(), foobarString);259260 const {ipcOutput} = await subprocess;242 t.deepEqual(ipcOutput, buffer ? [foobarString] : []);261 assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);262};263245test('subprocess.sendMessage() "strict" works with serialization "json", buffer false', testStrictJson, false);246test('subprocess.sendMessage() "strict" works with serialization "json", buffer true', testStrictJson, true);264test('subprocess.sendMessage() "strict" works with serialization "json", buffer false', () => testStrictJson(false));265test('subprocess.sendMessage() "strict" works with serialization "json", buffer true', () => testStrictJson(true));266248test('exports.sendMessage() "strict" works with serialization "json"', async t => {267test('exports.sendMessage() "strict" works with serialization "json"', async () => {268 const subprocess = execa('ipc-send-strict-get.js', {ipc: true, serialization: 'json'});269 await subprocess.sendMessage(foobarString, {strict: true});270271 const {ipcOutput} = await subprocess;253 t.deepEqual(ipcOutput, [foobarString, foobarString]);272 assert.deepEqual(ipcOutput, [foobarString, foobarString]);273});274256test('subprocess.sendMessage() "strict" fails with serialization "json" if the subprocess is not listening', async t => {275test('subprocess.sendMessage() "strict" fails with serialization "json" if the subprocess is not listening', async () => {276 const subprocess = execa('ipc-send.js', {ipc: true, serialization: 'json'});258 const {message} = await t.throwsAsync(subprocess.sendMessage(foobarString, {strict: true}));259 t.is(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');277 const {message} = await assertRejects(subprocess.sendMessage(foobarString, {strict: true}));278 assert.equal(message, 'subprocess.sendMessage() failed: the subprocess exited without listening to incoming messages.');279280 const {ipcOutput} = await subprocess;262 t.deepEqual(ipcOutput, [foobarString]);281 assert.deepEqual(ipcOutput, [foobarString]);282});283284const noop = () => {};285286// Messages received in the same batch are processed one after the other.287// The deadlock must be detected on the message being processed, not on the first one received.288// Without the detection, the subprocess would deadlock, so the `timeout` turns that hang into a failed assertion.270test('Detects a "strict" deadlock on a later message of the same batch', async t => {289test('Detects a "strict" deadlock on a later message of the same batch', async () => {290 const subprocess = execa('ipc-echo-strict-deadlock.js', {ipc: true, buffer: {ipc: false}, timeout: 1e4});291 await subprocess.sendMessage(foobarString);292 subprocess.sendMessage(foobarString, {strict: true}).catch(noop);293275 const {exitCode, timedOut, stderr, ipcOutput} = await t.throwsAsync(subprocess);276 t.false(timedOut);277 t.is(exitCode, 1);278 t.true(stderr.includes('Error: sendMessage() failed: the parent process is sending a message too, instead of listening to incoming messages.'));279 t.deepEqual(ipcOutput, []);294 const {exitCode, timedOut, stderr, ipcOutput} = await assertRejects(subprocess);295 assert.equal(timedOut, false);296 assert.equal(exitCode, 1);297 assert.ok(stderr.includes('Error: sendMessage() failed: the parent process is sending a message too, instead of listening to incoming messages.'));298 assert.deepEqual(ipcOutput, []);299});
modified:test/ipc/validation.js+54 added-52 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows, assertRejects} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';78setFixtureDirectory();98const testRequiredIpcSubprocess = async (t, methodName, options) => {10const testRequiredIpcSubprocess = async (methodName, options) => {11 const subprocess = execa('empty.js', options);10 const {message} = await t.throws(() => subprocess[methodName]());11 t.true(message.includes(`subprocess.${methodName}() can only be used`));12 const {message} = await assertThrows(() => subprocess[methodName]());13 assert.ok(message.includes(`subprocess.${methodName}() can only be used`));14 await subprocess;15};1615test('Cannot use subprocess.sendMessage() without ipc option', testRequiredIpcSubprocess, 'sendMessage', {});16test('Cannot use subprocess.sendMessage() with ipc: false', testRequiredIpcSubprocess, 'sendMessage', {ipc: false});17test('Cannot use subprocess.getOneMessage() without ipc option', testRequiredIpcSubprocess, 'getOneMessage', {});18test('Cannot use subprocess.getOneMessage() with ipc: false', testRequiredIpcSubprocess, 'getOneMessage', {ipc: false});19test('Cannot use subprocess.getEachMessage() without ipc option', testRequiredIpcSubprocess, 'getEachMessage', {});20test('Cannot use subprocess.getEachMessage() with ipc: false', testRequiredIpcSubprocess, 'getEachMessage', {ipc: false});17test('Cannot use subprocess.sendMessage() without ipc option', () => testRequiredIpcSubprocess('sendMessage', {}));18test('Cannot use subprocess.sendMessage() with ipc: false', () => testRequiredIpcSubprocess('sendMessage', {ipc: false}));19test('Cannot use subprocess.getOneMessage() without ipc option', () => testRequiredIpcSubprocess('getOneMessage', {}));20test('Cannot use subprocess.getOneMessage() with ipc: false', () => testRequiredIpcSubprocess('getOneMessage', {ipc: false}));21test('Cannot use subprocess.getEachMessage() without ipc option', () => testRequiredIpcSubprocess('getEachMessage', {}));22test('Cannot use subprocess.getEachMessage() with ipc: false', () => testRequiredIpcSubprocess('getEachMessage', {ipc: false}));2322const testRequiredIpcExports = async (t, methodName, options) => {23 const {message} = await t.throwsAsync(execa('ipc-any.js', [methodName], options));24 t.true(message.includes(`${methodName}() can only be used`));24const testRequiredIpcExports = async (methodName, options) => {25 const {message} = await assertRejects(execa('ipc-any.js', [methodName], options));26 assert.ok(message.includes(`${methodName}() can only be used`));27};2827test('Cannot use exports.sendMessage() without ipc option', testRequiredIpcExports, 'sendMessage', {});28test('Cannot use exports.sendMessage() with ipc: false', testRequiredIpcExports, 'sendMessage', {ipc: false});29test('Cannot use exports.getOneMessage() without ipc option', testRequiredIpcExports, 'getOneMessage', {});30test('Cannot use exports.getOneMessage() with ipc: false', testRequiredIpcExports, 'getOneMessage', {ipc: false});31test('Cannot use exports.getEachMessage() without ipc option', testRequiredIpcExports, 'getEachMessage', {});32test('Cannot use exports.getEachMessage() with ipc: false', testRequiredIpcExports, 'getEachMessage', {ipc: false});29test('Cannot use exports.sendMessage() without ipc option', () => testRequiredIpcExports('sendMessage', {}));30test('Cannot use exports.sendMessage() with ipc: false', () => testRequiredIpcExports('sendMessage', {ipc: false}));31test('Cannot use exports.getOneMessage() without ipc option', () => testRequiredIpcExports('getOneMessage', {}));32test('Cannot use exports.getOneMessage() with ipc: false', () => testRequiredIpcExports('getOneMessage', {ipc: false}));33test('Cannot use exports.getEachMessage() without ipc option', () => testRequiredIpcExports('getEachMessage', {}));34test('Cannot use exports.getEachMessage() with ipc: false', () => testRequiredIpcExports('getEachMessage', {ipc: false}));3534const testPostDisconnection = async (t, methodName) => {36const testPostDisconnection = async methodName => {37 const subprocess = execa('empty.js', {ipc: true});38 await subprocess;37 const {message} = t.throws(() => subprocess[methodName](foobarString));38 t.true(message.includes(`subprocess.${methodName}() cannot be used`));39 const {message} = assertThrows(() => subprocess[methodName](foobarString));40 assert.ok(message.includes(`subprocess.${methodName}() cannot be used`));41};4241test('subprocess.sendMessage() after disconnection', testPostDisconnection, 'sendMessage');42test('subprocess.getOneMessage() after disconnection', testPostDisconnection, 'getOneMessage');43test('subprocess.getEachMessage() after disconnection', testPostDisconnection, 'getEachMessage');43test('subprocess.sendMessage() after disconnection', () => testPostDisconnection('sendMessage'));44test('subprocess.getOneMessage() after disconnection', () => testPostDisconnection('getOneMessage'));45test('subprocess.getEachMessage() after disconnection', () => testPostDisconnection('getEachMessage'));4645const testPostDisconnectionSubprocess = async (t, methodName) => {47const testPostDisconnectionSubprocess = async methodName => {48 const subprocess = execa('ipc-disconnect.js', [methodName], {ipc: true});49 subprocess.nodeChildProcess.disconnect();48 const {message} = await t.throwsAsync(subprocess);49 t.true(message.includes(`${methodName}() cannot be used`));50 const {message} = await assertRejects(subprocess);51 assert.ok(message.includes(`${methodName}() cannot be used`));52};5352test('exports.sendMessage() after disconnection', testPostDisconnectionSubprocess, 'sendMessage');53test('exports.getOneMessage() after disconnection', testPostDisconnectionSubprocess, 'getOneMessage');54test('exports.getEachMessage() after disconnection', testPostDisconnectionSubprocess, 'getEachMessage');54test('exports.sendMessage() after disconnection', () => testPostDisconnectionSubprocess('sendMessage'));55test('exports.getOneMessage() after disconnection', () => testPostDisconnectionSubprocess('getOneMessage'));56test('exports.getEachMessage() after disconnection', () => testPostDisconnectionSubprocess('getEachMessage'));5758const INVALID_TYPE_MESSAGE = 'The "message" argument must be one of type string';59const UNDEFINED_MESSAGE = 'The "message" argument must be specified';60const CLONE_MESSAGE = 'could not be cloned';61const CYCLE_MESSAGE = 'Converting circular structure to JSON';62const MAX_CALL_STACK_MESSAGE = 'Maximum call stack size exceeded';6362const testInvalidPayload = async (t, serialization, message, expectedMessage) => {64const testInvalidPayload = async (serialization, message, expectedMessage) => {65 const subprocess = execa('empty.js', {ipc: true, serialization});64 const error = await t.throwsAsync(subprocess.sendMessage(message));65 t.true(error.message.includes('subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized'));66 t.true(error.cause.message.includes(expectedMessage));66 const error = await assertRejects(subprocess.sendMessage(message));67 assert.ok(error.message.includes('subprocess.sendMessage()\'s argument type is invalid: the message cannot be serialized'));68 assert.ok(error.cause.message.includes(expectedMessage));69 await subprocess;70};7172const cycleObject = {};73cycleObject.self = cycleObject;74const toJsonCycle = {toJSON: () => ({test: true, toJsonCycle})};7574test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'advanced', undefined, UNDEFINED_MESSAGE);75test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'advanced', 0n, INVALID_TYPE_MESSAGE);76test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'advanced', Symbol('test'), INVALID_TYPE_MESSAGE);77test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'advanced', () => {}, INVALID_TYPE_MESSAGE);78test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'advanced', Promise.resolve(), CLONE_MESSAGE);79test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'advanced', new Proxy({}, {}), CLONE_MESSAGE);80test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'advanced', new Intl.Collator(), CLONE_MESSAGE);81test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'json', undefined, UNDEFINED_MESSAGE);82test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'json', 0n, INVALID_TYPE_MESSAGE);83test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'json', Symbol('test'), INVALID_TYPE_MESSAGE);84test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'json', () => {}, INVALID_TYPE_MESSAGE);85test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'json', cycleObject, CYCLE_MESSAGE);86test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'json', toJsonCycle, MAX_CALL_STACK_MESSAGE);76test('subprocess.sendMessage() cannot send undefined', () => testInvalidPayload('advanced', undefined, UNDEFINED_MESSAGE));77test('subprocess.sendMessage() cannot send bigints', () => testInvalidPayload('advanced', 0n, INVALID_TYPE_MESSAGE));78test('subprocess.sendMessage() cannot send symbols', () => testInvalidPayload('advanced', Symbol('test'), INVALID_TYPE_MESSAGE));79test('subprocess.sendMessage() cannot send functions', () => testInvalidPayload('advanced', () => {}, INVALID_TYPE_MESSAGE));80test('subprocess.sendMessage() cannot send promises', () => testInvalidPayload('advanced', Promise.resolve(), CLONE_MESSAGE));81test('subprocess.sendMessage() cannot send proxies', () => testInvalidPayload('advanced', new Proxy({}, {}), CLONE_MESSAGE));82test('subprocess.sendMessage() cannot send Intl', () => testInvalidPayload('advanced', new Intl.Collator(), CLONE_MESSAGE));83test('subprocess.sendMessage() cannot send undefined, JSON', () => testInvalidPayload('json', undefined, UNDEFINED_MESSAGE));84test('subprocess.sendMessage() cannot send bigints, JSON', () => testInvalidPayload('json', 0n, INVALID_TYPE_MESSAGE));85test('subprocess.sendMessage() cannot send symbols, JSON', () => testInvalidPayload('json', Symbol('test'), INVALID_TYPE_MESSAGE));86test('subprocess.sendMessage() cannot send functions, JSON', () => testInvalidPayload('json', () => {}, INVALID_TYPE_MESSAGE));87test('subprocess.sendMessage() cannot send cycles, JSON', () => testInvalidPayload('json', cycleObject, CYCLE_MESSAGE));88test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', () => testInvalidPayload('json', toJsonCycle, MAX_CALL_STACK_MESSAGE));8988test('exports.sendMessage() validates payload', async t => {90test('exports.sendMessage() validates payload', async () => {91 const subprocess = execa('ipc-echo-item.js', {ipc: true});92 await subprocess.sendMessage([undefined]);91 const {message} = await t.throwsAsync(subprocess);92 t.true(message.includes('Error: sendMessage()\'s argument type is invalid: the message cannot be serialized'));93 t.true(message.includes(UNDEFINED_MESSAGE));93 const {message} = await assertRejects(subprocess);94 assert.ok(message.includes('Error: sendMessage()\'s argument type is invalid: the message cannot be serialized'));95 assert.ok(message.includes(UNDEFINED_MESSAGE));96});
modified:test/methods/bind.js+61 added-59 removed
1import assert from 'node:assert/strict';2import path from 'node:path';2import test from 'ava';3import test from 'node:test';4import {assertRejects} from '../helpers/assert.js';5import {6 execa,7 execaSync,8 execaNode,
7 unmodified lines
1617const NOOP_PATH = path.join(FIXTURES_DIRECTORY, 'noop.js');18const PRINT_ENV_PATH = path.join(FIXTURES_DIRECTORY, 'environment.js');1918const testBindOptions = async (t, execaMethod) => {20const testBindOptions = async execaMethod => {21 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);20 t.is(stdout, `${foobarString}\n`);22 assert.equal(stdout, `${foobarString}\n`);23};2423test('execa() can bind options', testBindOptions, execa);24test('execaNode() can bind options', testBindOptions, execaNode);25test('$ can bind options', testBindOptions, $);25test('execa() can bind options', () => testBindOptions(execa));26test('execaNode() can bind options', () => testBindOptions(execaNode));27test('$ can bind options', () => testBindOptions($));2827const testBindOptionsSync = (t, execaMethod) => {29const testBindOptionsSync = execaMethod => {30 const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);29 t.is(stdout, `${foobarString}\n`);31 assert.equal(stdout, `${foobarString}\n`);32};3332test('execaSync() can bind options', testBindOptionsSync, execaSync);33test('$.sync can bind options', testBindOptionsSync, $.sync);34test('execaSync() can bind options', () => testBindOptionsSync(execaSync));35test('$.sync can bind options', () => testBindOptionsSync($.sync));3635const testBindPriority = async (t, execaMethod) => {37const testBindPriority = async execaMethod => {38 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: true});37 t.is(stdout, foobarString);39 assert.equal(stdout, foobarString);40};4140test('execa() bound options have lower priority', testBindPriority, execa);41test('execaSync() bound options have lower priority', testBindPriority, execaSync);42test('execaNode() bound options have lower priority', testBindPriority, execaNode);43test('$ bound options have lower priority', testBindPriority, $);44test('$.sync bound options have lower priority', testBindPriority, $.sync);42test('execa() bound options have lower priority', () => testBindPriority(execa));43test('execaSync() bound options have lower priority', () => testBindPriority(execaSync));44test('execaNode() bound options have lower priority', () => testBindPriority(execaNode));45test('$ bound options have lower priority', () => testBindPriority($));46test('$.sync bound options have lower priority', () => testBindPriority($.sync));4746const testBindUndefined = async (t, execaMethod) => {48const testBindUndefined = async execaMethod => {49 const {stdout} = await execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString], {stripFinalNewline: undefined});48 t.is(stdout, foobarString);50 assert.equal(stdout, foobarString);51};5251test('execa() undefined options use default value', testBindUndefined, execa);52test('execaSync() undefined options use default value', testBindUndefined, execaSync);53test('execaNode() undefined options use default value', testBindUndefined, execaNode);54test('$ undefined options use default value', testBindUndefined, $);55test('$.sync undefined options use default value', testBindUndefined, $.sync);53test('execa() undefined options use default value', () => testBindUndefined(execa));54test('execaSync() undefined options use default value', () => testBindUndefined(execaSync));55test('execaNode() undefined options use default value', () => testBindUndefined(execaNode));56test('$ undefined options use default value', () => testBindUndefined($));57test('$.sync undefined options use default value', () => testBindUndefined($.sync));5857const testMergeEnv = async (t, execaMethod) => {59const testMergeEnv = async execaMethod => {60 const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: 'bar'}});59 t.is(stdout, 'foo\nbar');61 assert.equal(stdout, 'foo\nbar');62};6362test('execa() bound options are merged', testMergeEnv, execa);63test('execaSync() bound options are merged', testMergeEnv, execaSync);64test('execaNode() bound options are merged', testMergeEnv, execaNode);65test('$ bound options are merged', testMergeEnv, $);66test('$.sync bound options are merged', testMergeEnv, $.sync);64test('execa() bound options are merged', () => testMergeEnv(execa));65test('execaSync() bound options are merged', () => testMergeEnv(execaSync));66test('execaNode() bound options are merged', () => testMergeEnv(execaNode));67test('$ bound options are merged', () => testMergeEnv($));68test('$.sync bound options are merged', () => testMergeEnv($.sync));6968const testMergeMultiple = async (t, execaMethod) => {70const testMergeMultiple = async execaMethod => {71 const {stdout} = await execaMethod({env: {FOO: 'baz'}})({env: {BAR: 'bar'}})(PRINT_ENV_PATH, {env: {FOO: 'foo'}});70 t.is(stdout, 'foo\nbar');72 assert.equal(stdout, 'foo\nbar');73};7473test('execa() bound options are merged multiple times', testMergeMultiple, execa);74test('execaSync() bound options are merged multiple times', testMergeMultiple, execaSync);75test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);76test('$ bound options are merged multiple times', testMergeMultiple, $);77test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);75test('execa() bound options are merged multiple times', () => testMergeMultiple(execa));76test('execaSync() bound options are merged multiple times', () => testMergeMultiple(execaSync));77test('execaNode() bound options are merged multiple times', () => testMergeMultiple(execaNode));78test('$ bound options are merged multiple times', () => testMergeMultiple($));79test('$.sync bound options are merged multiple times', () => testMergeMultiple($.sync));8079const testMergeFdSpecific = async (t, execaMethod) => {80 const {isMaxBuffer, shortMessage} = await t.throwsAsync(execaMethod({maxBuffer: {stdout: 1}})(NOOP_PATH, [foobarString], {maxBuffer: {stderr: 100}}));81 t.true(isMaxBuffer);82 t.true(shortMessage.includes('Command\'s stdout was larger than 1'));81const testMergeFdSpecific = async execaMethod => {82 const {isMaxBuffer, shortMessage} = await assertRejects(execaMethod({maxBuffer: {stdout: 1}})(NOOP_PATH, [foobarString], {maxBuffer: {stderr: 100}}));83 assert.equal(isMaxBuffer, true);84 assert.ok(shortMessage.includes('Command\'s stdout was larger than 1'));85};8685test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);86test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);87test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);87test('execa() bound options merge fd-specific ones', () => testMergeFdSpecific(execa));88test('execaNode() bound options merge fd-specific ones', () => testMergeFdSpecific(execaNode));89test('$ bound options merge fd-specific ones', () => testMergeFdSpecific($));9089const testMergeEnvUndefined = async (t, execaMethod) => {91const testMergeEnvUndefined = async execaMethod => {92 const {stdout} = await execaMethod({env: {FOO: 'foo'}})(PRINT_ENV_PATH, {env: {BAR: undefined}});91 t.is(stdout, 'foo\nundefined');93 assert.equal(stdout, 'foo\nundefined');94};9594test('execa() bound options are merged even if undefined', testMergeEnvUndefined, execa);95test('execaSync() bound options are merged even if undefined', testMergeEnvUndefined, execaSync);96test('execaNode() bound options are merged even if undefined', testMergeEnvUndefined, execaNode);97test('$ bound options are merged even if undefined', testMergeEnvUndefined, $);98test('$.sync bound options are merged even if undefined', testMergeEnvUndefined, $.sync);96test('execa() bound options are merged even if undefined', () => testMergeEnvUndefined(execa));97test('execaSync() bound options are merged even if undefined', () => testMergeEnvUndefined(execaSync));98test('execaNode() bound options are merged even if undefined', () => testMergeEnvUndefined(execaNode));99test('$ bound options are merged even if undefined', () => testMergeEnvUndefined($));100test('$.sync bound options are merged even if undefined', () => testMergeEnvUndefined($.sync));101100const testMergeSpecific = async (t, execaMethod) => {102const testMergeSpecific = async execaMethod => {103 const {stdout} = await execaMethod({stdout: {transform: uppercaseGenerator().transform, objectMode: true}})(NOOP_PATH, {stdout: {transform: uppercaseGenerator().transform}});102 t.is(stdout, foobarUppercase);104 assert.equal(stdout, foobarUppercase);105};106105test('execa() bound options only merge specific ones', testMergeSpecific, execa);106test('execaSync() bound options only merge specific ones', testMergeSpecific, execaSync);107test('execaNode() bound options only merge specific ones', testMergeSpecific, execaNode);108test('$ bound options only merge specific ones', testMergeSpecific, $);109test('$.sync bound options only merge specific ones', testMergeSpecific, $.sync);107test('execa() bound options only merge specific ones', () => testMergeSpecific(execa));108test('execaSync() bound options only merge specific ones', () => testMergeSpecific(execaSync));109test('execaNode() bound options only merge specific ones', () => testMergeSpecific(execaNode));110test('$ bound options only merge specific ones', () => testMergeSpecific($));111test('$.sync bound options only merge specific ones', () => testMergeSpecific($.sync));
modified:test/methods/command.js+47 added-45 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows} from '../helpers/assert.js';4import {5 execa,6 execaSync,7 $,
9 unmodified lines
17const ECHO_FIXTURE_URL = new URL('echo.js', FIXTURES_DIRECTORY_URL);1819const parseAndRunCommand = command => execa`${parseCommandString(command)}`;2019test('parseCommandString() + execa()', async t => {21test('parseCommandString() + execa()', async () => {22 const {stdout} = await execa('echo.js', parseCommandString('foo bar'));21 t.is(stdout, 'foo\nbar');23 assert.equal(stdout, 'foo\nbar');24});2524test('parseCommandString() + execaSync()', t => {26test('parseCommandString() + execaSync()', () => {27 const {stdout} = execaSync('echo.js', parseCommandString('foo bar'));26 t.is(stdout, 'foo\nbar');28 assert.equal(stdout, 'foo\nbar');29});3029test('parseCommandString() + execa`...`', async t => {31test('parseCommandString() + execa`...`', async () => {32 const {stdout} = await execa`${parseCommandString('echo.js foo bar')}`;31 t.is(stdout, 'foo\nbar');33 assert.equal(stdout, 'foo\nbar');34});3534test('parseCommandString() + execa`...`, only arguments', async t => {36test('parseCommandString() + execa`...`, only arguments', async () => {37 const {stdout} = await execa`echo.js ${parseCommandString('foo bar')}`;36 t.is(stdout, 'foo\nbar');38 assert.equal(stdout, 'foo\nbar');39});4039test('parseCommandString() + execa`...`, only some arguments', async t => {41test('parseCommandString() + execa`...`, only some arguments', async () => {42 const {stdout} = await execa`echo.js ${'foo bar'} ${parseCommandString('foo bar')}`;41 t.is(stdout, 'foo bar\nfoo\nbar');43 assert.equal(stdout, 'foo bar\nfoo\nbar');44});4544test('parseCommandString() + execaSync`...`', t => {46test('parseCommandString() + execaSync`...`', () => {47 const {stdout} = execaSync`${parseCommandString('echo.js foo bar')}`;46 t.is(stdout, 'foo\nbar');48 assert.equal(stdout, 'foo\nbar');49});5049test('parseCommandString() + execaSync`...`, only arguments', t => {51test('parseCommandString() + execaSync`...`, only arguments', () => {52 const {stdout} = execaSync`echo.js ${parseCommandString('foo bar')}`;51 t.is(stdout, 'foo\nbar');53 assert.equal(stdout, 'foo\nbar');54});5554test('parseCommandString() + execaSync`...`, only some arguments', t => {56test('parseCommandString() + execaSync`...`, only some arguments', () => {57 const {stdout} = execaSync`echo.js ${'foo bar'} ${parseCommandString('foo bar')}`;56 t.is(stdout, 'foo bar\nfoo\nbar');58 assert.equal(stdout, 'foo bar\nfoo\nbar');59});6059test('parseCommandString() + $', async t => {61test('parseCommandString() + $', async () => {62 const {stdout} = await $`${parseCommandString('echo.js foo bar')}`;61 t.is(stdout, 'foo\nbar');63 assert.equal(stdout, 'foo\nbar');64});6564test('parseCommandString() + $.sync', t => {66test('parseCommandString() + $.sync', () => {67 const {stdout} = $.sync`${parseCommandString('echo.js foo bar')}`;66 t.is(stdout, 'foo\nbar');68 assert.equal(stdout, 'foo\nbar');69});7069test('parseCommandString() + execaNode', async t => {71test('parseCommandString() + execaNode', async () => {72 const {stdout} = await execaNode(ECHO_FIXTURE_URL, parseCommandString('foo bar'));71 t.is(stdout, 'foo\nbar');73 assert.equal(stdout, 'foo\nbar');74});7574const testInvalidArgumentsParse = (t, command) => {75 t.throws(() => parseCommandString(command), {76const testInvalidArgumentsParse = command => {77 assertThrows(() => parseCommandString(command), {78 message: /The command must be a string/,79 });80};8180test('parseCommandString() must not pass a number', testInvalidArgumentsParse, 0);81test('parseCommandString() must not pass undefined', testInvalidArgumentsParse, undefined);82test('parseCommandString() must not pass null', testInvalidArgumentsParse, null);83test('parseCommandString() must not pass a symbol', testInvalidArgumentsParse, Symbol('test'));84test('parseCommandString() must not pass an object', testInvalidArgumentsParse, {});85test('parseCommandString() must not pass an array', testInvalidArgumentsParse, []);82test('parseCommandString() must not pass a number', () => testInvalidArgumentsParse(0));83test('parseCommandString() must not pass undefined', () => testInvalidArgumentsParse(undefined));84test('parseCommandString() must not pass null', () => testInvalidArgumentsParse(null));85test('parseCommandString() must not pass a symbol', () => testInvalidArgumentsParse(Symbol('test')));86test('parseCommandString() must not pass an object', () => testInvalidArgumentsParse({}));87test('parseCommandString() must not pass an array', () => testInvalidArgumentsParse([]));8887const testParseCommandOutput = async (t, command, expectedOutput, execaMethod) => {89const testParseCommandOutput = async (command, expectedOutput, execaMethod) => {90 const {stdout} = await execaMethod(command);89 t.is(stdout, expectedOutput);91 assert.equal(stdout, expectedOutput);92};9392test('parseCommandString() allows escaping spaces in commands', testParseCommandOutput, 'command\\ with\\ space.js foo bar', 'foo\nbar', parseAndRunCommand);93test('parseCommandString() trims', testParseCommandOutput, ' echo.js foo bar ', 'foo\nbar', parseAndRunCommand);94test('parseCommandString() ignores consecutive spaces', testParseCommandOutput, 'echo.js foo bar', 'foo\nbar', parseAndRunCommand);95test('parseCommandString() escapes other whitespaces', testParseCommandOutput, 'echo.js foo\tbar', 'foo\tbar', parseAndRunCommand);96test('parseCommandString() allows escaping spaces', testParseCommandOutput, 'echo.js foo\\ bar', 'foo bar', parseAndRunCommand);97test('parseCommandString() allows escaping backslashes before spaces', testParseCommandOutput, 'echo.js foo\\\\ bar', 'foo\\ bar', parseAndRunCommand);98test('parseCommandString() allows escaping multiple backslashes before spaces', testParseCommandOutput, 'echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', parseAndRunCommand);99test('parseCommandString() allows escaping backslashes not before spaces', testParseCommandOutput, 'echo.js foo\\bar baz', 'foo\\bar\nbaz', parseAndRunCommand);94test('parseCommandString() allows escaping spaces in commands', () => testParseCommandOutput('command\\ with\\ space.js foo bar', 'foo\nbar', parseAndRunCommand));95test('parseCommandString() trims', () => testParseCommandOutput(' echo.js foo bar ', 'foo\nbar', parseAndRunCommand));96test('parseCommandString() ignores consecutive spaces', () => testParseCommandOutput('echo.js foo bar', 'foo\nbar', parseAndRunCommand));97test('parseCommandString() escapes other whitespaces', () => testParseCommandOutput('echo.js foo\tbar', 'foo\tbar', parseAndRunCommand));98test('parseCommandString() allows escaping spaces', () => testParseCommandOutput('echo.js foo\\ bar', 'foo bar', parseAndRunCommand));99test('parseCommandString() allows escaping backslashes before spaces', () => testParseCommandOutput('echo.js foo\\\\ bar', 'foo\\ bar', parseAndRunCommand));100test('parseCommandString() allows escaping multiple backslashes before spaces', () => testParseCommandOutput('echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', parseAndRunCommand));101test('parseCommandString() allows escaping backslashes not before spaces', () => testParseCommandOutput('echo.js foo\\bar baz', 'foo\\bar\nbaz', parseAndRunCommand));102101test('parseCommandString() can get empty strings', t => {102 t.deepEqual(parseCommandString(''), []);103test('parseCommandString() can get empty strings', () => {104 assert.deepEqual(parseCommandString(''), []);105});106105test('parseCommandString() can get only whitespaces', t => {107test('parseCommandString() can get only whitespaces', () => {108 // eslint-disable-next-line unicorn/prefer-string-repeat107 t.deepEqual(parseCommandString(' '), []);109 assert.deepEqual(parseCommandString(' '), []);110});
modified:test/methods/create.js+30 added-29 removed
1import assert from 'node:assert/strict';2import path from 'node:path';2import test from 'ava';3import test from 'node:test';4import {5 execa,6 execaSync,7 execaNode,
5 unmodified lines
13setFixtureDirectory();1415const NOOP_PATH = path.join(FIXTURES_DIRECTORY, 'noop.js');1616const testTemplate = async (t, execaMethod) => {17const testTemplate = async execaMethod => {18 const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;18 t.is(stdout, foobarString);19 assert.equal(stdout, foobarString);20};2121test('execa() can use template strings', testTemplate, execa);22test('execaNode() can use template strings', testTemplate, execaNode);23test('$ can use template strings', testTemplate, $);22test('execa() can use template strings', () => testTemplate(execa));23test('execaNode() can use template strings', () => testTemplate(execaNode));24test('$ can use template strings', () => testTemplate($));2525const testTemplateSync = (t, execaMethod) => {26const testTemplateSync = execaMethod => {27 const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;27 t.is(stdout, foobarString);28 assert.equal(stdout, foobarString);29};3030test('execaSync() can use template strings', testTemplateSync, execaSync);31test('$.sync can use template strings', testTemplateSync, $.sync);31test('execaSync() can use template strings', () => testTemplateSync(execaSync));32test('$.sync can use template strings', () => testTemplateSync($.sync));3333const testTemplateOptions = async (t, execaMethod) => {34const testTemplateOptions = async execaMethod => {35 const {stdout} = await execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;35 t.is(stdout, `${foobarString}\n`);36 assert.equal(stdout, `${foobarString}\n`);37};3838test('execa() can use template strings with options', testTemplateOptions, execa);39test('execaNode() can use template strings with options', testTemplateOptions, execaNode);40test('$ can use template strings with options', testTemplateOptions, $);39test('execa() can use template strings with options', () => testTemplateOptions(execa));40test('execaNode() can use template strings with options', () => testTemplateOptions(execaNode));41test('$ can use template strings with options', () => testTemplateOptions($));4242const testTemplateOptionsSync = (t, execaMethod) => {43const testTemplateOptionsSync = execaMethod => {44 const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;44 t.is(stdout, `${foobarString}\n`);45 assert.equal(stdout, `${foobarString}\n`);46};4747test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);48test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);48test('execaSync() can use template strings with options', () => testTemplateOptionsSync(execaSync));49test('$.sync can use template strings with options', () => testTemplateOptionsSync($.sync));5050const testSpacedCommand = async (t, commandArguments, execaMethod) => {51const testSpacedCommand = async (commandArguments, execaMethod) => {52 const {stdout} = await execaMethod('command with space.js', commandArguments);53 const expectedStdout = commandArguments === undefined ? '' : commandArguments.join('\n');53 t.is(stdout, expectedStdout);54 assert.equal(stdout, expectedStdout);55};5656test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);57test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);58test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);59test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);60test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);61test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);62test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);63test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);57test('allow commands with spaces and no array arguments', () => testSpacedCommand(undefined, execa));58test('allow commands with spaces and array arguments', () => testSpacedCommand(foobarArray, execa));59test('allow commands with spaces and no array arguments, execaSync', () => testSpacedCommand(undefined, execaSync));60test('allow commands with spaces and array arguments, execaSync', () => testSpacedCommand(foobarArray, execaSync));61test('allow commands with spaces and no array arguments, $', () => testSpacedCommand(undefined, $));62test('allow commands with spaces and array arguments, $', () => testSpacedCommand(foobarArray, $));63test('allow commands with spaces and no array arguments, $.sync', () => testSpacedCommand(undefined, $.sync));64test('allow commands with spaces and array arguments, $.sync', () => testSpacedCommand(foobarArray, $.sync));
modified:test/methods/main-async.js+42 added-41 removed
1import assert from 'node:assert/strict';2import process from 'node:process';3import {ChildProcess} from 'node:child_process';3import test from 'ava';4import test from 'node:test';5import {execa} from '../../index.js';6import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';78setFixtureDirectory();910const isWindows = process.platform === 'win32';1112if (isWindows) {12 test('execa() - cmd file', async t => {13 test('execa() - cmd file', async () => {14 const {stdout} = await execa('hello.cmd');14 t.is(stdout, 'Hello World');15 assert.equal(stdout, 'Hello World');16 });1717 test('execa() - run cmd command', async t => {18 test('execa() - run cmd command', async () => {19 const {stdout} = await execa('cmd', ['/c', 'hello.cmd']);19 t.is(stdout, 'Hello World');20 assert.equal(stdout, 'Hello World');21 });2223 // A bare command name without an extension is resolved using `PATHEXT`.23 test('execa() - resolve command extension using PATHEXT', async t => {24 test('execa() - resolve command extension using PATHEXT', async () => {25 const {stdout} = await execa('hello');25 t.is(stdout, 'Hello World');26 assert.equal(stdout, 'Hello World');27 });2828 test('execa() - run cmd file using a relative path', async t => {29 test('execa() - run cmd file using a relative path', async () => {30 const {stdout} = await execa('./hello.cmd', {cwd: FIXTURES_DIRECTORY});30 t.is(stdout, 'Hello World');31 assert.equal(stdout, 'Hello World');32 });3334 // The fixture's filename contains a space and it starts with a shebang.34 test('execa() - run file with a space in its path and a shebang', async t => {35 test('execa() - run file with a space in its path and a shebang', async () => {36 const {stdout} = await execa('command with space.js', ['foo']);36 t.is(stdout, 'foo');37 assert.equal(stdout, 'foo');38 });39}4040test('execa() returns a promise with pid', async t => {41test('execa() returns a promise with pid', async () => {42 const subprocess = execa('noop.js', ['foo']);42 t.is(typeof subprocess.pid, 'number');43 assert.equal(typeof subprocess.pid, 'number');44 await subprocess;45});4646test('execa() returns a promise with nodeChildProcess', async t => {47test('execa() returns a promise with nodeChildProcess', async () => {48 const subprocess = execa('noop.js', ['foo']);48 t.true(subprocess instanceof Promise);49 t.false(subprocess instanceof ChildProcess);50 t.true(subprocess.nodeChildProcess instanceof ChildProcess);51 t.is(subprocess.pid, subprocess.nodeChildProcess.pid);52 t.is(subprocess.stdout, subprocess.nodeChildProcess.stdout);53 t.is(subprocess.on, undefined);54 t.is(subprocess.once, undefined);55 t.is(subprocess.send, undefined);56 t.is(subprocess.ref, undefined);57 t.is(subprocess.unref, undefined);58 t.is(subprocess.disconnect, undefined);59 t.is(subprocess.channel, undefined);60 t.is(subprocess.connected, undefined);61 t.is(subprocess.exitCode, undefined);62 t.is(subprocess.signalCode, undefined);63 t.is(subprocess.killed, undefined);64 t.is(subprocess.spawnargs, undefined);65 t.is(subprocess.spawnfile, undefined);66 // eslint-disable-next-line unicorn/no-nonstandard-builtin-properties -- `Symbol.dispose` is a standard well-known symbol, not yet recognized by this rule.67 t.is(subprocess[Symbol.dispose], undefined);49 assert.ok(subprocess instanceof Promise);50 assert.ok(!(subprocess instanceof ChildProcess));51 assert.ok(subprocess.nodeChildProcess instanceof ChildProcess);52 assert.equal(subprocess.pid, subprocess.nodeChildProcess.pid);53 assert.equal(subprocess.stdout, subprocess.nodeChildProcess.stdout);54 assert.equal(subprocess.on, undefined);55 assert.equal(subprocess.once, undefined);56 assert.equal(subprocess.send, undefined);57 assert.equal(subprocess.ref, undefined);58 assert.equal(subprocess.unref, undefined);59 assert.equal(subprocess.disconnect, undefined);60 assert.equal(subprocess.channel, undefined);61 assert.equal(subprocess.connected, undefined);62 assert.equal(subprocess.exitCode, undefined);63 assert.equal(subprocess.signalCode, undefined);64 assert.equal(subprocess.killed, undefined);65 assert.equal(subprocess.spawnargs, undefined);66 assert.equal(subprocess.spawnfile, undefined);6768 assert.equal(subprocess[Symbol.dispose], undefined);69 await subprocess;70});7171test('nodeChildProcess does not include Execa-specific APIs', async t => {72test('nodeChildProcess does not include Execa-specific APIs', async () => {73 const subprocess = execa('noop.js', ['foo'], {all: true});73 t.false(Object.hasOwn(subprocess.nodeChildProcess, 'all'));74 t.is(subprocess.nodeChildProcess.readable, undefined);75 t.is(subprocess.nodeChildProcess.writable, undefined);76 t.is(subprocess.nodeChildProcess.duplex, undefined);77 t.is(subprocess.nodeChildProcess.iterable, undefined);78 t.is(subprocess.nodeChildProcess[Symbol.asyncIterator], undefined);74 assert.ok(!Object.hasOwn(subprocess.nodeChildProcess, 'all'));75 assert.equal(subprocess.nodeChildProcess.readable, undefined);76 assert.equal(subprocess.nodeChildProcess.writable, undefined);77 assert.equal(subprocess.nodeChildProcess.duplex, undefined);78 assert.equal(subprocess.nodeChildProcess.iterable, undefined);79 assert.equal(subprocess.nodeChildProcess[Symbol.asyncIterator], undefined);80 await subprocess;81});
modified:test/methods/node.js+152 added-146 removed
1import assert from 'node:assert/strict';2import path from 'node:path';3import process, {version} from 'node:process';4import {pathToFileURL} from 'node:url';4import test from 'ava';5import test from 'node:test';6import getNode from 'get-node';7import {assertThrows, assertRejects} from '../helpers/assert.js';8import {execa, execaSync, execaNode} from '../../index.js';9import {FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';10import {identity, fullStdio} from '../helpers/stdio.js';11import {foobarString} from '../helpers/input.js';
8 unmodified lines
20 ? execaSync(file, commandArguments, {...options, node: true})21 : execaSync(file, {...options, node: true});22const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});2322const testNodeSuccess = async (t, execaMethod) => {24const testNodeSuccess = async execaMethod => {25 const {exitCode, stdout} = await execaMethod('noop.js', [foobarString]);24 t.is(exitCode, 0);25 t.is(stdout, foobarString);26 assert.equal(exitCode, 0);27 assert.equal(stdout, foobarString);28};2928test('execaNode() succeeds', testNodeSuccess, execaNode);29test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);30test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);30test('execaNode() succeeds', () => testNodeSuccess(execaNode));31test('The "node" option succeeds', () => testNodeSuccess(runWithNodeOption));32test('The "node" option succeeds - sync', () => testNodeSuccess(runWithNodeOptionSync));3332test('execaNode(options) succeeds', async t => {34test('execaNode(options) succeeds', async () => {35 const {stdout} = await execaNode({stripFinalNewline: false})('noop.js', [foobarString]);34 t.is(stdout, `${foobarString}\n`);36 assert.equal(stdout, `${foobarString}\n`);37});3837test('execaNode`...` succeeds', async t => {39test('execaNode`...` succeeds', async () => {40 const {stdout} = await execaNode`noop.js ${foobarString}`;39 t.is(stdout, foobarString);41 assert.equal(stdout, foobarString);42});4342test('execaNode().pipe(execaNode()) succeeds', async t => {44test('execaNode().pipe(execaNode()) succeeds', async () => {45 const {stdout} = await execaNode('noop.js').pipe(execaNode('--version'));44 t.is(stdout, version);46 assert.equal(stdout, version);47});4847test('execaNode().pipe(execa()) requires using "node"', async t => {48 await t.throwsAsync(execaNode('noop.js').pipe(execa('--version')));49test('execaNode().pipe(execa()) requires using "node"', async () => {50 await assertRejects(execaNode('noop.js').pipe(execa('--version')));51});5251test('execaNode().pipe(...) requires using "node"', async t => {52 await t.throwsAsync(execaNode('noop.js').pipe('--version'));53test('execaNode().pipe(...) requires using "node"', async () => {54 await assertRejects(execaNode('noop.js').pipe('--version'));55});5655test('execaNode().pipe`...` requires using "node"', async t => {56 await t.throwsAsync(execaNode('noop.js').pipe`--version`);57test('execaNode().pipe`...` requires using "node"', async () => {58 await assertRejects(execaNode('noop.js').pipe`--version`);59});6059test('execaNode() cannot set the "node" option to false', t => {60 t.throws(() => {61test('execaNode() cannot set the "node" option to false', () => {62 assertThrows(() => {63 execaNode('empty.js', {node: false});64 }, {message: /The "node" option cannot be false/});65});6665const testDoubleNode = (t, nodePath, execaMethod) => {66 t.throws(() => {67const testDoubleNode = (nodePath, execaMethod) => {68 assertThrows(() => {69 execaMethod(nodePath, ['noop.js']);70 }, {message: /does not need to be "node"/});71};7271test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);72test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);73test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);74test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);75test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);76test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);77test('Cannot use deno style nodePath as binary - execaNode()', testDoubleNode, getDenoNodePath(), execaNode);78test('Cannot use deno style nodePath as binary - "node" option', testDoubleNode, getDenoNodePath(), runWithNodeOption);79test('Cannot use deno style nodePath as binary - "node" option sync', testDoubleNode, getDenoNodePath(), runWithNodeOptionSync);73test('Cannot use "node" as binary - execaNode()', () => testDoubleNode('node', execaNode));74test('Cannot use "node" as binary - "node" option', () => testDoubleNode('node', runWithNodeOption));75test('Cannot use "node" as binary - "node" option sync', () => testDoubleNode('node', runWithNodeOptionSync));76test('Cannot use path to "node" as binary - execaNode()', () => testDoubleNode(process.execPath, execaNode));77test('Cannot use path to "node" as binary - "node" option', () => testDoubleNode(process.execPath, runWithNodeOption));78test('Cannot use path to "node" as binary - "node" option sync', () => testDoubleNode(process.execPath, runWithNodeOptionSync));79test('Cannot use deno style nodePath as binary - execaNode()', () => testDoubleNode(getDenoNodePath(), execaNode));80test('Cannot use deno style nodePath as binary - "node" option', () => testDoubleNode(getDenoNodePath(), runWithNodeOption));81test('Cannot use deno style nodePath as binary - "node" option sync', () => testDoubleNode(getDenoNodePath(), runWithNodeOptionSync));8283const getNodePath = async () => {84 const {path} = await getNode(TEST_NODE_VERSION);85 return path;86};8788const TEST_NODE_VERSION = '16.0.0';8990// `nodeOptions` defaults to `process.execArgv`, which `node --test` fills with its own flags.91// Those flags are unknown to the Node.js version downloaded by `getNode()`, so they are not forwarded.92const downloadedNodeOptions = {nodeOptions: []};9388const testNodePath = async (t, execaMethod, mapPath) => {94const testNodePath = async (execaMethod, mapPath) => {95 const nodePath = mapPath(await getNodePath());90 const {stdout} = await execaMethod('--version', [], {nodePath});91 t.is(stdout, `v${TEST_NODE_VERSION}`);96 const {stdout} = await execaMethod('--version', [], {nodePath, ...downloadedNodeOptions});97 assert.equal(stdout, `v${TEST_NODE_VERSION}`);98};9994test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);95test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);96test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);97test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);98test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);99test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);100test('The "nodePath" option can be used - execaNode()', () => testNodePath(execaNode, identity));101test('The "nodePath" option can be a file URL - execaNode()', () => testNodePath(execaNode, pathToFileURL));102test('The "nodePath" option can be used - "node" option', () => testNodePath(runWithNodeOption, identity));103test('The "nodePath" option can be a file URL - "node" option', () => testNodePath(runWithNodeOption, pathToFileURL));104test('The "nodePath" option can be used - "node" option sync', () => testNodePath(runWithNodeOptionSync, identity));105test('The "nodePath" option can be a file URL - "node" option sync', () => testNodePath(runWithNodeOptionSync, pathToFileURL));106101const testNodePathDefault = async (t, execaMethod) => {107const testNodePathDefault = async execaMethod => {108 const {stdout} = await execaMethod('--version');103 t.is(stdout, process.version);109 assert.equal(stdout, process.version);110};111106test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);107test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);108test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);112test('The "nodePath" option defaults to the current Node.js binary - execaNode()', () => testNodePathDefault(execaNode));113test('The "nodePath" option defaults to the current Node.js binary - "node" option', () => testNodePathDefault(runWithNodeOption));114test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', () => testNodePathDefault(runWithNodeOptionSync));115110const testNodePathInvalid = (t, execaMethod) => {111 t.throws(() => {116const testNodePathInvalid = execaMethod => {117 assertThrows(() => {118 execaMethod('noop.js', [], {nodePath: true});119 }, {message: /The "nodePath" option must be a string or a file URL/});120};121116test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);117test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);118test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);122test('The "nodePath" option must be a string or URL - execaNode()', () => testNodePathInvalid(execaNode));123test('The "nodePath" option must be a string or URL - "node" option', () => testNodePathInvalid(runWithNodeOption));124test('The "nodePath" option must be a string or URL - "node" option sync', () => testNodePathInvalid(runWithNodeOptionSync));125120const testFormerNodePath = (t, execaMethod) => {121 t.throws(() => {126const testFormerNodePath = execaMethod => {127 assertThrows(() => {128 execaMethod('noop.js', [], {execPath: process.execPath});129 }, {message: /The "execPath" option has been removed/});130};131126test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);127test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);128test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);132test('The "execPath" option cannot be used - execaNode()', () => testFormerNodePath(execaNode));133test('The "execPath" option cannot be used - "node" option', () => testFormerNodePath(runWithNodeOption));134test('The "execPath" option cannot be used - "node" option sync', () => testFormerNodePath(runWithNodeOptionSync));135136const nodePathArguments = ['-p', ['process.env.Path || process.env.PATH']];137132const testSubprocessNodePath = async (t, execaMethod, mapPath) => {138const testSubprocessNodePath = async (execaMethod, mapPath) => {139 const nodePath = mapPath(await getNodePath());134 const {stdout} = await execaMethod(...nodePathArguments, {nodePath});135 t.true(stdout.includes(TEST_NODE_VERSION));140 const {stdout} = await execaMethod(...nodePathArguments, {nodePath, ...downloadedNodeOptions});141 assert.ok(stdout.includes(TEST_NODE_VERSION));142};143138test.serial('The "nodePath" option impacts the subprocess - execaNode()', testSubprocessNodePath, execaNode, identity);139test.serial('The "nodePath" option impacts the subprocess - "node" option', testSubprocessNodePath, runWithNodeOption, identity);140test.serial('The "nodePath" option impacts the subprocess - "node" option sync', testSubprocessNodePath, runWithNodeOptionSync, identity);144test('The "nodePath" option impacts the subprocess - execaNode()', () => testSubprocessNodePath(execaNode, identity));145test('The "nodePath" option impacts the subprocess - "node" option', () => testSubprocessNodePath(runWithNodeOption, identity));146test('The "nodePath" option impacts the subprocess - "node" option sync', () => testSubprocessNodePath(runWithNodeOptionSync, identity));147142const testSubprocessNodePathDefault = async (t, execaMethod) => {148const testSubprocessNodePathDefault = async execaMethod => {149 const {stdout} = await execaMethod(...nodePathArguments);144 t.true(stdout.includes(path.dirname(process.execPath)));150 assert.ok(stdout.includes(path.dirname(process.execPath)));151};152147test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', testSubprocessNodePathDefault, execaNode);148test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', testSubprocessNodePathDefault, runWithNodeOption);149test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', testSubprocessNodePathDefault, runWithNodeOptionSync);153test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', () => testSubprocessNodePathDefault(execaNode));154test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', () => testSubprocessNodePathDefault(runWithNodeOption));155test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', () => testSubprocessNodePathDefault(runWithNodeOptionSync));156151test.serial('The "nodePath" option requires "node: true" to impact the subprocess', async t => {157test('The "nodePath" option requires "node: true" to impact the subprocess', async () => {158 const nodePath = await getNodePath();159 const {stdout} = await execa('node', nodePathArguments.flat(), {nodePath});154 t.false(stdout.includes(TEST_NODE_VERSION));160 assert.ok(!stdout.includes(TEST_NODE_VERSION));161});162157const testSubprocessNodePathCwd = async (t, execaMethod) => {163const testSubprocessNodePathCwd = async execaMethod => {164 const nodePath = await getNodePath();165 const cwd = path.dirname(path.dirname(nodePath));166 const relativeExecPath = path.relative(cwd, nodePath);161 const {stdout} = await execaMethod(...nodePathArguments, {nodePath: relativeExecPath, cwd});162 t.true(stdout.includes(TEST_NODE_VERSION));167 const {stdout} = await execaMethod(...nodePathArguments, {nodePath: relativeExecPath, cwd, ...downloadedNodeOptions});168 assert.ok(stdout.includes(TEST_NODE_VERSION));169};170165test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', testSubprocessNodePathCwd, execaNode);166test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', testSubprocessNodePathCwd, runWithNodeOption);167test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', testSubprocessNodePathCwd, runWithNodeOptionSync);171test('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', () => testSubprocessNodePathCwd(execaNode));172test('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', () => testSubprocessNodePathCwd(runWithNodeOption));173test('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', () => testSubprocessNodePathCwd(runWithNodeOptionSync));174169const testCwdNodePath = async (t, execaMethod) => {175const testCwdNodePath = async execaMethod => {176 const nodePath = await getNodePath();177 const cwd = path.dirname(path.dirname(nodePath));178 const relativeExecPath = path.relative(cwd, nodePath);173 const {stdout} = await execaMethod('--version', [], {nodePath: relativeExecPath, cwd});174 t.is(stdout, `v${TEST_NODE_VERSION}`);179 const {stdout} = await execaMethod('--version', [], {nodePath: relativeExecPath, cwd, ...downloadedNodeOptions});180 assert.equal(stdout, `v${TEST_NODE_VERSION}`);181};182177test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);178test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);179test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);183test('The "nodePath" option is relative to "cwd" - execaNode()', () => testCwdNodePath(execaNode));184test('The "nodePath" option is relative to "cwd" - "node" option', () => testCwdNodePath(runWithNodeOption));185test('The "nodePath" option is relative to "cwd" - "node" option sync', () => testCwdNodePath(runWithNodeOptionSync));186181const testDenoExecPath = async (t, execaMethod) => {187const testDenoExecPath = async execaMethod => {188 const {exitCode, stdout} = await execaMethod('noop.js', [], {nodePath: getDenoNodePath()});183 t.is(exitCode, 0);184 t.is(stdout, foobarString);189 assert.equal(exitCode, 0);190 assert.equal(stdout, foobarString);191};192187test('The deno style "nodePath" option can be used - execaNode()', testDenoExecPath, execaNode);188test('The deno style "nodePath" option can be used - "node" option', testDenoExecPath, runWithNodeOption);189test('The deno style "nodePath" option can be used - "node" option sync', testDenoExecPath, runWithNodeOptionSync);193test('The deno style "nodePath" option can be used - execaNode()', () => testDenoExecPath(execaNode));194test('The deno style "nodePath" option can be used - "node" option', () => testDenoExecPath(runWithNodeOption));195test('The deno style "nodePath" option can be used - "node" option sync', () => testDenoExecPath(runWithNodeOptionSync));196191const testNodeOptions = async (t, execaMethod) => {197const testNodeOptions = async execaMethod => {198 const {stdout} = await execaMethod('empty.js', [], {nodeOptions: ['--version']});193 t.is(stdout, process.version);199 assert.equal(stdout, process.version);200};201196test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);197test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);198test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);202test('The "nodeOptions" option can be used - execaNode()', () => testNodeOptions(execaNode));203test('The "nodeOptions" option can be used - "node" option', () => testNodeOptions(runWithNodeOption));204test('The "nodeOptions" option can be used - "node" option sync', () => testNodeOptions(runWithNodeOptionSync));205206const spawnNestedExecaNode = (realExecArgv, fakeExecArgv, execaMethod, nodeOptions) => execa(207 'node',208 [...realExecArgv, 'nested-node.js', fakeExecArgv, execaMethod, nodeOptions, 'noop.js', foobarString],209 {...fullStdio, cwd: FIXTURES_DIRECTORY},210);211206const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {212const testInspectRemoval = async (fakeExecArgv, execaMethod) => {213 const {stdout, stdio} = await spawnNestedExecaNode([], fakeExecArgv, execaMethod, '');208 t.is(stdout, foobarString);209 t.is(stdio[3], '');214 assert.equal(stdout, foobarString);215 assert.equal(stdio[3], '');216};217212test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');213test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');214test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');215test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');216test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');217test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');218test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');219test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');218test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect', 'execaNode'));219test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', () => testInspectRemoval('--inspect', 'nodeOption'));220test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect=9222', 'execaNode'));221test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', () => testInspectRemoval('--inspect=9222', 'nodeOption'));222test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect-brk', 'execaNode'));223test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', () => testInspectRemoval('--inspect-brk', 'nodeOption'));224test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect-brk=9223', 'execaNode'));225test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', () => testInspectRemoval('--inspect-brk=9223', 'nodeOption'));226221const testInspectDifferentPort = async (t, execaMethod) => {227const testInspectDifferentPort = async execaMethod => {228 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9225'], '', execaMethod, '--inspect=9224');223 t.is(stdout, foobarString);224 t.true(stdio[3].includes('Debugger listening'));229 assert.equal(stdout, foobarString);230 assert.ok(stdio[3].includes('Debugger listening'));231};232227test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', testInspectDifferentPort, 'execaNode');228test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', testInspectDifferentPort, 'nodeOption');233test('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', () => testInspectDifferentPort('execaNode'));234test('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', () => testInspectDifferentPort('nodeOption'));235230const testInspectSamePort = async (t, execaMethod) => {236const testInspectSamePort = async execaMethod => {237 const {stdout, stdio} = await spawnNestedExecaNode(['--inspect=9226'], '', execaMethod, '--inspect=9226');232 t.is(stdout, foobarString);233 t.true(stdio[3].includes('address already in use'));238 assert.equal(stdout, foobarString);239 assert.ok(stdio[3].includes('address already in use'));240};241236test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', testInspectSamePort, 'execaNode');237test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', testInspectSamePort, 'nodeOption');242test('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', () => testInspectSamePort('execaNode'));243test('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', () => testInspectSamePort('nodeOption'));244239const testIpc = async (t, execaMethod, options) => {245const testIpc = async (execaMethod, options) => {246 const subprocess = execaMethod('ipc-echo.js', [], options);247248 await subprocess.sendMessage(foobarString);243 t.is(await subprocess.getOneMessage(), foobarString);249 assert.equal(await subprocess.getOneMessage(), foobarString);250251 const {stdio} = await subprocess;246 t.is(stdio.length, 4);247 t.is(stdio[3], undefined);252 assert.equal(stdio.length, 4);253 assert.equal(stdio[3], undefined);254};255250test('execaNode() adds an ipc channel', testIpc, execaNode, {});251test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});252test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});253test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});254test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});255test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});256test('execaNode() adds an ipc channel', () => testIpc(execaNode, {}));257test('The "node" option adds an ipc channel', () => testIpc(runWithNodeOption, {}));258test('The "ipc" option adds an ipc channel', () => testIpc(runWithIpc, {}));259test('The "ipc" option works with "stdio: \'pipe\'"', () => testIpc(runWithIpc, {stdio: 'pipe'}));260test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', () => testIpc(runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']}));261test('The "ipc" option works with "stdout: \'pipe\'"', () => testIpc(runWithIpc, {stdout: 'pipe'}));262263const NO_SEND_MESSAGE = 'sendMessage() can only be used';264259test('No ipc channel is added by default', async t => {260 const {message, stdio} = await t.throwsAsync(execa('node', ['ipc-send.js']));261 t.true(message.includes(NO_SEND_MESSAGE));262 t.is(stdio.length, 3);265test('No ipc channel is added by default', async () => {266 const {message, stdio} = await assertRejects(execa('node', ['ipc-send.js']));267 assert.ok(message.includes(NO_SEND_MESSAGE));268 assert.equal(stdio.length, 3);269});270265const testDisableIpc = async (t, execaMethod) => {271const testDisableIpc = async execaMethod => {272 const {failed, message, stdio} = await execaMethod('ipc-send.js', [], {ipc: false, reject: false});267 t.true(failed);268 t.true(message.includes(NO_SEND_MESSAGE));269 t.is(stdio.length, 3);273 assert.equal(failed, true);274 assert.ok(message.includes(NO_SEND_MESSAGE));275 assert.equal(stdio.length, 3);276};277272test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);273test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);274test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);278test('Can disable "ipc" - execaNode()', () => testDisableIpc(execaNode));279test('Can disable "ipc" - "node" option', () => testDisableIpc(runWithNodeOption));280test('Can disable "ipc" - "node" option sync', () => testDisableIpc(runWithNodeOptionSync));281282const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;283278const testNoIpcSync = (t, node) => {279 t.throws(() => {284const testNoIpcSync = node => {285 assertThrows(() => {286 execaSync('node', ['ipc-send.js'], {ipc: true, node});287 }, {message: NO_IPC_MESSAGE});288};289284test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);285test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);290test('Cannot use "ipc: true" with execaSync()', () => testNoIpcSync(undefined));291test('Cannot use "ipc: true" with execaSync() - "node: false"', () => testNoIpcSync(false));292287test('Cannot use "ipc: true" with execaSync() - "node: true"', t => {288 t.throws(() => {293test('Cannot use "ipc: true" with execaSync() - "node: true"', () => {294 assertThrows(() => {295 execaSync('ipc-send.js', {ipc: true, node: true});296 }, {message: NO_IPC_MESSAGE});297});298293const testNoShell = async (t, execaMethod) => {299const testNoShell = async execaMethod => {300 const {failed, message} = await execaMethod('node --version', [], {shell: true, reject: false});295 t.true(failed);296 t.true(message.includes('MODULE_NOT_FOUND'));301 assert.equal(failed, true);302 assert.ok(message.includes('MODULE_NOT_FOUND'));303};304299test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);300test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);301test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);305test('Cannot use "shell: true" - execaNode()', () => testNoShell(execaNode));306test('Cannot use "shell: true" - "node" option', () => testNoShell(runWithNodeOption));307test('Cannot use "shell: true" - "node" option sync', () => testNoShell(runWithNodeOptionSync));
modified:test/methods/override-promise.js+4 added-3 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3// The helper module overrides Promise on import so has to be imported before `execa`.4import {restorePromise} from '../helpers/override-promise.js';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';78restorePromise();9setFixtureDirectory();1010test('should work with third-party Promise', async t => {11test('should work with third-party Promise', async () => {12 const {stdout} = await execa('noop.js', ['foo']);12 t.is(stdout, 'foo');13 assert.equal(stdout, 'foo');14});
modified:test/methods/parameters-args.js+23 added-22 removed
1import test from 'ava';1import test from 'node:test';2import {assertThrows} from '../helpers/assert.js';3import {4 execa,5 execaSync,6 execaNode,
2 unmodified lines
9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';1011setFixtureDirectory();1212const testInvalidArguments = async (t, execaMethod) => {13 t.throws(() => {13const testInvalidArguments = async execaMethod => {14 assertThrows(() => {15 execaMethod('echo', true);16 }, {message: /Second argument must be either/});17};1818test('execa()\'s second argument must be valid', testInvalidArguments, execa);19test('execaSync()\'s second argument must be valid', testInvalidArguments, execaSync);20test('execaNode()\'s second argument must be valid', testInvalidArguments, execaNode);21test('$\'s second argument must be valid', testInvalidArguments, $);22test('$.sync\'s second argument must be valid', testInvalidArguments, $.sync);19test('execa()\'s second argument must be valid', () => testInvalidArguments(execa));20test('execaSync()\'s second argument must be valid', () => testInvalidArguments(execaSync));21test('execaNode()\'s second argument must be valid', () => testInvalidArguments(execaNode));22test('$\'s second argument must be valid', () => testInvalidArguments($));23test('$.sync\'s second argument must be valid', () => testInvalidArguments($.sync));2424const testInvalidArgumentsItems = async (t, execaMethod) => {25 t.throws(() => {25const testInvalidArgumentsItems = async execaMethod => {26 assertThrows(() => {27 execaMethod('echo', [{}]);28 }, {message: 'Second argument must be an array of strings: [object Object]'});29};3030test('execa()\'s second argument must not be objects', testInvalidArgumentsItems, execa);31test('execaSync()\'s second argument must not be objects', testInvalidArgumentsItems, execaSync);32test('execaNode()\'s second argument must not be objects', testInvalidArgumentsItems, execaNode);33test('$\'s second argument must not be objects', testInvalidArgumentsItems, $);34test('$.sync\'s second argument must not be objects', testInvalidArgumentsItems, $.sync);31test('execa()\'s second argument must not be objects', () => testInvalidArgumentsItems(execa));32test('execaSync()\'s second argument must not be objects', () => testInvalidArgumentsItems(execaSync));33test('execaNode()\'s second argument must not be objects', () => testInvalidArgumentsItems(execaNode));34test('$\'s second argument must not be objects', () => testInvalidArgumentsItems($));35test('$.sync\'s second argument must not be objects', () => testInvalidArgumentsItems($.sync));3636const testNullByteArgument = async (t, execaMethod) => {37 t.throws(() => {37const testNullByteArgument = async execaMethod => {38 assertThrows(() => {39 execaMethod('echo', ['a\0b']);40 }, {message: /null bytes/});41};4242test('execa()\'s second argument must not include \\0', testNullByteArgument, execa);43test('execaSync()\'s second argument must not include \\0', testNullByteArgument, execaSync);44test('execaNode()\'s second argument must not include \\0', testNullByteArgument, execaNode);45test('$\'s second argument must not include \\0', testNullByteArgument, $);46test('$.sync\'s second argument must not include \\0', testNullByteArgument, $.sync);43test('execa()\'s second argument must not include \\0', () => testNullByteArgument(execa));44test('execaSync()\'s second argument must not include \\0', () => testNullByteArgument(execaSync));45test('execaNode()\'s second argument must not include \\0', () => testNullByteArgument(execaNode));46test('$\'s second argument must not include \\0', () => testNullByteArgument($));47test('$.sync\'s second argument must not include \\0', () => testNullByteArgument($.sync));
modified:test/methods/parameters-command.js+41 added-39 removed
1import assert from 'node:assert/strict';2import path from 'node:path';3import {fileURLToPath} from 'node:url';3import test from 'ava';4import test from 'node:test';5import {assertThrows} from '../helpers/assert.js';6import {7 execa,8 execaSync,9 execaNode,
3 unmodified lines
13import {foobarString} from '../helpers/input.js';1415setFixtureDirectory();1615const testFileUrl = async (t, execaMethod) => {17const testFileUrl = async execaMethod => {18 const command = new URL('noop.js', FIXTURES_DIRECTORY_URL);19 const {stdout} = await execaMethod(command);18 t.is(stdout, foobarString);20 assert.equal(stdout, foobarString);21};2221test('execa()\'s command argument can be a file URL', testFileUrl, execa);22test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);23test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);24test('$\'s command argument can be a file URL', testFileUrl, $);25test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);23test('execa()\'s command argument can be a file URL', () => testFileUrl(execa));24test('execaSync()\'s command argument can be a file URL', () => testFileUrl(execaSync));25test('execaNode()\'s command argument can be a file URL', () => testFileUrl(execaNode));26test('$\'s command argument can be a file URL', () => testFileUrl($));27test('$.sync\'s command argument can be a file URL', () => testFileUrl($.sync));2827const testInvalidFileUrl = async (t, execaMethod) => {29const testInvalidFileUrl = async execaMethod => {30 const invalidUrl = new URL('https://invalid.com');29 t.throws(() => {31 assertThrows(() => {32 execaMethod(invalidUrl);33 }, {code: 'ERR_INVALID_URL_SCHEME'});34};3534test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);35test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);36test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);37test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);38test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);36test('execa()\'s command argument cannot be a non-file URL', () => testInvalidFileUrl(execa));37test('execaSync()\'s command argument cannot be a non-file URL', () => testInvalidFileUrl(execaSync));38test('execaNode()\'s command argument cannot be a non-file URL', () => testInvalidFileUrl(execaNode));39test('$\'s command argument cannot be a non-file URL', () => testInvalidFileUrl($));40test('$.sync\'s command argument cannot be a non-file URL', () => testInvalidFileUrl($.sync));4140const testInvalidCommand = async (t, commandArgument, execaMethod) => {41 t.throws(() => {42const testInvalidCommand = async (commandArgument, execaMethod) => {43 assertThrows(() => {44 execaMethod(commandArgument);45 }, {message: /First argument must be a string or a file URL/});46};4746test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);47test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);48test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);49test('$\'s first argument must be defined', testInvalidCommand, undefined, $);50test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);51test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);52test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);53test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);54test('$\'s first argument must be valid', testInvalidCommand, true, $);55test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);56test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);57test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);58test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);59test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);60test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);48test('execa()\'s first argument must be defined', () => testInvalidCommand(undefined, execa));49test('execaSync()\'s first argument must be defined', () => testInvalidCommand(undefined, execaSync));50test('execaNode()\'s first argument must be defined', () => testInvalidCommand(undefined, execaNode));51test('$\'s first argument must be defined', () => testInvalidCommand(undefined, $));52test('$.sync\'s first argument must be defined', () => testInvalidCommand(undefined, $.sync));53test('execa()\'s first argument must be valid', () => testInvalidCommand(true, execa));54test('execaSync()\'s first argument must be valid', () => testInvalidCommand(true, execaSync));55test('execaNode()\'s first argument must be valid', () => testInvalidCommand(true, execaNode));56test('$\'s first argument must be valid', () => testInvalidCommand(true, $));57test('$.sync\'s first argument must be valid', () => testInvalidCommand(true, $.sync));58test('execa()\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], execa));59test('execaSync()\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], execaSync));60test('execaNode()\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], execaNode));61test('$\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], $));62test('$.sync\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], $.sync));6362const testRelativePath = async (t, execaMethod) => {64const testRelativePath = async execaMethod => {65 // @todo: use import.meta.dirname after dropping support for Node <20.11.066 const rootDirectory = path.basename(fileURLToPath(new URL('../..', import.meta.url)));67 const pathViaParentDirectory = path.join('..', rootDirectory, 'test', 'fixtures', 'noop.js');68 const {stdout} = await execaMethod(pathViaParentDirectory);67 t.is(stdout, foobarString);69 assert.equal(stdout, foobarString);70};7170test('execa() use relative path with \'..\' chars', testRelativePath, execa);71test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);72test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);73test('$ use relative path with \'..\' chars', testRelativePath, $);74test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);72test('execa() use relative path with \'..\' chars', () => testRelativePath(execa));73test('execaSync() use relative path with \'..\' chars', () => testRelativePath(execaSync));74test('execaNode() use relative path with \'..\' chars', () => testRelativePath(execaNode));75test('$ use relative path with \'..\' chars', () => testRelativePath($));76test('$.sync use relative path with \'..\' chars', () => testRelativePath($.sync));
modified:test/methods/parameters-options.js+52 added-50 removed
1import assert from 'node:assert/strict';2import path from 'node:path';2import test from 'ava';3import test from 'node:test';4import {assertThrows} from '../helpers/assert.js';5import {6 execa,7 execaSync,8 execaNode,
4 unmodified lines
13setFixtureDirectory();1415const NOOP_PATH = path.join(FIXTURES_DIRECTORY, 'noop.js');1615const testSerializeArgument = async (t, commandArgument, execaMethod) => {17const testSerializeArgument = async (commandArgument, execaMethod) => {18 const {stdout} = await execaMethod(NOOP_PATH, [commandArgument]);17 t.is(stdout, String(commandArgument));19 assert.equal(stdout, String(commandArgument));20};2120test('execa()\'s arguments can be numbers', testSerializeArgument, 1, execa);21test('execa()\'s arguments can be booleans', testSerializeArgument, true, execa);22test('execa()\'s arguments can be NaN', testSerializeArgument, NaN, execa);23test('execa()\'s arguments can be Infinity', testSerializeArgument, Infinity, execa);24test('execa()\'s arguments can be null', testSerializeArgument, null, execa);25test('execa()\'s arguments can be undefined', testSerializeArgument, undefined, execa);26test('execa()\'s arguments can be bigints', testSerializeArgument, 1n, execa);27test('execa()\'s arguments can be symbols', testSerializeArgument, Symbol('test'), execa);28test('execaSync()\'s arguments can be numbers', testSerializeArgument, 1, execaSync);29test('execaSync()\'s arguments can be booleans', testSerializeArgument, true, execaSync);30test('execaSync()\'s arguments can be NaN', testSerializeArgument, NaN, execaSync);31test('execaSync()\'s arguments can be Infinity', testSerializeArgument, Infinity, execaSync);32test('execaSync()\'s arguments can be null', testSerializeArgument, null, execaSync);33test('execaSync()\'s arguments can be undefined', testSerializeArgument, undefined, execaSync);34test('execaSync()\'s arguments can be bigints', testSerializeArgument, 1n, execaSync);35test('execaSync()\'s arguments can be symbols', testSerializeArgument, Symbol('test'), execaSync);36test('execaNode()\'s arguments can be numbers', testSerializeArgument, 1, execaNode);37test('execaNode()\'s arguments can be booleans', testSerializeArgument, true, execaNode);38test('execaNode()\'s arguments can be NaN', testSerializeArgument, NaN, execaNode);39test('execaNode()\'s arguments can be Infinity', testSerializeArgument, Infinity, execaNode);40test('execaNode()\'s arguments can be null', testSerializeArgument, null, execaNode);41test('execaNode()\'s arguments can be undefined', testSerializeArgument, undefined, execaNode);42test('execaNode()\'s arguments can be bigints', testSerializeArgument, 1n, execaNode);43test('execaNode()\'s arguments can be symbols', testSerializeArgument, Symbol('test'), execaNode);44test('$\'s arguments can be numbers', testSerializeArgument, 1, $);45test('$\'s arguments can be booleans', testSerializeArgument, true, $);46test('$\'s arguments can be NaN', testSerializeArgument, NaN, $);47test('$\'s arguments can be Infinity', testSerializeArgument, Infinity, $);48test('$\'s arguments can be null', testSerializeArgument, null, $);49test('$\'s arguments can be undefined', testSerializeArgument, undefined, $);50test('$\'s arguments can be bigints', testSerializeArgument, 1n, $);51test('$\'s arguments can be symbols', testSerializeArgument, Symbol('test'), $);52test('$.sync\'s arguments can be numbers', testSerializeArgument, 1, $.sync);53test('$.sync\'s arguments can be booleans', testSerializeArgument, true, $.sync);54test('$.sync\'s arguments can be NaN', testSerializeArgument, NaN, $.sync);55test('$.sync\'s arguments can be Infinity', testSerializeArgument, Infinity, $.sync);56test('$.sync\'s arguments can be null', testSerializeArgument, null, $.sync);57test('$.sync\'s arguments can be undefined', testSerializeArgument, undefined, $.sync);58test('$.sync\'s arguments can be bigints', testSerializeArgument, 1n, $.sync);59test('$.sync\'s arguments can be symbols', testSerializeArgument, Symbol('test'), $.sync);22test('execa()\'s arguments can be numbers', () => testSerializeArgument(1, execa));23test('execa()\'s arguments can be booleans', () => testSerializeArgument(true, execa));24test('execa()\'s arguments can be NaN', () => testSerializeArgument(NaN, execa));25test('execa()\'s arguments can be Infinity', () => testSerializeArgument(Infinity, execa));26test('execa()\'s arguments can be null', () => testSerializeArgument(null, execa));27test('execa()\'s arguments can be undefined', () => testSerializeArgument(undefined, execa));28test('execa()\'s arguments can be bigints', () => testSerializeArgument(1n, execa));29test('execa()\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), execa));30test('execaSync()\'s arguments can be numbers', () => testSerializeArgument(1, execaSync));31test('execaSync()\'s arguments can be booleans', () => testSerializeArgument(true, execaSync));32test('execaSync()\'s arguments can be NaN', () => testSerializeArgument(NaN, execaSync));33test('execaSync()\'s arguments can be Infinity', () => testSerializeArgument(Infinity, execaSync));34test('execaSync()\'s arguments can be null', () => testSerializeArgument(null, execaSync));35test('execaSync()\'s arguments can be undefined', () => testSerializeArgument(undefined, execaSync));36test('execaSync()\'s arguments can be bigints', () => testSerializeArgument(1n, execaSync));37test('execaSync()\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), execaSync));38test('execaNode()\'s arguments can be numbers', () => testSerializeArgument(1, execaNode));39test('execaNode()\'s arguments can be booleans', () => testSerializeArgument(true, execaNode));40test('execaNode()\'s arguments can be NaN', () => testSerializeArgument(NaN, execaNode));41test('execaNode()\'s arguments can be Infinity', () => testSerializeArgument(Infinity, execaNode));42test('execaNode()\'s arguments can be null', () => testSerializeArgument(null, execaNode));43test('execaNode()\'s arguments can be undefined', () => testSerializeArgument(undefined, execaNode));44test('execaNode()\'s arguments can be bigints', () => testSerializeArgument(1n, execaNode));45test('execaNode()\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), execaNode));46test('$\'s arguments can be numbers', () => testSerializeArgument(1, $));47test('$\'s arguments can be booleans', () => testSerializeArgument(true, $));48test('$\'s arguments can be NaN', () => testSerializeArgument(NaN, $));49test('$\'s arguments can be Infinity', () => testSerializeArgument(Infinity, $));50test('$\'s arguments can be null', () => testSerializeArgument(null, $));51test('$\'s arguments can be undefined', () => testSerializeArgument(undefined, $));52test('$\'s arguments can be bigints', () => testSerializeArgument(1n, $));53test('$\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), $));54test('$.sync\'s arguments can be numbers', () => testSerializeArgument(1, $.sync));55test('$.sync\'s arguments can be booleans', () => testSerializeArgument(true, $.sync));56test('$.sync\'s arguments can be NaN', () => testSerializeArgument(NaN, $.sync));57test('$.sync\'s arguments can be Infinity', () => testSerializeArgument(Infinity, $.sync));58test('$.sync\'s arguments can be null', () => testSerializeArgument(null, $.sync));59test('$.sync\'s arguments can be undefined', () => testSerializeArgument(undefined, $.sync));60test('$.sync\'s arguments can be bigints', () => testSerializeArgument(1n, $.sync));61test('$.sync\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), $.sync));6261const testInvalidOptions = async (t, execaMethod) => {62 t.throws(() => {63const testInvalidOptions = async execaMethod => {64 assertThrows(() => {65 execaMethod('echo', [], new Map());66 }, {message: /Last argument must be an options object/});67};6867test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);68test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);69test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);70test('$\'s third argument must be a plain object', testInvalidOptions, $);71test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);69test('execa()\'s third argument must be a plain object', () => testInvalidOptions(execa));70test('execaSync()\'s third argument must be a plain object', () => testInvalidOptions(execaSync));71test('execaNode()\'s third argument must be a plain object', () => testInvalidOptions(execaNode));72test('$\'s third argument must be a plain object', () => testInvalidOptions($));73test('$.sync\'s third argument must be a plain object', () => testInvalidOptions($.sync));
modified:test/methods/promise.js+23 added-21 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';67setFixtureDirectory();87test('subprocess properties are enumerable', t => {9test('subprocess properties are enumerable', () => {10 const descriptors = Object.getOwnPropertyDescriptors(execa('noop.js'));9 t.true(descriptors.nodeChildProcess.enumerable);11 assert.equal(descriptors.nodeChildProcess.enumerable, true);12});1312test('finally function is executed on success', async t => {14test('finally function is executed on success', async () => {15 let isCalled = false;16 const {stdout} = await execa('noop.js', ['foo']).finally(() => {17 isCalled = true;18 });17 t.true(isCalled);18 t.is(stdout, 'foo');19 assert.equal(isCalled, true);20 assert.equal(stdout, 'foo');21});2221test('finally function is executed on failure', async t => {23test('finally function is executed on failure', async () => {24 let isError = false;23 const {stdout, stderr} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {25 const {stdout, stderr} = await assertRejects(execa('exit.js', ['2']).finally(() => {26 isError = true;27 }));26 t.true(isError);27 t.is(typeof stdout, 'string');28 t.is(typeof stderr, 'string');28 assert.equal(isError, true);29 assert.equal(typeof stdout, 'string');30 assert.equal(typeof stderr, 'string');31});3231test('throw in finally function bubbles up on success', async t => {32 const {message} = await t.throwsAsync(execa('noop.js', ['foo']).finally(() => {33test('throw in finally function bubbles up on success', async () => {34 const {message} = await assertRejects(execa('noop.js', ['foo']).finally(() => {35 throw new Error('called');36 }));35 t.is(message, 'called');37 assert.equal(message, 'called');38});3938test('throw in finally bubbles up on error', async t => {39 const {message} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {40test('throw in finally bubbles up on error', async () => {41 const {message} = await assertRejects(execa('exit.js', ['2']).finally(() => {42 throw new Error('called');43 }));42 t.is(message, 'called');44 assert.equal(message, 'called');45});4645const testNoAwait = async (t, fixtureName, options, message) => {47const testNoAwait = async (fixtureName, options, message) => {48 const {stdout} = await execa('no-await.js', [JSON.stringify(options), fixtureName]);47 t.true(stdout.includes(message));49 assert.ok(stdout.includes(message));50};5150test('Throws if promise is not awaited and subprocess fails', testNoAwait, 'fail.js', {}, 'exit code 2');51test('Throws if promise is not awaited and subprocess times out', testNoAwait, 'forever.js', {timeout: 1}, 'timed out');52test('Throws if promise is not awaited and subprocess fails', () => testNoAwait('fail.js', {}, 'exit code 2'));53test('Throws if promise is not awaited and subprocess times out', () => testNoAwait('forever.js', {timeout: 1}, 'timed out'));
modified:test/methods/script.js+26 added-25 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {isStream} from 'is-stream';4import {$} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString} from '../helpers/input.js';78setFixtureDirectory();99const testScriptStdoutSync = (t, getSubprocess, expectedStdout) => {10const testScriptStdoutSync = (getSubprocess, expectedStdout) => {11 const {stdout} = getSubprocess();11 t.is(stdout, expectedStdout);12 assert.equal(stdout, expectedStdout);13};1414test('$.sync`...`', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');15test('$.s`...`', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');16test('$(options).sync`...`', testScriptStdoutSync, () => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`);17test('$.sync(options)`...`', testScriptStdoutSync, () => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`);15test('$.sync`...`', () => testScriptStdoutSync(() => $.sync`echo.js foo bar`, 'foo\nbar'));16test('$.s`...`', () => testScriptStdoutSync(() => $.s`echo.js foo bar`, 'foo\nbar'));17test('$(options).sync`...`', () => testScriptStdoutSync(() => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`));18test('$.sync(options)`...`', () => testScriptStdoutSync(() => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`));1919test('Cannot call $.sync.sync', t => {20 t.false('sync' in $.sync);20test('Cannot call $.sync.sync', () => {21 assert.equal('sync' in $.sync, false);22});2323test('Cannot call $.sync(options).sync', t => {24 t.false('sync' in $.sync({}));24test('Cannot call $.sync(options).sync', () => {25 assert.equal('sync' in $.sync({}), false);26});2727test('$(options)() stdin defaults to "inherit"', async t => {28test('$(options)() stdin defaults to "inherit"', async () => {29 const {stdout} = await $({input: foobarString})('stdin-script.js');29 t.is(stdout, foobarString);30 assert.equal(stdout, foobarString);31});3232test('$.sync(options)() stdin defaults to "inherit"', t => {33test('$.sync(options)() stdin defaults to "inherit"', () => {34 const {stdout} = $.sync({input: foobarString})('stdin-script.js');34 t.is(stdout, foobarString);35 assert.equal(stdout, foobarString);36});3737test('$(options).sync() stdin defaults to "inherit"', t => {38test('$(options).sync() stdin defaults to "inherit"', () => {39 const {stdout} = $({input: foobarString}).sync('stdin-script.js');39 t.is(stdout, foobarString);40 assert.equal(stdout, foobarString);41});4242test('$(options)`...` stdin defaults to "inherit"', async t => {43test('$(options)`...` stdin defaults to "inherit"', async () => {44 const {stdout} = await $({input: foobarString})`stdin-script.js`;44 t.is(stdout, foobarString);45 assert.equal(stdout, foobarString);46});4747test('$.sync(options)`...` stdin defaults to "inherit"', t => {48test('$.sync(options)`...` stdin defaults to "inherit"', () => {49 const {stdout} = $.sync({input: foobarString})`stdin-script.js`;49 t.is(stdout, foobarString);50 assert.equal(stdout, foobarString);51});5252test('$(options).sync`...` stdin defaults to "inherit"', t => {53test('$(options).sync`...` stdin defaults to "inherit"', () => {54 const {stdout} = $({input: foobarString}).sync`stdin-script.js`;54 t.is(stdout, foobarString);55 assert.equal(stdout, foobarString);56});5757test('$ stdin has no default value when stdio is set', t => {58 t.true(isStream($({stdio: 'pipe'})`noop.js`.stdin));58test('$ stdin has no default value when stdio is set', () => {59 assert.ok(isStream($({stdio: 'pipe'})`noop.js`.stdin));60});
modified:test/methods/template.js+315 added-313 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows} from '../helpers/assert.js';4import {$} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';67setFixtureDirectory();
4 unmodified lines
12 templates.raw = [string];13 return $(templates);14};1514const testScriptStdout = async (t, getSubprocess, expectedStdout) => {16const testScriptStdout = async (getSubprocess, expectedStdout) => {17 const {stdout} = await getSubprocess();16 t.is(stdout, expectedStdout);18 assert.equal(stdout, expectedStdout);19};2019test('$ allows number interpolation', testScriptStdout, () => $`echo.js 1 ${2}`, '1\n2');20test('$ can concatenate multiple tokens', testScriptStdout, () => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo');21test('$ can use newlines and tab indentations', testScriptStdout, () => $`echo.js foo22 bar`, 'foo\nbar');23test('$ can use newlines and space indentations', testScriptStdout, () => $`echo.js foo24 bar`, 'foo\nbar');25test('$ can use escaped newlines and space indentations', testScriptStdout, () => $`echo.js foo\26 bar`, 'foo\nbar');27test('$ can use escaped newlines and inline tab indentations', testScriptStdout, () => $`echo.js foo\28 bar`, 'foo\nbar');29test('$ can use escaped newlines and character escaped tab indentations', testScriptStdout, () => $`echo.js foo\30\tbar`, 'foo\tbar');31test('$ can use escaped newlines and character escaped newlines', testScriptStdout, () => $`echo.js foo\32\n\nbar`, 'foo\n\nbar');21test('$ allows number interpolation', () => testScriptStdout(() => $`echo.js 1 ${2}`, '1\n2'));22test('$ can concatenate multiple tokens', () => testScriptStdout(() => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo'));23test('$ can use newlines and tab indentations', () => testScriptStdout(() => $`echo.js foo24 bar`, 'foo\nbar'));25test('$ can use newlines and space indentations', () => testScriptStdout(() => $`echo.js foo26 bar`, 'foo\nbar'));27test('$ can use escaped newlines and space indentations', () => testScriptStdout(() => $`echo.js foo\28 bar`, 'foo\nbar'));29test('$ can use escaped newlines and inline tab indentations', () => testScriptStdout(() => $`echo.js foo\30 bar`, 'foo\nbar'));31test('$ can use escaped newlines and character escaped tab indentations', () => testScriptStdout(() => $`echo.js foo\32\tbar`, 'foo\tbar'));33test('$ can use escaped newlines and character escaped newlines', () => testScriptStdout(() => $`echo.js foo\34\n\nbar`, 'foo\n\nbar'));35// An escaped newline is ignored, so it must not separate tokens, nor hide the whitespaces following it.36// This must behave the same whether the tokens around it are expressions or not.35test('$ can use escaped newlines between tokens', testScriptStdout, () => $`echo.js foo\36bar`, 'foobar');37test('$ can use escaped newlines between expressions', testScriptStdout, () => $`echo.js ${'foo'}\38${'bar'}`, 'foobar');39test('$ can use multiple escaped newlines between expressions', testScriptStdout, () => $`echo.js ${'foo'}\37test('$ can use escaped newlines between tokens', () => testScriptStdout(() => $`echo.js foo\38bar`, 'foobar'));39test('$ can use escaped newlines between expressions', () => testScriptStdout(() => $`echo.js ${'foo'}\40${'bar'}`, 'foobar'));41test('$ can use multiple escaped newlines between expressions', () => testScriptStdout(() => $`echo.js ${'foo'}\42\41${'bar'}`, 'foobar');42test('$ can use escaped newlines and space indentations between expressions', testScriptStdout, () => $`echo.js ${'foo'}\43 ${'bar'}`, 'foo\nbar');44test('$ can use escaped newlines and tab indentations between expressions', testScriptStdout, () => $`echo.js ${'foo'}\45 ${'bar'}`, 'foo\nbar');46test('$ can use escaped newlines and space indentations after an expression', testScriptStdout, () => $`echo.js ${'foo'}\47 bar`, 'foo\nbar');48test('$ can use escaped newlines and tab indentations after an expression', testScriptStdout, () => $`echo.js ${'foo'}\49 bar`, 'foo\nbar');50test('$ can use escaped newlines before an expression', testScriptStdout, () => $`echo.js foo\51${'bar'}`, 'foobar');52test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');53test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');54test('$ does not ignore comments in expressions', testScriptStdout, () => $`echo.js foo43${'bar'}`, 'foobar'));44test('$ can use escaped newlines and space indentations between expressions', () => testScriptStdout(() => $`echo.js ${'foo'}\45 ${'bar'}`, 'foo\nbar'));46test('$ can use escaped newlines and tab indentations between expressions', () => testScriptStdout(() => $`echo.js ${'foo'}\47 ${'bar'}`, 'foo\nbar'));48test('$ can use escaped newlines and space indentations after an expression', () => testScriptStdout(() => $`echo.js ${'foo'}\49 bar`, 'foo\nbar'));50test('$ can use escaped newlines and tab indentations after an expression', () => testScriptStdout(() => $`echo.js ${'foo'}\51 bar`, 'foo\nbar'));52test('$ can use escaped newlines before an expression', () => testScriptStdout(() => $`echo.js foo\53${'bar'}`, 'foobar'));54test('$ can use Windows newlines and tab indentations', () => testScriptStdout(() => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar'));55test('$ can use Windows newlines and space indentations', () => testScriptStdout(() => escapedCall('echo.js foo\r\n bar'), 'foo\nbar'));56test('$ does not ignore comments in expressions', () => testScriptStdout(() => $`echo.js foo57 ${/* This is a comment */''}58 bar59 ${/* This is another comment */''}60 baz59`, 'foo\n\nbar\n\nbaz');60test('$ allows escaping spaces with interpolation', testScriptStdout, () => $`echo.js ${'foo bar'}`, 'foo bar');61test('$ allows escaping spaces in commands with interpolation', testScriptStdout, () => $`${'command with space.js'} foo bar`, 'foo\nbar');62test('$ trims', testScriptStdout, () => $` echo.js foo bar `, 'foo\nbar');63test('$ allows array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar']}`, 'foo\nbar');64test('$ allows empty array interpolation', testScriptStdout, () => $`echo.js foo ${[]} bar`, 'foo\nbar');65test('$ allows space escaped values in array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz');66test('$ can concatenate at the end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo');67test('$ can concatenate at the start of tokens followed by an array', testScriptStdout, () => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo');68test('$ can concatenate at the start and end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar');69test('$ handles escaped newlines', testScriptStdout, () => $`echo.js a\70b`, 'ab');71test('$ handles backslashes at end of lines', testScriptStdout, () => $`echo.js a\\72 b`, 'a\\\nb');73test('$ handles double backslashes at end of lines', testScriptStdout, () => $`echo.js a\\\\74 b`, 'a\\\\\nb');75test('$ handles tokens - a', testScriptStdout, () => $`echo.js a`, 'a');76test('$ handles expressions - a', testScriptStdout, () => $`echo.js ${'a'}`, 'a');77test('$ handles tokens - abc', testScriptStdout, () => $`echo.js abc`, 'abc');78test('$ handles expressions - abc', testScriptStdout, () => $`echo.js ${'abc'}`, 'abc');79test('$ handles tokens - ""', testScriptStdout, () => $`echo.js`, '');80test('$ handles expressions - ""', testScriptStdout, () => $`echo.js a ${''} b`, 'a\n\nb');81test('$ splits tokens - ""', testScriptStdout, () => $`echo.js ab`, 'ab');82test('$ splits expressions - ""', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'ab');83test('$ concatenates expressions - ""', testScriptStdout, () => $`echo.js a${'b'}c`, 'abc');84test('$ handles tokens - " "', testScriptStdout, () => $`echo.js `, '');85test('$ handles expressions - " "', testScriptStdout, () => $`echo.js ${' '}`, ' ');86test('$ splits tokens - " "', testScriptStdout, () => $`echo.js a b`, 'a\nb');87test('$ splits expressions - " "', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');88test('$ concatenates tokens - " "', testScriptStdout, () => $`echo.js a `, 'a');89test('$ concatenates expressions - " "', testScriptStdout, () => $`echo.js ${'a'} `, 'a');90test('$ handles tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js `, '');91test('$ handles expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');92test('$ splits tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');93test('$ splits expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');94test('$ concatenates tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a `, 'a');95test('$ concatenates expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');96test('$ handles tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js `, '');61`, 'foo\n\nbar\n\nbaz'));62test('$ allows escaping spaces with interpolation', () => testScriptStdout(() => $`echo.js ${'foo bar'}`, 'foo bar'));63test('$ allows escaping spaces in commands with interpolation', () => testScriptStdout(() => $`${'command with space.js'} foo bar`, 'foo\nbar'));64test('$ trims', () => testScriptStdout(() => $` echo.js foo bar `, 'foo\nbar'));65test('$ allows array interpolation', () => testScriptStdout(() => $`echo.js ${['foo', 'bar']}`, 'foo\nbar'));66test('$ allows empty array interpolation', () => testScriptStdout(() => $`echo.js foo ${[]} bar`, 'foo\nbar'));67test('$ allows space escaped values in array interpolation', () => testScriptStdout(() => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz'));68test('$ can concatenate at the end of tokens followed by an array', () => testScriptStdout(() => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo'));69test('$ can concatenate at the start of tokens followed by an array', () => testScriptStdout(() => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo'));70test('$ can concatenate at the start and end of tokens followed by an array', () => testScriptStdout(() => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar'));71test('$ handles escaped newlines', () => testScriptStdout(() => $`echo.js a\72b`, 'ab'));73test('$ handles backslashes at end of lines', () => testScriptStdout(() => $`echo.js a\\74 b`, 'a\\\nb'));75test('$ handles double backslashes at end of lines', () => testScriptStdout(() => $`echo.js a\\\\76 b`, 'a\\\\\nb'));77test('$ handles tokens - a', () => testScriptStdout(() => $`echo.js a`, 'a'));78test('$ handles expressions - a', () => testScriptStdout(() => $`echo.js ${'a'}`, 'a'));79test('$ handles tokens - abc', () => testScriptStdout(() => $`echo.js abc`, 'abc'));80test('$ handles expressions - abc', () => testScriptStdout(() => $`echo.js ${'abc'}`, 'abc'));81test('$ handles tokens - ""', () => testScriptStdout(() => $`echo.js`, ''));82test('$ handles expressions - ""', () => testScriptStdout(() => $`echo.js a ${''} b`, 'a\n\nb'));83test('$ splits tokens - ""', () => testScriptStdout(() => $`echo.js ab`, 'ab'));84test('$ splits expressions - ""', () => testScriptStdout(() => $`echo.js ${'a'}${'b'}`, 'ab'));85test('$ concatenates expressions - ""', () => testScriptStdout(() => $`echo.js a${'b'}c`, 'abc'));86test('$ handles tokens - " "', () => testScriptStdout(() => $`echo.js `, ''));87test('$ handles expressions - " "', () => testScriptStdout(() => $`echo.js ${' '}`, ' '));88test('$ splits tokens - " "', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));89test('$ splits expressions - " "', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\nb'));90test('$ concatenates tokens - " "', () => testScriptStdout(() => $`echo.js a `, 'a'));91test('$ concatenates expressions - " "', () => testScriptStdout(() => $`echo.js ${'a'} `, 'a'));92test('$ handles tokens - " " (2 spaces)', () => testScriptStdout(() => $`echo.js `, ''));93test('$ handles expressions - " " (2 spaces)', () => testScriptStdout(() => $`echo.js ${' '}`, ' '));94test('$ splits tokens - " " (2 spaces)', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));95test('$ splits expressions - " " (2 spaces)', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\nb'));96test('$ concatenates tokens - " " (2 spaces)', () => testScriptStdout(() => $`echo.js a `, 'a'));97test('$ concatenates expressions - " " (2 spaces)', () => testScriptStdout(() => $`echo.js ${'a'} `, 'a'));98test('$ handles tokens - " " (3 spaces)', () => testScriptStdout(() => $`echo.js `, ''));99// eslint-disable-next-line unicorn/prefer-string-repeat98test('$ handles expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');99test('$ splits tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');100test('$ splits expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');101test('$ concatenates tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a `, 'a');102test('$ concatenates expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');103test('$ handles tokens - \\t (no escape)', testScriptStdout, () => $`echo.js `, '');104test('$ handles expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\t');105test('$ splits tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');106test('$ splits expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');107test('$ concatenates tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');108test('$ concatenates expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, 'a\nb');109test('$ handles tokens - \\t (escape)', testScriptStdout, () => $`echo.js \t`, '\t');110test('$ handles expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'\t'}`, '\t');111test('$ splits tokens - \\t (escape)', testScriptStdout, () => $`echo.js a\tb`, 'a\tb');112test('$ splits expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'a'}\t${'b'}`, 'a\tb');113test('$ concatenates tokens - \\t (escape)', testScriptStdout, () => $`echo.js \ta\t b`, '\ta\t\nb');114test('$ concatenates expressions - \\t (escape)', testScriptStdout, () => $`echo.js \t${'a'}\t b`, '\ta\t\nb');115test('$ handles tokens - \\n (no escape)', testScriptStdout, () => $`echo.js116 `, '');117test('$ handles expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${`118`} `, '\n');119test('$ splits tokens - \\n (no escape)', testScriptStdout, () => $`echo.js a120 b`, 'a\nb');121test('$ splits expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${'a'}122 ${'b'}`, 'a\nb');123test('$ concatenates tokens - \\n (no escape)', testScriptStdout, () => $`echo.js100test('$ handles expressions - " " (3 spaces)', () => testScriptStdout(() => $`echo.js ${' '}`, ' '));101test('$ splits tokens - " " (3 spaces)', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));102test('$ splits expressions - " " (3 spaces)', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\nb'));103test('$ concatenates tokens - " " (3 spaces)', () => testScriptStdout(() => $`echo.js a `, 'a'));104test('$ concatenates expressions - " " (3 spaces)', () => testScriptStdout(() => $`echo.js ${'a'} `, 'a'));105test('$ handles tokens - \\t (no escape)', () => testScriptStdout(() => $`echo.js `, ''));106test('$ handles expressions - \\t (no escape)', () => testScriptStdout(() => $`echo.js ${' '}`, '\t'));107test('$ splits tokens - \\t (no escape)', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));108test('$ splits expressions - \\t (no escape)', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\nb'));109test('$ concatenates tokens - \\t (no escape)', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));110test('$ concatenates expressions - \\t (no escape)', () => testScriptStdout(() => $`echo.js ${'a'} b`, 'a\nb'));111test('$ handles tokens - \\t (escape)', () => testScriptStdout(() => $`echo.js \t`, '\t'));112test('$ handles expressions - \\t (escape)', () => testScriptStdout(() => $`echo.js ${'\t'}`, '\t'));113test('$ splits tokens - \\t (escape)', () => testScriptStdout(() => $`echo.js a\tb`, 'a\tb'));114test('$ splits expressions - \\t (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\t${'b'}`, 'a\tb'));115test('$ concatenates tokens - \\t (escape)', () => testScriptStdout(() => $`echo.js \ta\t b`, '\ta\t\nb'));116test('$ concatenates expressions - \\t (escape)', () => testScriptStdout(() => $`echo.js \t${'a'}\t b`, '\ta\t\nb'));117test('$ handles tokens - \\n (no escape)', () => testScriptStdout(() => $`echo.js118 `, ''));119test('$ handles expressions - \\n (no escape)', () => testScriptStdout(() => $`echo.js ${`120`} `, '\n'));121test('$ splits tokens - \\n (no escape)', () => testScriptStdout(() => $`echo.js a122 b`, 'a\nb'));123test('$ splits expressions - \\n (no escape)', () => testScriptStdout(() => $`echo.js ${'a'}124 ${'b'}`, 'a\nb'));125test('$ concatenates tokens - \\n (no escape)', () => testScriptStdout(() => $`echo.js126a125 b`, 'a\nb');126test('$ concatenates expressions - \\n (no escape)', testScriptStdout, () => $`echo.js127 b`, 'a\nb'));128test('$ concatenates expressions - \\n (no escape)', () => testScriptStdout(() => $`echo.js129${'a'}128 b`, 'a\nb');129test('$ handles tokens - \\n (escape)', testScriptStdout, () => $`echo.js \n `, '\n');130test('$ handles expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'\n'} `, '\n');131test('$ splits tokens - \\n (escape)', testScriptStdout, () => $`echo.js a\n b`, 'a\n\nb');132test('$ splits expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb');133test('$ concatenates tokens - \\n (escape)', testScriptStdout, () => $`echo.js \na\n b`, '\na\n\nb');134test('$ concatenates expressions - \\n (escape)', testScriptStdout, () => $`echo.js \n${'a'}\n b`, '\na\n\nb');135test('$ handles tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \r '), '');136test('$ splits tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');137test('$ splits expressions - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');138test('$ concatenates tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');139test('$ concatenates expressions - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');140test('$ splits tokens - \\r (escape)', testScriptStdout, () => $`echo.js a\r b`, 'a\r\nb');141test('$ splits expressions - \\r (escape)', testScriptStdout, () => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb');142test('$ concatenates tokens - \\r (escape)', testScriptStdout, () => $`echo.js \ra\r b`, '\ra\r\nb');143test('$ concatenates expressions - \\r (escape)', testScriptStdout, () => $`echo.js \r${'a'}\r b`, '\ra\r\nb');144test('$ handles tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\n '), '');145test('$ splits tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');146test('$ splits expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');147test('$ concatenates tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');148test('$ concatenates expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');149test('$ handles tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n `, '\r\n');150test('$ handles expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'\r\n'} `, '\r\n');151test('$ splits tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js a\r\n b`, 'a\r\n\nb');152test('$ splits expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb');153test('$ concatenates tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb');154test('$ concatenates expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n${'a'}\r\n b`, '\r\na\r\n\nb');130 b`, 'a\nb'));131test('$ handles tokens - \\n (escape)', () => testScriptStdout(() => $`echo.js \n `, '\n'));132test('$ handles expressions - \\n (escape)', () => testScriptStdout(() => $`echo.js ${'\n'} `, '\n'));133test('$ splits tokens - \\n (escape)', () => testScriptStdout(() => $`echo.js a\n b`, 'a\n\nb'));134test('$ splits expressions - \\n (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb'));135test('$ concatenates tokens - \\n (escape)', () => testScriptStdout(() => $`echo.js \na\n b`, '\na\n\nb'));136test('$ concatenates expressions - \\n (escape)', () => testScriptStdout(() => $`echo.js \n${'a'}\n b`, '\na\n\nb'));137test('$ handles tokens - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js \r '), ''));138test('$ splits tokens - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js a\rb'), 'a\nb'));139test('$ splits expressions - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js a\rb'), 'a\nb'));140test('$ concatenates tokens - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js \ra\r b'), 'a\nb'));141test('$ concatenates expressions - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js \ra\r b'), 'a\nb'));142test('$ splits tokens - \\r (escape)', () => testScriptStdout(() => $`echo.js a\r b`, 'a\r\nb'));143test('$ splits expressions - \\r (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb'));144test('$ concatenates tokens - \\r (escape)', () => testScriptStdout(() => $`echo.js \ra\r b`, '\ra\r\nb'));145test('$ concatenates expressions - \\r (escape)', () => testScriptStdout(() => $`echo.js \r${'a'}\r b`, '\ra\r\nb'));146test('$ handles tokens - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js \r\n '), ''));147test('$ splits tokens - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js a\r\nb'), 'a\nb'));148test('$ splits expressions - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js a\r\nb'), 'a\nb'));149test('$ concatenates tokens - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js \r\na\r\n b'), 'a\nb'));150test('$ concatenates expressions - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js \r\na\r\n b'), 'a\nb'));151test('$ handles tokens - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js \r\n `, '\r\n'));152test('$ handles expressions - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js ${'\r\n'} `, '\r\n'));153test('$ splits tokens - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js a\r\n b`, 'a\r\n\nb'));154test('$ splits expressions - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb'));155test('$ concatenates tokens - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb'));156test('$ concatenates expressions - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js \r\n${'a'}\r\n b`, '\r\na\r\n\nb'));157/* eslint-disable no-irregular-whitespace -- intentionally testing a literal form feed character */156test('$ handles expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\f');157test('$ splits tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\fb');158test('$ splits expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\fb');159test('$ concatenates tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, '\fa\f\nb');160test('$ concatenates expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, '\fa\f\nb');158test('$ handles expressions - \\f (no escape)', () => testScriptStdout(() => $`echo.js ${' '}`, '\f'));159test('$ splits tokens - \\f (no escape)', () => testScriptStdout(() => $`echo.js a b`, 'a\fb'));160test('$ splits expressions - \\f (no escape)', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\fb'));161test('$ concatenates tokens - \\f (no escape)', () => testScriptStdout(() => $`echo.js a b`, '\fa\f\nb'));162test('$ concatenates expressions - \\f (no escape)', () => testScriptStdout(() => $`echo.js ${'a'} b`, '\fa\f\nb'));163/* eslint-enable no-irregular-whitespace */162test('$ handles tokens - \\f (escape)', testScriptStdout, () => $`echo.js \f`, '\f');163test('$ handles expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'\f'}`, '\f');164test('$ splits tokens - \\f (escape)', testScriptStdout, () => $`echo.js a\fb`, 'a\fb');165test('$ splits expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'a'}\f${'b'}`, 'a\fb');166test('$ concatenates tokens - \\f (escape)', testScriptStdout, () => $`echo.js \fa\f b`, '\fa\f\nb');167test('$ concatenates expressions - \\f (escape)', testScriptStdout, () => $`echo.js \f${'a'}\f b`, '\fa\f\nb');168test('$ handles tokens - \\', testScriptStdout, () => $`echo.js \\`, '\\');169test('$ handles expressions - \\', testScriptStdout, () => $`echo.js ${'\\'}`, '\\');170test('$ splits tokens - \\', testScriptStdout, () => $`echo.js a\\b`, 'a\\b');171test('$ splits expressions - \\', testScriptStdout, () => $`echo.js ${'a'}\\${'b'}`, 'a\\b');172test('$ concatenates tokens - \\', testScriptStdout, () => $`echo.js \\a\\ b`, '\\a\\\nb');173test('$ concatenates expressions - \\', testScriptStdout, () => $`echo.js \\${'a'}\\ b`, '\\a\\\nb');174test('$ handles tokens - \\\\', testScriptStdout, () => $`echo.js \\\\`, '\\\\');175test('$ handles expressions - \\\\', testScriptStdout, () => $`echo.js ${'\\\\'}`, '\\\\');176test('$ splits tokens - \\\\', testScriptStdout, () => $`echo.js a\\\\b`, 'a\\\\b');177test('$ splits expressions - \\\\', testScriptStdout, () => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b');178test('$ concatenates tokens - \\\\', testScriptStdout, () => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb');179test('$ concatenates expressions - \\\\', testScriptStdout, () => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb');180test('$ handles tokens - `', testScriptStdout, () => $`echo.js \``, '`');181test('$ handles expressions - `', testScriptStdout, () => $`echo.js ${'`'}`, '`');182test('$ splits tokens - `', testScriptStdout, () => $`echo.js a\`b`, 'a`b');183test('$ splits expressions - `', testScriptStdout, () => $`echo.js ${'a'}\`${'b'}`, 'a`b');184test('$ concatenates tokens - `', testScriptStdout, () => $`echo.js \`a\` b`, '`a`\nb');185test('$ concatenates expressions - `', testScriptStdout, () => $`echo.js \`${'a'}\` b`, '`a`\nb');186test('$ handles tokens - \\v', testScriptStdout, () => $`echo.js \v`, '\v');187test('$ handles expressions - \\v', testScriptStdout, () => $`echo.js ${'\v'}`, '\v');188test('$ splits tokens - \\v', testScriptStdout, () => $`echo.js a\vb`, 'a\vb');189test('$ splits expressions - \\v', testScriptStdout, () => $`echo.js ${'a'}\v${'b'}`, 'a\vb');190test('$ concatenates tokens - \\v', testScriptStdout, () => $`echo.js \va\v b`, '\va\v\nb');191test('$ concatenates expressions - \\v', testScriptStdout, () => $`echo.js \v${'a'}\v b`, '\va\v\nb');192test('$ handles tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028`, '\u{2028}');193test('$ handles expressions - \\u2028', testScriptStdout, () => $`echo.js ${'\u{2028}'}`, '\u{2028}');194test('$ splits tokens - \\u2028', testScriptStdout, () => $`echo.js a\u2028b`, 'a\u{2028}b');195test('$ splits expressions - \\u2028', testScriptStdout, () => $`echo.js ${'a'}\u2028${'b'}`, 'a\u{2028}b');196test('$ concatenates tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028a\u2028 b`, '\u{2028}a\u{2028}\nb');197test('$ concatenates expressions - \\u2028', testScriptStdout, () => $`echo.js \u2028${'a'}\u2028 b`, '\u{2028}a\u{2028}\nb');198test('$ handles tokens - \\a', testScriptStdout, () => $`echo.js \a`, 'a');199test('$ splits tokens - \\a', testScriptStdout, () => $`echo.js a\ab`, 'aab');200test('$ splits expressions - \\a', testScriptStdout, () => $`echo.js ${'a'}\a${'b'}`, 'aab');201test('$ concatenates tokens - \\a', testScriptStdout, () => $`echo.js \aa\a b`, 'aaa\nb');202test('$ concatenates expressions - \\a', testScriptStdout, () => $`echo.js \a${'a'}\a b`, 'aaa\nb');203test('$ handles tokens - \\cJ', testScriptStdout, () => $`echo.js \cJ`, 'cJ');204test('$ splits tokens - \\cJ', testScriptStdout, () => $`echo.js a\cJb`, 'acJb');205test('$ splits expressions - \\cJ', testScriptStdout, () => $`echo.js ${'a'}\cJ${'b'}`, 'acJb');206test('$ concatenates tokens - \\cJ', testScriptStdout, () => $`echo.js \cJa\cJ b`, 'cJacJ\nb');207test('$ concatenates expressions - \\cJ', testScriptStdout, () => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb');208test('$ handles tokens - \\.', testScriptStdout, () => $`echo.js \.`, '.');209test('$ splits tokens - \\.', testScriptStdout, () => $`echo.js a\.b`, 'a.b');210test('$ splits expressions - \\.', testScriptStdout, () => $`echo.js ${'a'}\.${'b'}`, 'a.b');211test('$ concatenates tokens - \\.', testScriptStdout, () => $`echo.js \.a\. b`, '.a.\nb');212test('$ concatenates expressions - \\.', testScriptStdout, () => $`echo.js \.${'a'}\. b`, '.a.\nb');164test('$ handles tokens - \\f (escape)', () => testScriptStdout(() => $`echo.js \f`, '\f'));165test('$ handles expressions - \\f (escape)', () => testScriptStdout(() => $`echo.js ${'\f'}`, '\f'));166test('$ splits tokens - \\f (escape)', () => testScriptStdout(() => $`echo.js a\fb`, 'a\fb'));167test('$ splits expressions - \\f (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\f${'b'}`, 'a\fb'));168test('$ concatenates tokens - \\f (escape)', () => testScriptStdout(() => $`echo.js \fa\f b`, '\fa\f\nb'));169test('$ concatenates expressions - \\f (escape)', () => testScriptStdout(() => $`echo.js \f${'a'}\f b`, '\fa\f\nb'));170test('$ handles tokens - \\', () => testScriptStdout(() => $`echo.js \\`, '\\'));171test('$ handles expressions - \\', () => testScriptStdout(() => $`echo.js ${'\\'}`, '\\'));172test('$ splits tokens - \\', () => testScriptStdout(() => $`echo.js a\\b`, 'a\\b'));173test('$ splits expressions - \\', () => testScriptStdout(() => $`echo.js ${'a'}\\${'b'}`, 'a\\b'));174test('$ concatenates tokens - \\', () => testScriptStdout(() => $`echo.js \\a\\ b`, '\\a\\\nb'));175test('$ concatenates expressions - \\', () => testScriptStdout(() => $`echo.js \\${'a'}\\ b`, '\\a\\\nb'));176test('$ handles tokens - \\\\', () => testScriptStdout(() => $`echo.js \\\\`, '\\\\'));177test('$ handles expressions - \\\\', () => testScriptStdout(() => $`echo.js ${'\\\\'}`, '\\\\'));178test('$ splits tokens - \\\\', () => testScriptStdout(() => $`echo.js a\\\\b`, 'a\\\\b'));179test('$ splits expressions - \\\\', () => testScriptStdout(() => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b'));180test('$ concatenates tokens - \\\\', () => testScriptStdout(() => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb'));181test('$ concatenates expressions - \\\\', () => testScriptStdout(() => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb'));182test('$ handles tokens - `', () => testScriptStdout(() => $`echo.js \``, '`'));183test('$ handles expressions - `', () => testScriptStdout(() => $`echo.js ${'`'}`, '`'));184test('$ splits tokens - `', () => testScriptStdout(() => $`echo.js a\`b`, 'a`b'));185test('$ splits expressions - `', () => testScriptStdout(() => $`echo.js ${'a'}\`${'b'}`, 'a`b'));186test('$ concatenates tokens - `', () => testScriptStdout(() => $`echo.js \`a\` b`, '`a`\nb'));187test('$ concatenates expressions - `', () => testScriptStdout(() => $`echo.js \`${'a'}\` b`, '`a`\nb'));188test('$ handles tokens - \\v', () => testScriptStdout(() => $`echo.js \v`, '\v'));189test('$ handles expressions - \\v', () => testScriptStdout(() => $`echo.js ${'\v'}`, '\v'));190test('$ splits tokens - \\v', () => testScriptStdout(() => $`echo.js a\vb`, 'a\vb'));191test('$ splits expressions - \\v', () => testScriptStdout(() => $`echo.js ${'a'}\v${'b'}`, 'a\vb'));192test('$ concatenates tokens - \\v', () => testScriptStdout(() => $`echo.js \va\v b`, '\va\v\nb'));193test('$ concatenates expressions - \\v', () => testScriptStdout(() => $`echo.js \v${'a'}\v b`, '\va\v\nb'));194test('$ handles tokens - \\u2028', () => testScriptStdout(() => $`echo.js \u2028`, '\u{2028}'));195test('$ handles expressions - \\u2028', () => testScriptStdout(() => $`echo.js ${'\u{2028}'}`, '\u{2028}'));196test('$ splits tokens - \\u2028', () => testScriptStdout(() => $`echo.js a\u2028b`, 'a\u{2028}b'));197test('$ splits expressions - \\u2028', () => testScriptStdout(() => $`echo.js ${'a'}\u2028${'b'}`, 'a\u{2028}b'));198test('$ concatenates tokens - \\u2028', () => testScriptStdout(() => $`echo.js \u2028a\u2028 b`, '\u{2028}a\u{2028}\nb'));199test('$ concatenates expressions - \\u2028', () => testScriptStdout(() => $`echo.js \u2028${'a'}\u2028 b`, '\u{2028}a\u{2028}\nb'));200test('$ handles tokens - \\a', () => testScriptStdout(() => $`echo.js \a`, 'a'));201test('$ splits tokens - \\a', () => testScriptStdout(() => $`echo.js a\ab`, 'aab'));202test('$ splits expressions - \\a', () => testScriptStdout(() => $`echo.js ${'a'}\a${'b'}`, 'aab'));203test('$ concatenates tokens - \\a', () => testScriptStdout(() => $`echo.js \aa\a b`, 'aaa\nb'));204test('$ concatenates expressions - \\a', () => testScriptStdout(() => $`echo.js \a${'a'}\a b`, 'aaa\nb'));205test('$ handles tokens - \\cJ', () => testScriptStdout(() => $`echo.js \cJ`, 'cJ'));206test('$ splits tokens - \\cJ', () => testScriptStdout(() => $`echo.js a\cJb`, 'acJb'));207test('$ splits expressions - \\cJ', () => testScriptStdout(() => $`echo.js ${'a'}\cJ${'b'}`, 'acJb'));208test('$ concatenates tokens - \\cJ', () => testScriptStdout(() => $`echo.js \cJa\cJ b`, 'cJacJ\nb'));209test('$ concatenates expressions - \\cJ', () => testScriptStdout(() => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb'));210test('$ handles tokens - \\.', () => testScriptStdout(() => $`echo.js \.`, '.'));211test('$ splits tokens - \\.', () => testScriptStdout(() => $`echo.js a\.b`, 'a.b'));212test('$ splits expressions - \\.', () => testScriptStdout(() => $`echo.js ${'a'}\.${'b'}`, 'a.b'));213test('$ concatenates tokens - \\.', () => testScriptStdout(() => $`echo.js \.a\. b`, '.a.\nb'));214test('$ concatenates expressions - \\.', () => testScriptStdout(() => $`echo.js \.${'a'}\. b`, '.a.\nb'));215214test('$ handles tokens - \\x63', testScriptStdout, () => $`echo.js \x63`, 'c');215test('$ splits tokens - \\x63', testScriptStdout, () => $`echo.js a\x63b`, 'acb');216test('$ splits expressions - \\x63', testScriptStdout, () => $`echo.js ${'a'}\x63${'b'}`, 'acb');217test('$ concatenates tokens - \\x63', testScriptStdout, () => $`echo.js \x63a\x63 b`, 'cac\nb');218test('$ concatenates expressions - \\x63', testScriptStdout, () => $`echo.js \x63${'a'}\x63 b`, 'cac\nb');216test('$ handles tokens - \\x63', () => testScriptStdout(() => $`echo.js \x63`, 'c'));217test('$ splits tokens - \\x63', () => testScriptStdout(() => $`echo.js a\x63b`, 'acb'));218test('$ splits expressions - \\x63', () => testScriptStdout(() => $`echo.js ${'a'}\x63${'b'}`, 'acb'));219test('$ concatenates tokens - \\x63', () => testScriptStdout(() => $`echo.js \x63a\x63 b`, 'cac\nb'));220test('$ concatenates expressions - \\x63', () => testScriptStdout(() => $`echo.js \x63${'a'}\x63 b`, 'cac\nb'));221220test('$ handles tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063`, 'c');221test('$ splits tokens - \\u0063', testScriptStdout, () => $`echo.js a\u0063b`, 'acb');222test('$ splits expressions - \\u0063', testScriptStdout, () => $`echo.js ${'a'}\u0063${'b'}`, 'acb');223test('$ concatenates tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063a\u0063 b`, 'cac\nb');224test('$ concatenates expressions - \\u0063', testScriptStdout, () => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb');225test('$ handles tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}`, '\u{1}');226test('$ splits tokens - \\u{1}', testScriptStdout, () => $`echo.js a\u{1}b`, 'a\u{1}b');227test('$ splits expressions - \\u{1}', testScriptStdout, () => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u{1}b');228test('$ concatenates tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}a\u{1} b`, '\u{1}a\u{1}\nb');229test('$ concatenates expressions - \\u{1}', testScriptStdout, () => $`echo.js \u{1}${'a'}\u{1} b`, '\u{1}a\u{1}\nb');230test('$ handles tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}`, 'c');231test('$ splits tokens - \\u{63}', testScriptStdout, () => $`echo.js a\u{63}b`, 'acb');232test('$ splits expressions - \\u{63}', testScriptStdout, () => $`echo.js ${'a'}\u{63}${'b'}`, 'acb');233test('$ concatenates tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}a\u{63} b`, 'cac\nb');234test('$ concatenates expressions - \\u{63}', testScriptStdout, () => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb');235test('$ handles tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}`, 'c');236test('$ splits tokens - \\u{063}', testScriptStdout, () => $`echo.js a\u{063}b`, 'acb');237test('$ splits expressions - \\u{063}', testScriptStdout, () => $`echo.js ${'a'}\u{063}${'b'}`, 'acb');238test('$ concatenates tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}a\u{063} b`, 'cac\nb');239test('$ concatenates expressions - \\u{063}', testScriptStdout, () => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb');240test('$ handles tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}`, 'c');241test('$ splits tokens - \\u{0063}', testScriptStdout, () => $`echo.js a\u{0063}b`, 'acb');242test('$ splits expressions - \\u{0063}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb');243test('$ concatenates tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb');244test('$ concatenates expressions - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb');245test('$ handles tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}`, 'c');246test('$ splits tokens - \\u{00063}', testScriptStdout, () => $`echo.js a\u{00063}b`, 'acb');247test('$ splits expressions - \\u{00063}', testScriptStdout, () => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb');248test('$ concatenates tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb');249test('$ concatenates expressions - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb');250test('$ handles tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}`, 'c');251test('$ splits tokens - \\u{000063}', testScriptStdout, () => $`echo.js a\u{000063}b`, 'acb');252test('$ splits expressions - \\u{000063}', testScriptStdout, () => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb');253test('$ concatenates tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb');254test('$ concatenates expressions - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb');255test('$ handles tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}`, 'c');256test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');257test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');258test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');259test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');222test('$ handles tokens - \\u0063', () => testScriptStdout(() => $`echo.js \u0063`, 'c'));223test('$ splits tokens - \\u0063', () => testScriptStdout(() => $`echo.js a\u0063b`, 'acb'));224test('$ splits expressions - \\u0063', () => testScriptStdout(() => $`echo.js ${'a'}\u0063${'b'}`, 'acb'));225test('$ concatenates tokens - \\u0063', () => testScriptStdout(() => $`echo.js \u0063a\u0063 b`, 'cac\nb'));226test('$ concatenates expressions - \\u0063', () => testScriptStdout(() => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb'));227test('$ handles tokens - \\u{1}', () => testScriptStdout(() => $`echo.js \u{1}`, '\u{1}'));228test('$ splits tokens - \\u{1}', () => testScriptStdout(() => $`echo.js a\u{1}b`, 'a\u{1}b'));229test('$ splits expressions - \\u{1}', () => testScriptStdout(() => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u{1}b'));230test('$ concatenates tokens - \\u{1}', () => testScriptStdout(() => $`echo.js \u{1}a\u{1} b`, '\u{1}a\u{1}\nb'));231test('$ concatenates expressions - \\u{1}', () => testScriptStdout(() => $`echo.js \u{1}${'a'}\u{1} b`, '\u{1}a\u{1}\nb'));232test('$ handles tokens - \\u{63}', () => testScriptStdout(() => $`echo.js \u{63}`, 'c'));233test('$ splits tokens - \\u{63}', () => testScriptStdout(() => $`echo.js a\u{63}b`, 'acb'));234test('$ splits expressions - \\u{63}', () => testScriptStdout(() => $`echo.js ${'a'}\u{63}${'b'}`, 'acb'));235test('$ concatenates tokens - \\u{63}', () => testScriptStdout(() => $`echo.js \u{63}a\u{63} b`, 'cac\nb'));236test('$ concatenates expressions - \\u{63}', () => testScriptStdout(() => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb'));237test('$ handles tokens - \\u{063}', () => testScriptStdout(() => $`echo.js \u{063}`, 'c'));238test('$ splits tokens - \\u{063}', () => testScriptStdout(() => $`echo.js a\u{063}b`, 'acb'));239test('$ splits expressions - \\u{063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{063}${'b'}`, 'acb'));240test('$ concatenates tokens - \\u{063}', () => testScriptStdout(() => $`echo.js \u{063}a\u{063} b`, 'cac\nb'));241test('$ concatenates expressions - \\u{063}', () => testScriptStdout(() => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb'));242test('$ handles tokens - \\u{0063}', () => testScriptStdout(() => $`echo.js \u{0063}`, 'c'));243test('$ splits tokens - \\u{0063}', () => testScriptStdout(() => $`echo.js a\u{0063}b`, 'acb'));244test('$ splits expressions - \\u{0063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb'));245test('$ concatenates tokens - \\u{0063}', () => testScriptStdout(() => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb'));246test('$ concatenates expressions - \\u{0063}', () => testScriptStdout(() => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb'));247test('$ handles tokens - \\u{00063}', () => testScriptStdout(() => $`echo.js \u{00063}`, 'c'));248test('$ splits tokens - \\u{00063}', () => testScriptStdout(() => $`echo.js a\u{00063}b`, 'acb'));249test('$ splits expressions - \\u{00063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb'));250test('$ concatenates tokens - \\u{00063}', () => testScriptStdout(() => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb'));251test('$ concatenates expressions - \\u{00063}', () => testScriptStdout(() => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb'));252test('$ handles tokens - \\u{000063}', () => testScriptStdout(() => $`echo.js \u{000063}`, 'c'));253test('$ splits tokens - \\u{000063}', () => testScriptStdout(() => $`echo.js a\u{000063}b`, 'acb'));254test('$ splits expressions - \\u{000063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb'));255test('$ concatenates tokens - \\u{000063}', () => testScriptStdout(() => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb'));256test('$ concatenates expressions - \\u{000063}', () => testScriptStdout(() => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb'));257test('$ handles tokens - \\u{0000063}', () => testScriptStdout(() => $`echo.js \u{0000063}`, 'c'));258test('$ splits tokens - \\u{0000063}', () => testScriptStdout(() => $`echo.js a\u{0000063}b`, 'acb'));259test('$ splits expressions - \\u{0000063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb'));260test('$ concatenates tokens - \\u{0000063}', () => testScriptStdout(() => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb'));261test('$ concatenates expressions - \\u{0000063}', () => testScriptStdout(() => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb'));262263// Code points above the BMP are a surrogate pair, i.e. two characters, in the template string but not in its raw version.264// Miscounting them shifts every following character, which splits tokens at the wrong place and breaks the surrogate pair.263test('$ handles tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}`, '\u{1F600}');264test('$ splits tokens - \\u{1F600}', testScriptStdout, () => $`echo.js a\u{1F600}b`, 'a\u{1F600}b');265test('$ splits expressions - \\u{1F600}', testScriptStdout, () => $`echo.js ${'a'}\u{1F600}${'b'}`, 'a\u{1F600}b');266test('$ concatenates tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}a\u{1F600} b`, '\u{1F600}a\u{1F600}\nb');267test('$ concatenates expressions - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}${'a'}\u{1F600} b`, '\u{1F600}a\u{1F600}\nb');268test('$ handles multiple tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}\u{1F600} b c`, '\u{1F600}\u{1F600}\nb\nc');269test('$ handles the highest code point - \\u{10FFFF}', testScriptStdout, () => $`echo.js \u{10FFFF} b`, '\u{10FFFF}\nb');265test('$ handles tokens - \\u{1F600}', () => testScriptStdout(() => $`echo.js \u{1F600}`, '\u{1F600}'));266test('$ splits tokens - \\u{1F600}', () => testScriptStdout(() => $`echo.js a\u{1F600}b`, 'a\u{1F600}b'));267test('$ splits expressions - \\u{1F600}', () => testScriptStdout(() => $`echo.js ${'a'}\u{1F600}${'b'}`, 'a\u{1F600}b'));268test('$ concatenates tokens - \\u{1F600}', () => testScriptStdout(() => $`echo.js \u{1F600}a\u{1F600} b`, '\u{1F600}a\u{1F600}\nb'));269test('$ concatenates expressions - \\u{1F600}', () => testScriptStdout(() => $`echo.js \u{1F600}${'a'}\u{1F600} b`, '\u{1F600}a\u{1F600}\nb'));270test('$ handles multiple tokens - \\u{1F600}', () => testScriptStdout(() => $`echo.js \u{1F600}\u{1F600} b c`, '\u{1F600}\u{1F600}\nb\nc'));271test('$ handles the highest code point - \\u{10FFFF}', () => testScriptStdout(() => $`echo.js \u{10FFFF} b`, '\u{10FFFF}\nb'));272// The BMP boundary is the exact point where the character count changes271test('$ handles the last BMP code point - \\u{FFFF}', testScriptStdout, () => $`echo.js \u{FFFF} b`, '\u{FFFF}\nb');272test('$ handles the first astral code point - \\u{10000}', testScriptStdout, () => $`echo.js \u{10000} b`, '\u{10000}\nb');273test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');274test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');275test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');276test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');277test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');273test('$ handles the last BMP code point - \\u{FFFF}', () => testScriptStdout(() => $`echo.js \u{FFFF} b`, '\u{FFFF}\nb'));274test('$ handles the first astral code point - \\u{10000}', () => testScriptStdout(() => $`echo.js \u{10000} b`, '\u{10000}\nb'));275test('$ handles tokens - \\u{0063}}', () => testScriptStdout(() => $`echo.js \u{0063}}`, 'c}'));276test('$ splits tokens - \\u{0063}}', () => testScriptStdout(() => $`echo.js a\u{0063}}b`, 'ac}b'));277test('$ splits expressions - \\u{0063}}', () => testScriptStdout(() => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b'));278test('$ concatenates tokens - \\u{0063}}', () => testScriptStdout(() => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb'));279test('$ concatenates expressions - \\u{0063}}', () => testScriptStdout(() => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb'));280279const testScriptErrorStdout = async (t, getSubprocess) => {280 t.throws(getSubprocess, {message: /null bytes/});281const testScriptErrorStdout = async getSubprocess => {282 assertThrows(getSubprocess, {message: /null bytes/});283};284283test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);284test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);285test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);286test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);287test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);285test('$ handles tokens - \\0', () => testScriptErrorStdout(() => $`echo.js \0`));286test('$ splits tokens - \\0', () => testScriptErrorStdout(() => $`echo.js a\0b`));287test('$ splits expressions - \\0', () => testScriptErrorStdout(() => $`echo.js ${'a'}\0${'b'}`));288test('$ concatenates tokens - \\0', () => testScriptErrorStdout(() => $`echo.js \0a\0 b`));289test('$ concatenates expressions - \\0', () => testScriptErrorStdout(() => $`echo.js \0${'a'}\0 b`));290289const testReturnInterpolate = async (t, getSubprocess, expectedStdout, options = {}) => {291const testReturnInterpolate = async (getSubprocess, expectedStdout, options = {}) => {292 const foo = await $(options)`echo.js foo`;293 const {stdout} = await getSubprocess(foo);292 t.is(stdout, expectedStdout);294 assert.equal(stdout, expectedStdout);295};296295test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');296test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});297test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');298test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});297test('$ allows execa return value interpolation', () => testReturnInterpolate(foo => $`echo.js ${foo} bar`, 'foo\nbar'));298test('$ allows execa return value buffer interpolation', () => testReturnInterpolate(foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'}));299test('$ allows execa return value array interpolation', () => testReturnInterpolate(foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar'));300test('$ allows execa return value buffer array interpolation', () => testReturnInterpolate(foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'}));301300const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {302const testReturnInterpolateSync = (getSubprocess, expectedStdout, options = {}) => {303 const foo = $(options).sync`echo.js foo`;304 const {stdout} = getSubprocess(foo);303 t.is(stdout, expectedStdout);305 assert.equal(stdout, expectedStdout);306};307306test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');307test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});308test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');309test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});308test('$.sync allows execa return value interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${foo} bar`, 'foo\nbar'));309test('$.sync allows execa return value buffer interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'}));310test('$.sync allows execa return value array interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar'));311test('$.sync allows execa return value buffer array interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'}));312311const testInvalidSequence = (t, getSubprocess) => {312 t.throws(getSubprocess, {message: /Invalid backslash sequence/});313const testInvalidSequence = getSubprocess => {314 assertThrows(getSubprocess, {message: /Invalid backslash sequence/});315};316315test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);316test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);317test('$ handles invalid escape sequence - \\u0', testInvalidSequence, () => $`echo.js \u0`);318test('$ handles invalid escape sequence - \\u00', testInvalidSequence, () => $`echo.js \u00`);319test('$ handles invalid escape sequence - \\u000', testInvalidSequence, () => $`echo.js \u000`);320test('$ handles invalid escape sequence - \\ug', testInvalidSequence, () => $`echo.js \ug`);321test('$ handles invalid escape sequence - \\u{', testInvalidSequence, () => $`echo.js \u{`);322test('$ handles invalid escape sequence - \\u{0000', testInvalidSequence, () => $`echo.js \u{0000`);323test('$ handles invalid escape sequence - \\u{g}', testInvalidSequence, () => $`echo.js \u{g}`);317test('$ handles invalid escape sequence - \\1', () => testInvalidSequence(() => $`echo.js \1`));318test('$ handles invalid escape sequence - \\u', () => testInvalidSequence(() => $`echo.js \u`));319test('$ handles invalid escape sequence - \\u0', () => testInvalidSequence(() => $`echo.js \u0`));320test('$ handles invalid escape sequence - \\u00', () => testInvalidSequence(() => $`echo.js \u00`));321test('$ handles invalid escape sequence - \\u000', () => testInvalidSequence(() => $`echo.js \u000`));322test('$ handles invalid escape sequence - \\ug', () => testInvalidSequence(() => $`echo.js \ug`));323test('$ handles invalid escape sequence - \\u{', () => testInvalidSequence(() => $`echo.js \u{`));324test('$ handles invalid escape sequence - \\u{0000', () => testInvalidSequence(() => $`echo.js \u{0000`));325test('$ handles invalid escape sequence - \\u{g}', () => testInvalidSequence(() => $`echo.js \u{g}`));326325test('$ handles invalid escape sequence - \\x', testInvalidSequence, () => $`echo.js \x`);326test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);327test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);327test('$ handles invalid escape sequence - \\x', () => testInvalidSequence(() => $`echo.js \x`));328test('$ handles invalid escape sequence - \\x0', () => testInvalidSequence(() => $`echo.js \x0`));329test('$ handles invalid escape sequence - \\xgg', () => testInvalidSequence(() => $`echo.js \xgg`));330329const testEmptyScript = (t, getSubprocess) => {330 t.throws(getSubprocess, {message: /Template script must not be empty/});331const testEmptyScript = getSubprocess => {332 assertThrows(getSubprocess, {message: /Template script must not be empty/});333};334333test('$``', testEmptyScript, () => $``);334test('$` `', testEmptyScript, () => $` `);335test('$` ` (2 spaces)', testEmptyScript, () => $` `);336test('$`\\t`', testEmptyScript, () => $` `);337test('$`\\n`', testEmptyScript, () => $`338`);335test('$``', () => testEmptyScript(() => $``));336test('$` `', () => testEmptyScript(() => $` `));337test('$` ` (2 spaces)', () => testEmptyScript(() => $` `));338test('$`\\t`', () => testEmptyScript(() => $` `));339test('$`\\n`', () => testEmptyScript(() => $`340`));341340const testInvalidExpression = (t, invalidExpression) => {341 t.throws(342const testInvalidExpression = invalidExpression => {343 assertThrows(344 () => $`echo.js ${invalidExpression}`,345 {message: /in template expression/},346 );347};348347test('$ throws on invalid expression - undefined', testInvalidExpression, undefined);348test('$ throws on invalid expression - null', testInvalidExpression, null);349test('$ throws on invalid expression - true', testInvalidExpression, true);350test('$ throws on invalid expression - {}', testInvalidExpression, {});351test('$ throws on invalid expression - {foo: "bar"}', testInvalidExpression, {foo: 'bar'});352test('$ throws on invalid expression - {stdout: 1}', testInvalidExpression, {stdout: 1});353test('$ throws on invalid expression - [undefined]', testInvalidExpression, [undefined]);354test('$ throws on invalid expression - [null]', testInvalidExpression, [null]);355test('$ throws on invalid expression - [true]', testInvalidExpression, [true]);356test('$ throws on invalid expression - [{}]', testInvalidExpression, [{}]);357test('$ throws on invalid expression - [{foo: "bar"}]', testInvalidExpression, [{foo: 'bar'}]);358test('$ throws on invalid expression - [{stdout: 1}]', testInvalidExpression, [{stdout: 1}]);349test('$ throws on invalid expression - undefined', () => testInvalidExpression(undefined));350test('$ throws on invalid expression - null', () => testInvalidExpression(null));351test('$ throws on invalid expression - true', () => testInvalidExpression(true));352test('$ throws on invalid expression - {}', () => testInvalidExpression({}));353test('$ throws on invalid expression - {foo: "bar"}', () => testInvalidExpression({foo: 'bar'}));354test('$ throws on invalid expression - {stdout: 1}', () => testInvalidExpression({stdout: 1}));355test('$ throws on invalid expression - [undefined]', () => testInvalidExpression([undefined]));356test('$ throws on invalid expression - [null]', () => testInvalidExpression([null]));357test('$ throws on invalid expression - [true]', () => testInvalidExpression([true]));358test('$ throws on invalid expression - [{}]', () => testInvalidExpression([{}]));359test('$ throws on invalid expression - [{foo: "bar"}]', () => testInvalidExpression([{foo: 'bar'}]));360test('$ throws on invalid expression - [{stdout: 1}]', () => testInvalidExpression([{stdout: 1}]));361360const testMissingOutput = (t, invalidExpression) => {361 t.throws(362const testMissingOutput = invalidExpression => {363 assertThrows(364 () => $`echo.js ${invalidExpression()}`,365 {message: /Missing result.stdout/},366 );367};368367test('$ throws on invalid expression - {stdout: undefined}', testMissingOutput, () => ({stdout: undefined}));368test('$ throws on invalid expression - [{stdout: undefined}]', testMissingOutput, () => [{stdout: undefined}]);369test('$ throws on invalid expression - $(options).sync', testMissingOutput, () => $({stdio: 'ignore'}).sync`noop.js`);370test('$ throws on invalid expression - [$(options).sync]', testMissingOutput, () => [$({stdio: 'ignore'}).sync`noop.js`]);369test('$ throws on invalid expression - {stdout: undefined}', () => testMissingOutput(() => ({stdout: undefined})));370test('$ throws on invalid expression - [{stdout: undefined}]', () => testMissingOutput(() => [{stdout: undefined}]));371test('$ throws on invalid expression - $(options).sync', () => testMissingOutput(() => $({stdio: 'ignore'}).sync`noop.js`));372test('$ throws on invalid expression - [$(options).sync]', () => testMissingOutput(() => [$({stdio: 'ignore'}).sync`noop.js`]));373372const testInvalidPromise = (t, invalidExpression) => {373 t.throws(374const testInvalidPromise = invalidExpression => {375 assertThrows(376 () => $`echo.js ${invalidExpression()}`,377 {message: /Please use \${await subprocess}/},378 );379};380379test('$ throws on invalid expression - Promise.resolve()', testInvalidPromise, async () => ({}));380test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', testInvalidPromise, async () => ({foo: 'bar'}));381test('$ throws on invalid expression - [Promise.resolve()]', testInvalidPromise, () => [Promise.resolve()]);382test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', testInvalidPromise, () => [Promise.resolve({stdout: 'foo'})]);383test('$ throws on invalid expression - $', testInvalidPromise, () => $`noop.js`);384test('$ throws on invalid expression - [$]', testInvalidPromise, () => [$`noop.js`]);381test('$ throws on invalid expression - Promise.resolve()', () => testInvalidPromise(async () => ({})));382test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', () => testInvalidPromise(async () => ({foo: 'bar'})));383test('$ throws on invalid expression - [Promise.resolve()]', () => testInvalidPromise(() => [Promise.resolve()]));384test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', () => testInvalidPromise(() => [Promise.resolve({stdout: 'foo'})]));385test('$ throws on invalid expression - $', () => testInvalidPromise(() => $`noop.js`));386test('$ throws on invalid expression - [$]', () => testInvalidPromise(() => [$`noop.js`]));
modified:test/pipe/abort.js+60 added-58 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';2import test from 'ava';3import test from 'node:test';4import {assertRejects, assertLike} from '../helpers/assert.js';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {foobarString} from '../helpers/input.js';89setFixtureDirectory();109const assertUnPipeError = async (t, pipePromise) => {10 const error = await t.throwsAsync(pipePromise);11const assertUnPipeError = async pipePromise => {12 const error = await assertRejects(pipePromise);1312 t.is(error.command, 'source.pipe(destination)');13 t.is(error.escapedCommand, error.command);14 assert.equal(error.command, 'source.pipe(destination)');15 assert.equal(error.escapedCommand, error.command);1615 t.is(typeof error.cwd, 'string');16 t.true(error.failed);17 t.false(error.timedOut);18 t.false(error.isCanceled);19 t.false(error.isTerminated);20 t.is(error.exitCode, undefined);21 t.is(error.signal, undefined);22 t.is(error.signalDescription, undefined);23 t.is(error.stdout, undefined);24 t.is(error.stderr, undefined);25 t.is(error.all, undefined);26 t.deepEqual(error.stdio, Array.from({length: error.stdio.length}));27 t.deepEqual(error.pipedFrom, []);17 assert.equal(typeof error.cwd, 'string');18 assert.equal(error.failed, true);19 assert.equal(error.timedOut, false);20 assert.equal(error.isCanceled, false);21 assert.equal(error.isTerminated, false);22 assert.equal(error.exitCode, undefined);23 assert.equal(error.signal, undefined);24 assert.equal(error.signalDescription, undefined);25 assert.equal(error.stdout, undefined);26 assert.equal(error.stderr, undefined);27 assert.equal(error.all, undefined);28 assert.deepEqual(error.stdio, Array.from({length: error.stdio.length}));29 assert.deepEqual(error.pipedFrom, []);3029 t.true(error.originalMessage.includes('Pipe canceled'));30 t.true(error.shortMessage.includes(`Command failed: ${error.command}`));31 t.true(error.shortMessage.includes(error.originalMessage));32 t.true(error.message.includes(error.shortMessage));31 assert.ok(error.originalMessage.includes('Pipe canceled'));32 assert.ok(error.shortMessage.includes(`Command failed: ${error.command}`));33 assert.ok(error.shortMessage.includes(error.originalMessage));34 assert.ok(error.message.includes(error.shortMessage));35};3635test('Can unpipe a single subprocess', async t => {37test('Can unpipe a single subprocess', async () => {38 const abortController = new AbortController();39 const source = execa('stdin.js');40 const destination = execa('stdin.js');41 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});4243 abortController.abort();42 await assertUnPipeError(t, pipePromise);44 await assertUnPipeError(pipePromise);4546 source.stdin.end(foobarString);47 destination.stdin.end('.');4847 t.like(await destination, {stdout: '.'});48 t.like(await source, {stdout: foobarString});49 assertLike(await destination, {stdout: '.'});50 assertLike(await source, {stdout: foobarString});51});5251test('Can use an already aborted signal', async t => {53test('Can use an already aborted signal', async () => {54 const abortController = new AbortController();55 abortController.abort();56 const source = execa('empty.js');57 const destination = execa('empty.js');58 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});5958 await assertUnPipeError(t, pipePromise);60 await assertUnPipeError(pipePromise);61});6261test('Can unpipe a subprocess among other sources', async t => {63test('Can unpipe a subprocess among other sources', async () => {64 const abortController = new AbortController();65 const source = execa('stdin.js');66 const secondSource = execa('noop.js', [foobarString]);67 const destination = execa('stdin.js');68 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});69 const secondPipePromise = secondSource.pipe(destination);7071 abortController.abort();70 await assertUnPipeError(t, pipePromise);72 await assertUnPipeError(pipePromise);7374 source.stdin.end('.');7574 t.is(await secondPipePromise, await destination);75 t.like(await destination, {stdout: foobarString});76 t.like(await source, {stdout: '.'});77 t.like(await secondSource, {stdout: foobarString});76 assert.equal(await secondPipePromise, await destination);77 assertLike(await destination, {stdout: foobarString});78 assertLike(await source, {stdout: '.'});79 assertLike(await secondSource, {stdout: foobarString});80});8180test('Can unpipe a subprocess among other sources on the same subprocess', async t => {82test('Can unpipe a subprocess among other sources on the same subprocess', async () => {83 const abortController = new AbortController();84 const source = execa('stdin-both.js');85 const destination = execa('stdin.js');86 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});87 const secondPipePromise = source.pipe(destination, {from: 'stderr'});8889 abortController.abort();88 await assertUnPipeError(t, pipePromise);90 await assertUnPipeError(pipePromise);9192 source.stdin.end(foobarString);9392 t.is(await secondPipePromise, await destination);93 t.like(await destination, {stdout: foobarString});94 t.like(await source, {stdout: foobarString, stderr: foobarString});94 assert.equal(await secondPipePromise, await destination);95 assertLike(await destination, {stdout: foobarString});96 assertLike(await source, {stdout: foobarString, stderr: foobarString});97});9897test('Can unpipe a subprocess among other destinations', async t => {99test('Can unpipe a subprocess among other destinations', async () => {100 const abortController = new AbortController();101 const source = execa('stdin.js');102 const destination = execa('stdin.js');103 const secondDestination = execa('stdin.js');104 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});105 const secondPipePromise = source.pipe(secondDestination);106107 abortController.abort();106 await assertUnPipeError(t, pipePromise);108 await assertUnPipeError(pipePromise);109110 source.stdin.end(foobarString);111 destination.stdin.end('.');112111 t.is(await secondPipePromise, await secondDestination);112 t.like(await destination, {stdout: '.'});113 t.like(await source, {stdout: foobarString});114 t.like(await secondDestination, {stdout: foobarString});113 assert.equal(await secondPipePromise, await secondDestination);114 assertLike(await destination, {stdout: '.'});115 assertLike(await source, {stdout: foobarString});116 assertLike(await secondDestination, {stdout: foobarString});117});118117test('Can unpipe then re-pipe a subprocess', async t => {119test('Can unpipe then re-pipe a subprocess', async () => {120 const abortController = new AbortController();121 const source = execa('stdin.js');122 const destination = execa('stdin.js');123 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});124125 source.stdin.write('.');126 const [firstWrite] = await once(source.stdout, 'data');125 t.is(firstWrite.toString(), '.');127 assert.equal(firstWrite.toString(), '.');128129 abortController.abort();128 await assertUnPipeError(t, pipePromise);130 await assertUnPipeError(pipePromise);131132 source.pipe(destination);133 source.stdin.end('.');134133 t.like(await destination, {stdout: '..'});134 t.like(await source, {stdout: '..'});135 assertLike(await destination, {stdout: '..'});136 assertLike(await source, {stdout: '..'});137});138137test('Can unpipe to prevent termination to propagate to source', async t => {139test('Can unpipe to prevent termination to propagate to source', async () => {140 const abortController = new AbortController();141 const source = execa('stdin.js');142 const destination = execa('stdin.js');143 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});144145 abortController.abort();144 await assertUnPipeError(t, pipePromise);146 await assertUnPipeError(pipePromise);147148 destination.kill();147 t.like(await t.throwsAsync(destination), {signal: 'SIGTERM'});149 assertLike(await assertRejects(destination), {signal: 'SIGTERM'});150151 source.stdin.end(foobarString);150 t.like(await source, {stdout: foobarString});152 assertLike(await source, {stdout: foobarString});153});154153test('Can unpipe to prevent termination to propagate to destination', async t => {155test('Can unpipe to prevent termination to propagate to destination', async () => {156 const abortController = new AbortController();157 const source = execa('noop-forever.js', [foobarString]);158 const destination = execa('stdin.js');159 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});160161 abortController.abort();160 await assertUnPipeError(t, pipePromise);162 await assertUnPipeError(pipePromise);163164 source.kill();163 t.like(await t.throwsAsync(source), {signal: 'SIGTERM'});165 assertLike(await assertRejects(source), {signal: 'SIGTERM'});166167 destination.stdin.end(foobarString);166 t.like(await destination, {stdout: foobarString});168 assertLike(await destination, {stdout: foobarString});169});
modified:test/pipe/methods.js+108 added-103 removed
1import assert from 'node:assert/strict';2import {setTimeout} from 'node:timers/promises';3import {Readable} from 'node:stream';4import {text} from 'node:stream/consumers';4import test from 'ava';5import test from 'node:test';6import {assertThrows, assertRejects} from '../helpers/assert.js';7import {execa} from '../../index.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9import {simpleFull, noNewlinesFull, noNewlinesChunks} from '../helpers/lines.js';10import {foobarString, foobarArray} from '../helpers/input.js';11/* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */1213setFixtureDirectory();1415const timeoutSymbol = Symbol('timeout');
2 unmodified lines
18const pipeSimple = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js');19const pipeAll = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js', {all: true});20const pipeDistinctBoth = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin-distinct-both.js');2119const assertSettles = async (t, promise, timeout = 1000) => {22const assertSettles = async (promise, timeout = 1000) => {23 const result = await Promise.race([24 promise,25 // Several pipe cancellation tests are specifically checking that a pending reader does not hang.26 setTimeout(timeout, timeoutSymbol, {ref: false}),27 ]);2826 t.not(result, timeoutSymbol);29 assert.notEqual(result, timeoutSymbol);30 return result;31};3233const cleanupSubprocesses = async (...subprocesses) => {
9 unmodified lines
4344 return messages;45};4644test('The .pipe() return value can be iterated', async t => {47test('The .pipe() return value can be iterated', async () => {48 const lines = await Array.fromAsync(pipeSimple());4947 t.deepEqual(lines, noNewlinesChunks);50 assert.deepEqual(lines, noNewlinesChunks);51});5250test('The .pipe() return value has an .iterable() method', async t => {53test('The .pipe() return value has an .iterable() method', async () => {54 const lines = await Array.fromAsync(pipeSimple().iterable());5553 t.deepEqual(lines, noNewlinesChunks);56 assert.deepEqual(lines, noNewlinesChunks);57});5856test('The .pipe() return value has a .readable() method', async t => {57 t.is(await text(pipeSimple().readable()), simpleFull);59test('The .pipe() return value has a .readable() method', async () => {60 assert.equal(await text(pipeSimple().readable()), simpleFull);61});6260test('The .pipe() return value has a .readableStream() method', async t => {61 t.is(await text(pipeSimple().readableStream()), simpleFull);63test('The .pipe() return value has a .readableStream() method', async () => {64 assert.equal(await text(pipeSimple().readableStream()), simpleFull);65});6664test('The .pipe() return value .readable() can be called multiple times', async t => {67test('The .pipe() return value .readable() can be called multiple times', async () => {68 const piped = pipeSimple();69 const [output, secondOutput] = await Promise.all([70 text(piped.readable()),71 text(piped.readable()),72 ]);7371 t.is(output, simpleFull);72 t.is(secondOutput, simpleFull);74 assert.equal(output, simpleFull);75 assert.equal(secondOutput, simpleFull);76});7775test('The .pipe() return value .readable() keeps conversion options', async t => {78test('The .pipe() return value .readable() keeps conversion options', async () => {79 const chunks = await Array.fromAsync(pipeSimple().readable({binary: false, preserveNewlines: false}));8078 t.deepEqual(chunks, noNewlinesChunks);79 t.is(chunks.join(''), noNewlinesFull);81 assert.deepEqual(chunks, noNewlinesChunks);82 assert.equal(chunks.join(''), noNewlinesFull);83});8482test('The .pipe() return value does not have a .writable() method', async t => {85test('The .pipe() return value does not have a .writable() method', async () => {86 const piped = pipeSimple();84 t.is(piped.writable, undefined);85 t.is(piped.duplex, undefined);86 t.is(piped.writableStream, undefined);87 t.is(piped.transformStream, undefined);87 assert.equal(piped.writable, undefined);88 assert.equal(piped.duplex, undefined);89 assert.equal(piped.writableStream, undefined);90 assert.equal(piped.transformStream, undefined);91 await piped;92});9391test('The .pipe() return value does not have .all unless destination uses the "all" option', async t => {94test('The .pipe() return value does not have .all unless destination uses the "all" option', async () => {95 const piped = pipeSimple();96 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');9795 t.is(piped.all, undefined);96 t.is(descriptor.value, undefined);97 t.is(descriptor.get, undefined);98 assert.equal(piped.all, undefined);99 assert.equal(descriptor.value, undefined);100 assert.equal(descriptor.get, undefined);101 await piped;102});103101test('The .pipe() return value has an .all property', async t => {104test('The .pipe() return value has an .all property', async () => {105 const piped = pipeAll();103 t.true(piped.all instanceof Readable);104 t.is(await text(piped.all), simpleFull);106 assert.ok(piped.all instanceof Readable);107 assert.equal(await text(piped.all), simpleFull);108 await piped;109});110108test('The .pipe() return value .all is created lazily and cached', async t => {111test('The .pipe() return value .all is created lazily and cached', async () => {112 const piped = pipeAll();113 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');114112 t.is(typeof descriptor.get, 'function');115 assert.equal(typeof descriptor.get, 'function');116 const {all} = piped;114 t.true(all instanceof Readable);115 t.is(piped.all, all);116 t.is(Object.getOwnPropertyDescriptor(piped, 'all').get, undefined);117 t.is(await text(all), simpleFull);117 assert.ok(all instanceof Readable);118 assert.equal(piped.all, all);119 assert.equal(Object.getOwnPropertyDescriptor(piped, 'all').get, undefined);120 assert.equal(await text(all), simpleFull);121 await piped;122});123121test('The .pipe() return value .readable() can read destination stderr', async t => {124test('The .pipe() return value .readable() can read destination stderr', async () => {125 const piped = pipeDistinctBoth();126124 t.is(await text(piped.readable({from: 'stderr'})), `${simpleFull}:stderr`);127 assert.equal(await text(piped.readable({from: 'stderr'})), `${simpleFull}:stderr`);128 await piped;129});130128test('The .pipe() return value .iterable() can read destination stderr', async t => {131test('The .pipe() return value .iterable() can read destination stderr', async () => {132 const piped = pipeDistinctBoth();133 const lines = await Array.fromAsync(piped.iterable({from: 'stderr'}));134132 t.deepEqual(lines, ['aaa', 'bbb', 'ccc:stderr']);135 assert.deepEqual(lines, ['aaa', 'bbb', 'ccc:stderr']);136 await piped;137});138136test('The .pipe() return value has IPC methods', async t => {139test('The .pipe() return value has IPC methods', async () => {140 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});138 t.deepEqual(await getPipeMessages(piped), foobarArray);141 assert.deepEqual(await getPipeMessages(piped), foobarArray);142 const {ipcOutput} = await piped;140 t.deepEqual(ipcOutput, foobarArray);143 assert.deepEqual(ipcOutput, foobarArray);144});145143test('The .pipe() return value .getEachMessage() can be called twice at the same time', async t => {146test('The .pipe() return value .getEachMessage() can be called twice at the same time', async () => {147 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});148146 t.deepEqual(149 assert.deepEqual(150 await Promise.all([getPipeMessages(piped), getPipeMessages(piped)]),151 [foobarArray, foobarArray],152 );153154 const {ipcOutput} = await piped;152 t.deepEqual(ipcOutput, foobarArray);155 assert.deepEqual(ipcOutput, foobarArray);156});157155test('The .pipe() return value .getEachMessage() preserves setup errors', async t => {158test('The .pipe() return value .getEachMessage() preserves setup errors', async () => {159 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});160158 t.throws(() => {161 assertThrows(() => {162 piped.getEachMessage(null);163 }, {instanceOf: TypeError});164165 await piped;166});167165test('The .pipe() return value .getEachMessage() waits for source failure', async t => {168test('The .pipe() return value .getEachMessage() waits for source failure', async () => {169 const piped = execa('fail.js').pipe('ipc-send-twice.js', {ipc: true});170168 await t.throwsAsync(async () => {171 await assertRejects(async () => {172 for await (const message of piped.getEachMessage()) {170 t.true(foobarArray.includes(message));173 assert.ok(foobarArray.includes(message));174 }175 }, {message: /Command failed with exit code 2/});176});177178test('The .pipe() return value .getEachMessage() waits for pipe cancellation', async t => {179 const abortController = new AbortController();180 const source = execa('noop-repeat.js');181 const destination = execa('ipc-send-forever.js', {ipc: true});179 t.teardown(async () => {182 t.after(async () => {183 await cleanupSubprocesses(source, destination);184 });185186 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});187 const iterator = piped.getEachMessage();185 t.deepEqual(await iterator.next(), {done: false, value: foobarString});188 assert.deepEqual(await iterator.next(), {done: false, value: foobarString});189187 const readerPromise = t.throwsAsync(iterator.next(), {message: /Pipe canceled/});190 const readerPromise = assertRejects(iterator.next(), {message: /Pipe canceled/});191 abortController.abort();189 await assertSettles(t, readerPromise);192 await assertSettles(readerPromise);193});194195test('The .pipe() return value .getEachMessage() cancels every pending reader', async t => {196 const abortController = new AbortController();197 const source = execa('noop-repeat.js');198 const destination = execa('ipc-send-forever.js', {ipc: true});196 t.teardown(async () => {199 t.after(async () => {200 await cleanupSubprocesses(source, destination);201 });202203 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});
1 unmodified line
205 piped.getEachMessage(),206 piped.getEachMessage(),207 ];208206 t.deepEqual(209 assert.deepEqual(210 await Promise.all(iterators.map(async iterator => iterator.next())),211 [212 {done: false, value: foobarString},213 {done: false, value: foobarString},214 ],215 );216214 const readerPromises = iterators.map(iterator => t.throwsAsync(iterator.next(), {message: /Pipe canceled/}));217 const readerPromises = iterators.map(iterator => assertRejects(iterator.next(), {message: /Pipe canceled/}));218 abortController.abort();216 await Promise.all(readerPromises.map(async readerPromise => assertSettles(t, readerPromise)));219 await Promise.all(readerPromises.map(async readerPromise => assertSettles(readerPromise)));220});221222const assertCanceledPipeMessageReader = async (t, getReader, shouldAbortBeforePipe = false) => {223 const abortController = new AbortController();
2 unmodified lines
226 }227228 const source = execa('noop-repeat.js');229 const destination = execa('ipc-get.js', {ipc: true});227 t.teardown(async () => {230 t.after(async () => {231 await cleanupSubprocesses(source, destination);232 });233234 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});232 const readerPromise = t.throwsAsync(getReader(piped), {message: /Pipe canceled/});235 const readerPromise = assertRejects(getReader(piped), {message: /Pipe canceled/});236237 if (!shouldAbortBeforePipe) {238 abortController.abort();239 }240238 await assertSettles(t, readerPromise);239 await t.throwsAsync(piped, {message: /Pipe canceled/});241 await assertSettles(readerPromise);242 await assertRejects(piped, {message: /Pipe canceled/});243};244245test('The .pipe() return value .getEachMessage() waits for pipe cancellation before IPC messages', async t => {246 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next());
13 unmodified lines
260261test('The .pipe() return value .getEachMessage() waits for the pipe when the iterator is returned', async t => {262 const source = execa('empty.js');263 const destination = execa('ipc-send-forever.js', {ipc: true});261 t.teardown(async () => {264 t.after(async () => {265 await cleanupSubprocesses(source, destination);266 });267268 const piped = source.pipe(destination);269 const iterator = piped.getEachMessage();270268 t.deepEqual(await iterator.next(), {done: false, value: foobarString});269 const returnPromise = t.throwsAsync(iterator.return());271 assert.deepEqual(await iterator.next(), {done: false, value: foobarString});272 const returnPromise = assertRejects(iterator.return());273 destination.kill();274 const error = await returnPromise;272 t.true(error.isTerminated);275 assert.equal(error.isTerminated, true);276 await Promise.allSettled([source, destination, piped]);277});278276test('The .pipe() return value .getEachMessage() propagates source failure when the iterator is returned', async t => {279test('The .pipe() return value .getEachMessage() propagates source failure when the iterator is returned', async () => {280 const source = execa('ipc-echo-fail.js', {ipc: true});281 const piped = source.pipe('ipc-send-wait-print.js', {ipc: true});282 const iterator = piped.getEachMessage();283281 t.deepEqual(await iterator.next(), {done: false, value: foobarString});282 const returnPromise = t.throwsAsync(iterator.return(), {message: /Command failed with exit code 1/});284 assert.deepEqual(await iterator.next(), {done: false, value: foobarString});285 const returnPromise = assertRejects(iterator.return(), {message: /Command failed with exit code 1/});286 await source.sendMessage(foobarString);287 await returnPromise;288});289287test('The .pipe() return value .getEachMessage() propagates destination failure', async t => {290test('The .pipe() return value .getEachMessage() propagates destination failure', async () => {291 const piped = execa('empty.js').pipe('ipc-send-fail.js', {ipc: true});292290 await t.throwsAsync(async () => {293 await assertRejects(async () => {294 for await (const message of piped.getEachMessage()) {292 t.is(message, foobarString);295 assert.equal(message, foobarString);296 }297 }, {message: /Command failed with exit code 1/});298296 const {ipcOutput} = await t.throwsAsync(piped);297 t.deepEqual(ipcOutput, [foobarString]);299 const {ipcOutput} = await assertRejects(piped);300 assert.deepEqual(ipcOutput, [foobarString]);301});302300test('The .pipe() return value .getEachMessage() waits for the pipe when the consumer throws', async t => {303test('The .pipe() return value .getEachMessage() waits for the pipe when the consumer throws', async () => {304 const piped = execa('empty.js').pipe('ipc-send-wait-print.js', {ipc: true});305 const cause = new Error(foobarString);306304 t.is(await t.throwsAsync(async () => {307 assert.equal(await assertRejects(async () => {308 // eslint-disable-next-line no-unreachable-loop309 for await (const message of piped.getEachMessage()) {307 t.is(message, foobarString);310 assert.equal(message, foobarString);311 throw cause;312 }313 }), cause);314315 const {ipcOutput, stdout} = await piped;313 t.deepEqual(ipcOutput, [foobarString]);314 t.is(stdout, '.');316 assert.deepEqual(ipcOutput, [foobarString]);317 assert.equal(stdout, '.');318});319320test('The .pipe() return value .getEachMessage() validates IPC immediately', async t => {321 const source = execa('stdin.js');322 const destination = execa('stdin.js');320 t.teardown(async () => {323 t.after(async () => {324 await cleanupSubprocesses(source, destination);325 });326327 const piped = source.pipe(destination);325 const {message} = t.throws(() => piped.getEachMessage());328 const {message} = assertThrows(() => piped.getEachMessage());329327 t.true(message.includes('subprocess.getEachMessage() can only be used'));330 assert.ok(message.includes('subprocess.getEachMessage() can only be used'));331 source.kill();332 destination.kill();333 await Promise.allSettled([source, destination, piped]);334});335333test('The .pipe() return value can exchange IPC messages', async t => {336test('The .pipe() return value can exchange IPC messages', async () => {337 const piped = execa('empty.js').pipe('ipc-echo.js', {ipc: true});338 await piped.sendMessage(foobarString);336 t.is(await piped.getOneMessage(), foobarString);339 assert.equal(await piped.getOneMessage(), foobarString);340 await piped;341});342340test('A chained .pipe() return value can be iterated', async t => {343test('A chained .pipe() return value can be iterated', async () => {344 const lines = await Array.fromAsync(execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js').pipe('stdin.js'));345343 t.deepEqual(lines, noNewlinesChunks);346 assert.deepEqual(lines, noNewlinesChunks);347});348346test('The .pipe() return value still awaits both subprocesses', async t => {347 await t.throwsAsync(execa('fail.js').pipe('stdin.js'), {message: /Command failed with exit code 2/});349test('The .pipe() return value still awaits both subprocesses', async () => {350 await assertRejects(execa('fail.js').pipe('stdin.js'), {message: /Command failed with exit code 2/});351});352350test('The .pipe() return value iteration waits for source failure', async t => {353test('The .pipe() return value iteration waits for source failure', async () => {354 const piped = execa('fail.js').pipe('stdin.js');355353 await t.throwsAsync(async () => {356 await assertRejects(async () => {357 for await (const line of piped) {355 t.fail(`Unexpected line: ${line}`);358 assert.fail(`Unexpected line: ${line}`);359 }360 }, {message: /Command failed with exit code 2/});361});362360test('The .pipe() return value .readable() waits for source failure', async t => {363test('The .pipe() return value .readable() waits for source failure', async () => {364 const piped = execa('fail.js').pipe('stdin.js');365363 await t.throwsAsync(text(piped.readable()), {message: /Command failed with exit code 2/});366 await assertRejects(text(piped.readable()), {message: /Command failed with exit code 2/});367});368366test('The .pipe() return value .readableStream() waits for source failure', async t => {369test('The .pipe() return value .readableStream() waits for source failure', async () => {370 const piped = execa('fail.js').pipe('stdin.js');371369 await t.throwsAsync(text(piped.readableStream()), {message: /Command failed with exit code 2/});372 await assertRejects(text(piped.readableStream()), {message: /Command failed with exit code 2/});373});374372test('The .pipe() return value .all waits for source failure', async t => {375test('The .pipe() return value .all waits for source failure', async () => {376 const piped = execa('fail.js').pipe('stdin.js', {all: true});377375 await t.throwsAsync(text(piped.all), {message: /Command failed with exit code 2/});378 await assertRejects(text(piped.all), {message: /Command failed with exit code 2/});379});380381const assertCanceledPipeReader = async (t, getReader, shouldAbortBeforePipe = false) => {382 const abortController = new AbortController();
2 unmodified lines
385 }386387 const source = execa('stdin.js');388 const destination = execa('stdin.js', {all: true});386 t.teardown(async () => {389 t.after(async () => {390 await cleanupSubprocesses(source, destination);391 });392393 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});391 const readerPromise = t.throwsAsync(getReader(piped), {message: /Pipe canceled/});394 const readerPromise = assertRejects(getReader(piped), {message: /Pipe canceled/});395396 if (!shouldAbortBeforePipe) {397 abortController.abort();398 }399397 await assertSettles(t, readerPromise, 200);400 await assertSettles(readerPromise, 200);401};402403test('The .pipe() return value .readable() waits for pipe cancellation', async t => {404 await assertCanceledPipeReader(t, piped => text(piped.readable()));
10 unmodified lines
415test('The .pipe() return value .all waits for already canceled pipes', async t => {416 await assertCanceledPipeReader(t, piped => text(piped.all), true);417});418416test('Multiple sources piped to one destination each expose the destination methods', async t => {419test('Multiple sources piped to one destination each expose the destination methods', async () => {420 const destination = execa('stdin.js');421 const piped = [422 execa('noop-fd.js', ['1', foobarString]).pipe(destination),423 execa('noop-fd.js', ['1', foobarString]).pipe(destination),424 ];425426 for (const pipePromise of piped) {424 t.is(typeof pipePromise.iterable, 'function');425 t.is(typeof pipePromise[Symbol.asyncIterator], 'function');427 assert.equal(typeof pipePromise.iterable, 'function');428 assert.equal(typeof pipePromise[Symbol.asyncIterator], 'function');429 }430431 await Promise.all(piped);432});433434/* eslint-enable node-test/no-conditional-assertion */
modified:test/pipe/pipe-arguments.js+99 added-97 removed
1import assert from 'node:assert/strict';2import {spawn} from 'node:child_process';3import {pathToFileURL} from 'node:url';3import test from 'ava';4import test from 'node:test';5import {assertRejects} from '../helpers/assert.js';6import {$, execa} from '../../index.js';7import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';8import {foobarString} from '../helpers/input.js';9import {getDenoNodePath} from '../helpers/file-path.js';1011setFixtureDirectory();1211test('$.pipe(subprocess)', async t => {13test('$.pipe(subprocess)', async () => {14 const {stdout} = await $`noop.js ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`);13 t.is(stdout, foobarString);15 assert.equal(stdout, foobarString);16});1716test('execa.$.pipe(subprocess)', async t => {18test('execa.$.pipe(subprocess)', async () => {19 const {stdout} = await execa('noop.js', [foobarString]).pipe($({stdin: 'pipe'})`stdin.js`);18 t.is(stdout, foobarString);20 assert.equal(stdout, foobarString);21});2221test('$.pipe.pipe(subprocess)', async t => {23test('$.pipe.pipe(subprocess)', async () => {24 const {stdout} = await $`noop.js ${foobarString}`25 .pipe($({stdin: 'pipe'})`stdin.js`)26 .pipe($({stdin: 'pipe'})`stdin.js`);25 t.is(stdout, foobarString);27 assert.equal(stdout, foobarString);28});2928test('$.pipe`command`', async t => {30test('$.pipe`command`', async () => {31 const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;30 t.is(stdout, foobarString);32 assert.equal(stdout, foobarString);33});3433test('execa.$.pipe`command`', async t => {35test('execa.$.pipe`command`', async () => {36 const {stdout} = await execa('noop.js', [foobarString]).pipe`stdin.js`;35 t.is(stdout, foobarString);37 assert.equal(stdout, foobarString);38});3938test('$.pipe.pipe`command`', async t => {40test('$.pipe.pipe`command`', async () => {41 const {stdout} = await $`noop.js ${foobarString}`42 .pipe`stdin.js`43 .pipe`stdin.js`;42 t.is(stdout, foobarString);44 assert.equal(stdout, foobarString);45});4645test('$.pipe("file")', async t => {47test('$.pipe("file")', async () => {48 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js');47 t.is(stdout, foobarString);49 assert.equal(stdout, foobarString);50});5150test('execa.$.pipe("file")`', async t => {52test('execa.$.pipe("file")`', async () => {53 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js');52 t.is(stdout, foobarString);54 assert.equal(stdout, foobarString);55});5655test('$.pipe.pipe("file")', async t => {57test('$.pipe.pipe("file")', async () => {58 const {stdout} = await $`noop.js ${foobarString}`59 .pipe`stdin.js`60 .pipe('stdin.js');59 t.is(stdout, foobarString);61 assert.equal(stdout, foobarString);62});6362test('execa.$.pipe(fileUrl)`', async t => {64test('execa.$.pipe(fileUrl)`', async () => {65 const {stdout} = await execa('noop.js', [foobarString]).pipe(pathToFileURL(`${FIXTURES_DIRECTORY}/stdin.js`));64 t.is(stdout, foobarString);66 assert.equal(stdout, foobarString);67});6867test('$.pipe("file", commandArguments, options)', async t => {69test('$.pipe("file", commandArguments, options)', async () => {70 const {stdout} = await $`noop.js ${foobarString}`.pipe('node', ['stdin.js'], {cwd: FIXTURES_DIRECTORY});69 t.is(stdout, foobarString);71 assert.equal(stdout, foobarString);72});7372test('execa.$.pipe("file", commandArguments, options)`', async t => {74test('execa.$.pipe("file", commandArguments, options)`', async () => {75 const {stdout} = await execa('noop.js', [foobarString]).pipe('node', ['stdin.js'], {cwd: FIXTURES_DIRECTORY});74 t.is(stdout, foobarString);76 assert.equal(stdout, foobarString);77});7877test('execa.$.pipe("file", commandArguments, options with denoNodePath)`', async t => {79test('execa.$.pipe("file", commandArguments, options with denoNodePath)`', async () => {80 const {stdout} = await execa('noop.js', [foobarString]).pipe('node', ['stdin.js'], {cwd: FIXTURES_DIRECTORY, nodePath: getDenoNodePath()});79 t.is(stdout, foobarString);81 assert.equal(stdout, foobarString);82});8382test('execa.$.pipe("file", commandArguments, denoNodePath)`', async t => {84test('execa.$.pipe("file", commandArguments, denoNodePath)`', async () => {85 const {stdout} = await execa('noop.js', [foobarString]).pipe(getDenoNodePath(), ['stdin.js'], {cwd: FIXTURES_DIRECTORY});84 t.is(stdout, foobarString);86 assert.equal(stdout, foobarString);87});8887test('$.pipe.pipe("file", commandArguments, options)', async t => {89test('$.pipe.pipe("file", commandArguments, options)', async () => {90 const {stdout} = await $`noop.js ${foobarString}`91 .pipe`stdin.js`92 .pipe('node', ['stdin.js'], {cwd: FIXTURES_DIRECTORY});91 t.is(stdout, foobarString);93 assert.equal(stdout, foobarString);94});9594test('$.pipe(subprocess, pipeOptions)', async t => {96test('$.pipe(subprocess, pipeOptions)', async () => {97 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});96 t.is(stdout, foobarString);98 assert.equal(stdout, foobarString);99});10099test('execa.$.pipe(subprocess, pipeOptions)', async t => {101test('execa.$.pipe(subprocess, pipeOptions)', async () => {102 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});101 t.is(stdout, foobarString);103 assert.equal(stdout, foobarString);104});105104test('$.pipe.pipe(subprocess, pipeOptions)', async t => {106test('$.pipe.pipe(subprocess, pipeOptions)', async () => {107 const {stdout} = await $`noop-fd.js 2 ${foobarString}`108 .pipe($({stdin: 'pipe'})`noop-stdin-fd.js 2`, {from: 'stderr'})109 .pipe($({stdin: 'pipe'})`stdin.js`, {from: 'stderr'});108 t.is(stdout, foobarString);110 assert.equal(stdout, foobarString);111});112111test('$.pipe(pipeOptions)`command`', async t => {113test('$.pipe(pipeOptions)`command`', async () => {114 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe({from: 'stderr'})`stdin.js`;113 t.is(stdout, foobarString);115 assert.equal(stdout, foobarString);116});117116test('execa.$.pipe(pipeOptions)`command`', async t => {118test('execa.$.pipe(pipeOptions)`command`', async () => {119 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe({from: 'stderr'})`stdin.js`;118 t.is(stdout, foobarString);120 assert.equal(stdout, foobarString);121});122121test('$.pipe.pipe(pipeOptions)`command`', async t => {123test('$.pipe.pipe(pipeOptions)`command`', async () => {124 const {stdout} = await $`noop-fd.js 2 ${foobarString}`125 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`126 .pipe({from: 'stderr'})`stdin.js`;125 t.is(stdout, foobarString);127 assert.equal(stdout, foobarString);128});129128test('$.pipe("file", pipeOptions)', async t => {130test('$.pipe("file", pipeOptions)', async () => {131 const {stdout} = await $`noop-fd.js 2 ${foobarString}`.pipe('stdin.js', {from: 'stderr'});130 t.is(stdout, foobarString);132 assert.equal(stdout, foobarString);133});134133test('execa.$.pipe("file", pipeOptions)', async t => {135test('execa.$.pipe("file", pipeOptions)', async () => {136 const {stdout} = await execa('noop-fd.js', ['2', foobarString]).pipe('stdin.js', {from: 'stderr'});135 t.is(stdout, foobarString);137 assert.equal(stdout, foobarString);138});139138test('$.pipe.pipe("file", pipeOptions)', async t => {140test('$.pipe.pipe("file", pipeOptions)', async () => {141 const {stdout} = await $`noop-fd.js 2 ${foobarString}`142 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`143 .pipe('stdin.js', {from: 'stderr'});142 t.is(stdout, foobarString);144 assert.equal(stdout, foobarString);145});146145test('$.pipe(options)`command`', async t => {147test('$.pipe(options)`command`', async () => {148 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})`stdin.js`;147 t.is(stdout, `${foobarString}\n`);149 assert.equal(stdout, `${foobarString}\n`);150});151150test('execa.$.pipe(options)`command`', async t => {152test('execa.$.pipe(options)`command`', async () => {153 const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})`stdin.js`;152 t.is(stdout, `${foobarString}\n`);154 assert.equal(stdout, `${foobarString}\n`);155});156155test('$.pipe.pipe(options)`command`', async t => {157test('$.pipe.pipe(options)`command`', async () => {158 const {stdout} = await $`noop.js ${foobarString}`159 .pipe({})`stdin.js`160 .pipe({stripFinalNewline: false})`stdin.js`;159 t.is(stdout, `${foobarString}\n`);161 assert.equal(stdout, `${foobarString}\n`);162});163162test('$.pipe("file", options)', async t => {164test('$.pipe("file", options)', async () => {165 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js', {stripFinalNewline: false});164 t.is(stdout, `${foobarString}\n`);166 assert.equal(stdout, `${foobarString}\n`);167});168167test('execa.$.pipe("file", options)', async t => {169test('execa.$.pipe("file", options)', async () => {170 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stripFinalNewline: false});169 t.is(stdout, `${foobarString}\n`);171 assert.equal(stdout, `${foobarString}\n`);172});173172test('$.pipe.pipe("file", options)', async t => {174test('$.pipe.pipe("file", options)', async () => {175 const {stdout} = await $`noop.js ${foobarString}`176 .pipe({})`stdin.js`177 .pipe('stdin.js', {stripFinalNewline: false});176 t.is(stdout, `${foobarString}\n`);178 assert.equal(stdout, `${foobarString}\n`);179});180179test('$.pipe(pipeAndSubprocessOptions)`command`', async t => {181test('$.pipe(pipeAndSubprocessOptions)`command`', async () => {182 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;181 t.is(stdout, `${foobarString}\n`);183 assert.equal(stdout, `${foobarString}\n`);184});185184test('execa.$.pipe(pipeAndSubprocessOptions)`command`', async t => {186test('execa.$.pipe(pipeAndSubprocessOptions)`command`', async () => {187 const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;186 t.is(stdout, `${foobarString}\n`);188 assert.equal(stdout, `${foobarString}\n`);189});190189test('$.pipe.pipe(pipeAndSubprocessOptions)`command`', async t => {191test('$.pipe.pipe(pipeAndSubprocessOptions)`command`', async () => {192 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`193 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`194 .pipe({from: 'stderr', stripFinalNewline: false})`stdin.js`;193 t.is(stdout, `${foobarString}\n`);195 assert.equal(stdout, `${foobarString}\n`);196});197196test('$.pipe("file", pipeAndSubprocessOptions)', async t => {198test('$.pipe("file", pipeAndSubprocessOptions)', async () => {199 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`.pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});198 t.is(stdout, `${foobarString}\n`);200 assert.equal(stdout, `${foobarString}\n`);201});202201test('execa.$.pipe("file", pipeAndSubprocessOptions)', async t => {203test('execa.$.pipe("file", pipeAndSubprocessOptions)', async () => {204 const {stdout} = await execa('noop-fd.js', ['2', `${foobarString}\n`]).pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});203 t.is(stdout, `${foobarString}\n`);205 assert.equal(stdout, `${foobarString}\n`);206});207206test('$.pipe.pipe("file", pipeAndSubprocessOptions)', async t => {208test('$.pipe.pipe("file", pipeAndSubprocessOptions)', async () => {209 const {stdout} = await $`noop-fd.js 2 ${foobarString}\n`210 .pipe({from: 'stderr'})`noop-stdin-fd.js 2`211 .pipe('stdin.js', {from: 'stderr', stripFinalNewline: false});210 t.is(stdout, `${foobarString}\n`);212 assert.equal(stdout, `${foobarString}\n`);213});214213test('$.pipe(options)(secondOptions)`command`', async t => {215test('$.pipe(options)(secondOptions)`command`', async () => {216 const {stdout} = await $`noop.js ${foobarString}`.pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;215 t.is(stdout, foobarString);217 assert.equal(stdout, foobarString);218});219218test('execa.$.pipe(options)(secondOptions)`command`', async t => {220test('execa.$.pipe(options)(secondOptions)`command`', async () => {221 const {stdout} = await execa('noop.js', [foobarString]).pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;220 t.is(stdout, foobarString);222 assert.equal(stdout, foobarString);223});224223test('$.pipe.pipe(options)(secondOptions)`command`', async t => {225test('$.pipe.pipe(options)(secondOptions)`command`', async () => {226 const {stdout} = await $`noop.js ${foobarString}`227 .pipe({})({})`stdin.js`228 .pipe({stripFinalNewline: false})({stripFinalNewline: true})`stdin.js`;227 t.is(stdout, foobarString);229 assert.equal(stdout, foobarString);230});231230test('$.pipe`command` forces "stdin: pipe"', async t => {232test('$.pipe`command` forces "stdin: pipe"', async () => {233 const {stdout} = await $`noop.js ${foobarString}`.pipe({stdin: 'ignore'})`stdin.js`;232 t.is(stdout, foobarString);234 assert.equal(stdout, foobarString);235});236235test('execa.pipe("file") forces "stdin: "pipe"', async t => {237test('execa.pipe("file") forces "stdin: "pipe"', async () => {238 const {stdout} = await execa('noop.js', [foobarString]).pipe('stdin.js', {stdin: 'ignore'});237 t.is(stdout, foobarString);239 assert.equal(stdout, foobarString);240});241240test('execa.pipe(subprocess) does not force "stdin: pipe"', async t => {241 await t.throwsAsync(242test('execa.pipe(subprocess) does not force "stdin: pipe"', async () => {243 await assertRejects(244 execa('noop.js', [foobarString]).pipe(execa('stdin.js', {stdin: 'ignore'})),245 {message: /"stdin: 'ignore'" option is incompatible/},246 );247});248247test('$.pipe(options)(subprocess) fails', async t => {248 await t.throwsAsync(249test('$.pipe(options)(subprocess) fails', async () => {250 await assertRejects(251 $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`),252 {message: /Please use \.pipe/},253 );254});255254test('execa.$.pipe(options)(subprocess) fails', async t => {255 await t.throwsAsync(256test('execa.$.pipe(options)(subprocess) fails', async () => {257 await assertRejects(258 execa('empty.js').pipe({stdout: 'pipe'})($`empty.js`),259 {message: /Please use \.pipe/},260 );261});262261test('$.pipe(options)("file") fails', async t => {262 await t.throwsAsync(263test('$.pipe(options)("file") fails', async () => {264 await assertRejects(265 $`empty.js`.pipe({stdout: 'pipe'})('empty.js'),266 {message: /Please use \.pipe/},267 );268});269268test('execa.$.pipe(options)("file") fails', async t => {269 await t.throwsAsync(270test('execa.$.pipe(options)("file") fails', async () => {271 await assertRejects(272 execa('empty.js').pipe({stdout: 'pipe'})('empty.js'),273 {message: /Please use \.pipe/},274 );275});276275const testInvalidPipe = async (t, ...pipeArguments) => {276 await t.throwsAsync(277const testInvalidPipe = async (...pipeArguments) => {278 await assertRejects(279 $`empty.js`.pipe(...pipeArguments),280 {message: /must be a template string/},281 );282};283282test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));283test('$.pipe(false) fails', testInvalidPipe, false);284test('$.pipe(nonExecaSubprocess) fails', () => testInvalidPipe(spawn('node', ['--version'])));285test('$.pipe(false) fails', () => testInvalidPipe(false));
modified:test/pipe/sequence.js+162 added-143 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import process from 'node:process';4import {PassThrough} from 'node:stream';5import {setTimeout} from 'node:timers/promises';5import test from 'ava';6import test from 'node:test';7import {assertRejects, assertLike} from '../helpers/assert.js';8import {execa} from '../../index.js';9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10import {foobarString} from '../helpers/input.js';11import {noopGenerator} from '../helpers/generator.js';
3 unmodified lines
1516const isLinux = process.platform === 'linux';17const timeoutSymbol = Symbol('timeout');1817const assertUnhandledRejection = async (t, pipePromise, unhandledRejectionPromise) => {19// The `unhandledRejection` event is what these tests assert on, but `node:test` also listens to it20// and fails any test during which it fires. That listener is removed while the event is observed,21// since the event itself is what `assertUnhandledRejection()` asserts on.22const observeUnhandledRejection = async () => {23 const testRunnerListeners = process.listeners('unhandledRejection');24 for (const listener of testRunnerListeners) {25 process.removeListener('unhandledRejection', listener);26 }2728 try {29 return await once(process, 'unhandledRejection');30 } finally {31 for (const listener of testRunnerListeners) {32 process.on('unhandledRejection', listener);33 }34 }35};3637const assertUnhandledRejection = async pipePromise => {38 const result = await Promise.race([19 unhandledRejectionPromise,20 setTimeout(500, timeoutSymbol),39 observeUnhandledRejection(),40 setTimeout(5000, timeoutSymbol),41 ]);4223 t.not(result, timeoutSymbol);43 assert.notEqual(result, timeoutSymbol);4445 if (result === timeoutSymbol) {46 return;47 }4849 const [reason, unhandledPromise] = result;30 t.is(unhandledPromise, pipePromise);31 t.regex(reason.message, /Command failed with exit code 2/);50 assert.equal(unhandledPromise, pipePromise);51 assert.match(reason.message, /Command failed with exit code 2/);52};5334const assertUnhandledPipePromise = async (t, {destinationOptions = {}, inspectPipePromise} = {}) => {54const assertUnhandledPipePromise = async ({destinationOptions = {}, inspectPipePromise} = {}) => {55 const source = execa('fail.js');56 const destination = execa('fail.js', destinationOptions);57 const pipePromise = source.pipe(destination);38 const unhandledRejectionPromise = once(process, 'unhandledRejection');58 await inspectPipePromise?.(pipePromise);40 await assertUnhandledRejection(t, pipePromise, unhandledRejectionPromise);59 await assertUnhandledRejection(pipePromise);60 await Promise.all([42 t.throwsAsync(source),43 t.throwsAsync(destination),61 assertRejects(source),62 assertRejects(destination),63 ]);45 await t.throwsAsync(pipePromise);64 await assertRejects(pipePromise);65};6648test('Source stream abort -> destination success', async t => {67test('Source stream abort -> destination success', async () => {68 const source = execa('noop-repeat.js');69 const destination = execa('stdin.js');70 const pipePromise = source.pipe(destination);71 source.stdout.destroy();7254 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));55 t.like(await t.throwsAsync(source), {exitCode: 1});73 assert.equal(await assertRejects(pipePromise), await assertRejects(source));74 assertLike(await assertRejects(source), {exitCode: 1});75 await destination;76});7759test('Source stream error -> destination success', async t => {78test('Source stream error -> destination success', async () => {79 const source = execa('noop-repeat.js');80 const destination = execa('stdin.js');81 const pipePromise = source.pipe(destination);82 const cause = new Error('test');83 source.stdout.destroy(cause);8466 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));67 t.like(await t.throwsAsync(source), {originalMessage: cause.message, exitCode: 1});85 assert.equal(await assertRejects(pipePromise), await assertRejects(source));86 assertLike(await assertRejects(source), {originalMessage: cause.message, exitCode: 1});87 await destination;88});8971test('Destination stream abort -> source failure', async t => {90test('Destination stream abort -> source failure', async () => {91 const source = execa('noop-repeat.js');92 const destination = execa('stdin.js');93 const pipePromise = source.pipe(destination);94 destination.stdin.destroy();9577 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));78 t.like(await t.throwsAsync(destination), prematureClose);79 t.like(await t.throwsAsync(source), {exitCode: 1});96 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));97 assertLike(await assertRejects(destination), prematureClose);98 assertLike(await assertRejects(source), {exitCode: 1});99});10082test('Destination stream error -> source failure', async t => {101test('Destination stream error -> source failure', async () => {102 const source = execa('noop-repeat.js');103 const destination = execa('stdin.js');104 const pipePromise = source.pipe(destination);105 const cause = new Error('test');106 destination.stdin.destroy(cause);10789 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));90 t.like(await t.throwsAsync(destination), {originalMessage: cause.message, exitCode: 0});91 t.like(await t.throwsAsync(source), {exitCode: 1});108 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));109 assertLike(await assertRejects(destination), {originalMessage: cause.message, exitCode: 0});110 assertLike(await assertRejects(source), {exitCode: 1});111});11294test('Source success -> destination success', async t => {113test('Source success -> destination success', async () => {114 const source = execa('noop.js', [foobarString]);115 const destination = execa('stdin.js');116 const pipePromise = source.pipe(destination);11799 t.like(await source, {stdout: foobarString});100 t.like(await destination, {stdout: foobarString});101 t.is(await pipePromise, await destination);118 assertLike(await source, {stdout: foobarString});119 assertLike(await destination, {stdout: foobarString});120 assert.equal(await pipePromise, await destination);121});122104test('Destination stream end -> source failure', async t => {123test('Destination stream end -> source failure', async () => {124 const source = execa('noop-repeat.js');125 const destination = execa('stdin.js');126 const pipePromise = source.pipe(destination);127 destination.stdin.end();128110 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));129 assert.equal(await assertRejects(pipePromise), await assertRejects(source));130 await destination;112 t.like(await t.throwsAsync(source), {exitCode: 1});131 assertLike(await assertRejects(source), {exitCode: 1});132});133115test('Source normal failure -> destination success', async t => {134test('Source normal failure -> destination success', async () => {135 const source = execa('noop-fail.js', ['1', foobarString]);136 const destination = execa('stdin.js');137 const pipePromise = source.pipe(destination);138120 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));121 t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});139 assert.equal(await assertRejects(pipePromise), await assertRejects(source));140 assertLike(await assertRejects(source), {stdout: foobarString, exitCode: 2});141 await destination;142});143125test('Source normal failure -> deep destination success', async t => {144test('Source normal failure -> deep destination success', async () => {145 const source = execa('noop-fail.js', ['1', foobarString]);146 const destination = execa('stdin.js');147 const secondDestination = execa('stdin.js');148 const pipePromise = source.pipe(destination);149 const secondPipePromise = pipePromise.pipe(secondDestination);150132 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));133 t.is(await t.throwsAsync(secondPipePromise), await t.throwsAsync(source));134 t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});135 t.like(await destination, {stdout: foobarString});136 t.like(await secondDestination, {stdout: foobarString});151 assert.equal(await assertRejects(pipePromise), await assertRejects(source));152 assert.equal(await assertRejects(secondPipePromise), await assertRejects(source));153 assertLike(await assertRejects(source), {stdout: foobarString, exitCode: 2});154 assertLike(await destination, {stdout: foobarString});155 assertLike(await secondDestination, {stdout: foobarString});156});157139const testSourceTerminated = async (t, signal) => {158const testSourceTerminated = async signal => {159 const source = execa('noop-repeat.js');160 const destination = execa('stdin.js');161 const pipePromise = source.pipe(destination);162 source.kill(signal);163145 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));146 t.like(await t.throwsAsync(source), {signal});164 assert.equal(await assertRejects(pipePromise), await assertRejects(source));165 assertLike(await assertRejects(source), {signal});166 await destination;167};168150test('Source SIGTERM -> destination success', testSourceTerminated, 'SIGTERM');151test('Source SIGKILL -> destination success', testSourceTerminated, 'SIGKILL');169test('Source SIGTERM -> destination success', () => testSourceTerminated('SIGTERM'));170test('Source SIGKILL -> destination success', () => testSourceTerminated('SIGKILL'));171153test('Destination success before source -> source success', async t => {172test('Destination success before source -> source success', async () => {173 const passThroughStream = new PassThrough();174 const source = execa('stdin.js', {stdin: ['pipe', passThroughStream]});175 const destination = execa('empty.js');176 const pipePromise = source.pipe(destination);177178 await destination;179 passThroughStream.end();180 await source;162 t.is(await pipePromise, await destination);181 assert.equal(await pipePromise, await destination);182});183165test('Destination normal failure -> source failure', async t => {184test('Destination normal failure -> source failure', async () => {185 const source = execa('noop-repeat.js');186 const destination = execa('fail.js');187 const pipePromise = source.pipe(destination);188170 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));171 t.like(await t.throwsAsync(destination), {exitCode: 2});172 t.like(await t.throwsAsync(source), {exitCode: 1});189 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));190 assertLike(await assertRejects(destination), {exitCode: 2});191 assertLike(await assertRejects(source), {exitCode: 1});192});193175test('Destination normal failure -> deep source failure', async t => {194test('Destination normal failure -> deep source failure', async () => {195 const source = execa('noop-repeat.js');196 const destination = execa('stdin.js');197 const secondDestination = execa('fail.js');198 const pipePromise = source.pipe(destination);199 const secondPipePromise = pipePromise.pipe(secondDestination);200182 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));183 t.is(await t.throwsAsync(secondPipePromise), await t.throwsAsync(secondDestination));184 t.like(await t.throwsAsync(secondDestination), {exitCode: 2});185 t.like(await t.throwsAsync(destination), {exitCode: 1});186 t.like(await t.throwsAsync(source), {exitCode: 1});201 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));202 assert.equal(await assertRejects(secondPipePromise), await assertRejects(secondDestination));203 assertLike(await assertRejects(secondDestination), {exitCode: 2});204 assertLike(await assertRejects(destination), {exitCode: 1});205 assertLike(await assertRejects(source), {exitCode: 1});206});207189const testDestinationTerminated = async (t, signal) => {208const testDestinationTerminated = async signal => {209 const source = execa('noop-repeat.js');210 const destination = execa('stdin.js');211 const pipePromise = source.pipe(destination);212 destination.kill(signal);213195 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));196 t.like(await t.throwsAsync(destination), {signal});197 t.like(await t.throwsAsync(source), {exitCode: 1});214 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));215 assertLike(await assertRejects(destination), {signal});216 assertLike(await assertRejects(source), {exitCode: 1});217};218200test('Destination SIGTERM -> source abort', testDestinationTerminated, 'SIGTERM');201test('Destination SIGKILL -> source abort', testDestinationTerminated, 'SIGKILL');219test('Destination SIGTERM -> source abort', () => testDestinationTerminated('SIGTERM'));220test('Destination SIGKILL -> source abort', () => testDestinationTerminated('SIGKILL'));221203test('Source already ended -> ignore source', async t => {222test('Source already ended -> ignore source', async () => {223 const source = execa('noop.js', [foobarString]);224 await source;225 const destination = execa('stdin.js');226 const pipePromise = source.pipe(destination);227209 t.is(await pipePromise, await destination);210 t.like(await source, {stdout: foobarString});211 t.like(await destination, {stdout: ''});228 assert.equal(await pipePromise, await destination);229 assertLike(await source, {stdout: foobarString});230 assertLike(await destination, {stdout: ''});231});232214test('Source already aborted -> ignore source', async t => {233test('Source already aborted -> ignore source', async () => {234 const source = execa('noop.js', [foobarString]);235 source.stdout.destroy();236 const destination = execa('stdin.js');237 const pipePromise = source.pipe(destination);238220 t.is(await pipePromise, await destination);221 t.like(await source, {stdout: ''});222 t.like(await destination, {stdout: ''});239 assert.equal(await pipePromise, await destination);240 assertLike(await source, {stdout: ''});241 assertLike(await destination, {stdout: ''});242});243225test('Source already errored -> failure', async t => {244test('Source already errored -> failure', async () => {245 const source = execa('noop.js', [foobarString]);246 const cause = new Error('test');247 source.stdout.destroy(cause);248 const destination = execa('stdin.js');249 const pipePromise = source.pipe(destination);250232 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));233 t.like(await t.throwsAsync(source), {cause});234 t.like(await destination, {stdout: ''});251 assert.equal(await assertRejects(pipePromise), await assertRejects(source));252 assertLike(await assertRejects(source), {cause});253 assertLike(await destination, {stdout: ''});254});255237test('Destination already ended -> ignore source', async t => {256test('Destination already ended -> ignore source', async () => {257 const destination = execa('stdin.js');258 destination.stdin.end('.');259 await destination;260 const source = execa('noop.js', [foobarString]);261 const pipePromise = source.pipe(destination);262244 t.is(await pipePromise, await destination);245 t.like(await destination, {stdout: '.'});246 t.like(await source, {stdout: ''});263 assert.equal(await pipePromise, await destination);264 assertLike(await destination, {stdout: '.'});265 assertLike(await source, {stdout: ''});266});267249test('Destination already aborted -> failure', async t => {268test('Destination already aborted -> failure', async () => {269 const destination = execa('stdin.js');270 destination.stdin.destroy();252 t.like(await t.throwsAsync(destination), prematureClose);271 assertLike(await assertRejects(destination), prematureClose);272 const source = execa('noop.js', [foobarString]);273 const pipePromise = source.pipe(destination);274256 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));257 t.like(await source, {stdout: ''});275 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));276 assertLike(await source, {stdout: ''});277});278260test('Destination already errored -> failure', async t => {279test('Destination already errored -> failure', async () => {280 const destination = execa('stdin.js');281 const cause = new Error('test');282 destination.stdin.destroy(cause);264 t.like(await t.throwsAsync(destination), {cause});283 assertLike(await assertRejects(destination), {cause});284 const source = execa('noop.js', [foobarString]);285 const pipePromise = source.pipe(destination);286268 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));269 t.like(await source, {stdout: ''});287 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));288 assertLike(await source, {stdout: ''});289});290272test('Source normal failure + destination normal failure', async t => {291test('Source normal failure + destination normal failure', async () => {292 const source = execa('noop-fail.js', ['1', foobarString]);293 const destination = execa('stdin-fail.js');294 const pipePromise = source.pipe(destination);295277 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));278 t.like(await t.throwsAsync(source), {stdout: foobarString, exitCode: 2});279 t.like(await t.throwsAsync(destination), {stdout: foobarString, exitCode: 2});296 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));297 assertLike(await assertRejects(source), {stdout: foobarString, exitCode: 2});298 assertLike(await assertRejects(destination), {stdout: foobarString, exitCode: 2});299});300282test('Simultaneous error on source and destination', async t => {301test('Simultaneous error on source and destination', async () => {302 const source = execa('noop.js', ['']);303 const destination = execa('stdin.js');304 const pipePromise = source.pipe(destination);305
1 unmodified line
307 source.nodeChildProcess.emit('error', sourceCause);308 const destinationCause = new Error('other');309 destination.nodeChildProcess.emit('error', destinationCause);310292 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(destination));293 t.like(await t.throwsAsync(source), {cause: {originalMessage: sourceCause.originalMessage}});294 t.like(await t.throwsAsync(destination), {cause: {originalMessage: destinationCause.originalMessage}});311 assert.equal(await assertRejects(pipePromise), await assertRejects(destination));312 assertLike(await assertRejects(source), {cause: sourceCause});313 assertLike(await assertRejects(destination), {cause: destinationCause});314});315297test('Does not need to await individual promises', async t => {316test('Does not need to await individual promises', async () => {317 const source = execa('fail.js');318 const destination = execa('fail.js');300 await t.throwsAsync(source.pipe(destination));319 await assertRejects(source.pipe(destination));320});321303test.serial('Need to await .pipe() return value', async t => {304 await assertUnhandledPipePromise(t);322test('Need to await .pipe() return value', async () => {323 await assertUnhandledPipePromise();324});325307test.serial('Need to await .pipe() return value, "all" option', async t => {308 await assertUnhandledPipePromise(t, {destinationOptions: {all: true}});326test('Need to await .pipe() return value, "all" option', async () => {327 await assertUnhandledPipePromise({destinationOptions: {all: true}});328});329311test.serial('Need to await .pipe() return value after inspecting lazy .all', async t => {312 await assertUnhandledPipePromise(t, {330test('Need to await .pipe() return value after inspecting lazy .all', async () => {331 await assertUnhandledPipePromise({332 destinationOptions: {all: true},333 inspectPipePromise(pipePromise) {334 const descriptor = Object.getOwnPropertyDescriptor(pipePromise, 'all');316 t.is(typeof descriptor.get, 'function');335 assert.equal(typeof descriptor.get, 'function');336 },337 });338});339321test.serial('Need to await .pipe() return value after getOneMessage()', async t => {340test('Need to await .pipe() return value after getOneMessage()', async () => {341 const source = execa('fail.js');342 const destination = execa('ipc-send-twice.js', {ipc: true});343 const pipePromise = source.pipe(destination);325 const unhandledRejectionPromise = once(process, 'unhandledRejection');344327 t.is(await pipePromise.getOneMessage(), 'foo');328 await assertUnhandledRejection(t, pipePromise, unhandledRejectionPromise);329 await t.throwsAsync(source);345 assert.equal(await pipePromise.getOneMessage(), 'foo');346 await assertUnhandledRejection(pipePromise);347 await assertRejects(source);348 await destination;331 await t.throwsAsync(pipePromise);349 await assertRejects(pipePromise);350});351334test.serial('Need to await .pipe() return value after paused getEachMessage()', async t => {352test('Need to await .pipe() return value after paused getEachMessage()', async () => {353 const source = execa('fail.js');354 const destination = execa('ipc-send-twice.js', {ipc: true});355 const pipePromise = source.pipe(destination);338 const unhandledRejectionPromise = once(process, 'unhandledRejection');356 const iterator = pipePromise.getEachMessage();357341 t.deepEqual(await iterator.next(), {done: false, value: 'foo'});342 await assertUnhandledRejection(t, pipePromise, unhandledRejectionPromise);343 await t.throwsAsync(source);358 assert.deepEqual(await iterator.next(), {done: false, value: 'foo'});359 await assertUnhandledRejection(pipePromise);360 await assertRejects(source);361 await destination;345 await t.throwsAsync(pipePromise);362 await assertRejects(pipePromise);363});364365if (isLinux) {349 const testYesHead = async (t, useStdoutTransform, useStdinTransform, all) => {366 const testYesHead = async (useStdoutTransform, useStdinTransform, all) => {367 const source = execa('yes', {stdout: useStdoutTransform ? noopGenerator(false) : 'pipe', all});368 const destination = execa('head', ['-n', '1'], {stdin: useStdinTransform ? noopGenerator(false) : 'pipe'});369 const pipePromise = source.pipe(destination);353 t.is(await t.throwsAsync(pipePromise), await t.throwsAsync(source));354 t.like(await destination, {stdout: 'y'});355 const sourceError = await t.throwsAsync(source);356 t.is(sourceError.exitCode, 1);357 t.regex(sourceError.stderr, /^yes: standard output: (?:Broken pipe|Connection reset by peer)$/);370 assert.equal(await assertRejects(pipePromise), await assertRejects(source));371 assertLike(await destination, {stdout: 'y'});372 const sourceError = await assertRejects(source);373 assert.equal(sourceError.exitCode, 1);374 assert.match(sourceError.stderr, /^yes: standard output: (?:Broken pipe|Connection reset by peer)$/);375359 t.false(source.stdout.readableEnded);360 t.is(source.stdout.errored, null);361 t.true(source.stdout.destroyed);362 t.true(source.stderr.readableEnded);363 t.is(source.stderr.errored, null);364 t.true(source.stderr.destroyed);376 assert.equal(source.stdout.readableEnded, false);377 assert.equal(source.stdout.errored, null);378 assert.equal(source.stdout.destroyed, true);379 assert.equal(source.stderr.readableEnded, true);380 assert.equal(source.stderr.errored, null);381 assert.equal(source.stderr.destroyed, true);382366 if (all) {367 t.true(source.all.readableEnded);368 t.is(source.all.errored, null);369 t.true(source.all.destroyed);383 if (!all) {384 return;385 }386387 assert.equal(source.all.readableEnded, true);388 assert.equal(source.all.errored, null);389 assert.equal(source.all.destroyed, true);390 };391373 test.serial('Works with yes | head', testYesHead, false, false, false);374 test.serial('Works with yes | head, input transform', testYesHead, false, true, false);375 test.serial('Works with yes | head, output transform', testYesHead, true, false, false);376 test.serial('Works with yes | head, input/output transform', testYesHead, true, true, false);377 test.serial('Works with yes | head, "all" option', testYesHead, false, false, true);378 test.serial('Works with yes | head, "all" option, input transform', testYesHead, false, true, true);379 test.serial('Works with yes | head, "all" option, output transform', testYesHead, true, false, true);380 test.serial('Works with yes | head, "all" option, input/output transform', testYesHead, true, true, true);392 test('Works with yes | head', () => testYesHead(false, false, false));393 test('Works with yes | head, input transform', () => testYesHead(false, true, false));394 test('Works with yes | head, output transform', () => testYesHead(true, false, false));395 test('Works with yes | head, input/output transform', () => testYesHead(true, true, false));396 test('Works with yes | head, "all" option', () => testYesHead(false, false, true));397 test('Works with yes | head, "all" option, input transform', () => testYesHead(false, true, true));398 test('Works with yes | head, "all" option, output transform', () => testYesHead(true, false, true));399 test('Works with yes | head, "all" option, input/output transform', () => testYesHead(true, true, true));400}
modified:test/pipe/setup.js+17 added-16 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {fullStdio, fullReadableStdio} from '../helpers/stdio.js';6import {foobarString} from '../helpers/input.js';78setFixtureDirectory();910// eslint-disable-next-line max-params10const pipeToSubprocess = async (t, readableFdNumber, writableFdNumber, from, to, readableOptions = {}, writableOptions = {}) => {11const pipeToSubprocess = async (readableFdNumber, writableFdNumber, from, to, readableOptions = {}, writableOptions = {}) => {12 const {stdout} = await execa('noop-fd.js', [`${readableFdNumber}`, foobarString], readableOptions)13 .pipe(execa('stdin-fd.js', [`${writableFdNumber}`], writableOptions), {from, to});13 t.is(stdout, foobarString);14 assert.equal(stdout, foobarString);15};1616test('pipe(...) can pipe', pipeToSubprocess, 1, 0);17test('pipe(..., {from: "stdout"}) can pipe', pipeToSubprocess, 1, 0, 'stdout');18test('pipe(..., {from: "fd1"}) can pipe', pipeToSubprocess, 1, 0, 'fd1');19test('pipe(..., {from: "stderr"}) can pipe stderr', pipeToSubprocess, 2, 0, 'stderr');20test('pipe(..., {from: "fd2"}) can pipe', pipeToSubprocess, 2, 0, 'fd2');21test('pipe(..., {from: "fd3"}) can pipe', pipeToSubprocess, 3, 0, 'fd3', undefined, fullStdio);22test('pipe(..., {from: "all"}) can pipe stdout', pipeToSubprocess, 1, 0, 'all', undefined, {all: true});23test('pipe(..., {from: "all"}) can pipe stderr', pipeToSubprocess, 2, 0, 'all', undefined, {all: true});24test('pipe(..., {from: "all"}) can pipe stdout even with "stderr: ignore"', pipeToSubprocess, 1, 0, 'all', undefined, {all: true, stderr: 'ignore'});25test('pipe(..., {from: "all"}) can pipe stderr even with "stdout: ignore"', pipeToSubprocess, 2, 0, 'all', undefined, {all: true, stdout: 'ignore'});26test('pipe(..., {to: "stdin"}) can pipe', pipeToSubprocess, 1, 0, undefined, 'stdin');27test('pipe(..., {to: "fd0"}) can pipe', pipeToSubprocess, 1, 0, undefined, 'fd0');28test('pipe(..., {to: "fd3"}) can pipe', pipeToSubprocess, 1, 3, undefined, 'fd3', {}, fullReadableStdio());17test('pipe(...) can pipe', () => pipeToSubprocess(1, 0));18test('pipe(..., {from: "stdout"}) can pipe', () => pipeToSubprocess(1, 0, 'stdout'));19test('pipe(..., {from: "fd1"}) can pipe', () => pipeToSubprocess(1, 0, 'fd1'));20test('pipe(..., {from: "stderr"}) can pipe stderr', () => pipeToSubprocess(2, 0, 'stderr'));21test('pipe(..., {from: "fd2"}) can pipe', () => pipeToSubprocess(2, 0, 'fd2'));22test('pipe(..., {from: "fd3"}) can pipe', () => pipeToSubprocess(3, 0, 'fd3', undefined, fullStdio));23test('pipe(..., {from: "all"}) can pipe stdout', () => pipeToSubprocess(1, 0, 'all', undefined, {all: true}));24test('pipe(..., {from: "all"}) can pipe stderr', () => pipeToSubprocess(2, 0, 'all', undefined, {all: true}));25test('pipe(..., {from: "all"}) can pipe stdout even with "stderr: ignore"', () => pipeToSubprocess(1, 0, 'all', undefined, {all: true, stderr: 'ignore'}));26test('pipe(..., {from: "all"}) can pipe stderr even with "stdout: ignore"', () => pipeToSubprocess(2, 0, 'all', undefined, {all: true, stdout: 'ignore'}));27test('pipe(..., {to: "stdin"}) can pipe', () => pipeToSubprocess(1, 0, undefined, 'stdin'));28test('pipe(..., {to: "fd0"}) can pipe', () => pipeToSubprocess(1, 0, undefined, 'fd0'));29test('pipe(..., {to: "fd3"}) can pipe', () => pipeToSubprocess(1, 3, undefined, 'fd3', {}, fullReadableStdio()));
modified:test/pipe/streaming.js+170 added-168 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {PassThrough} from 'node:stream';3import test from 'ava';4import test from 'node:test';5import {assertRejects, assertLike} from '../helpers/assert.js';6import {execa} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {foobarString} from '../helpers/input.js';9import {assertMaxListeners} from '../helpers/listeners.js';
1 unmodified line
11import {PARALLEL_COUNT} from '../helpers/parallel.js';1213setFixtureDirectory();1413test('Can pipe two sources to same destination', async t => {15test('Can pipe two sources to same destination', async () => {16 const source = execa('noop.js', [foobarString]);17 const secondSource = execa('noop.js', [foobarString]);18 const destination = execa('stdin.js');19 const pipePromise = source.pipe(destination);20 const secondPipePromise = secondSource.pipe(destination);2120 t.like(await source, {stdout: foobarString});21 t.like(await secondSource, {stdout: foobarString});22 t.like(await destination, {stdout: `${foobarString}\n${foobarString}`});23 t.is(await pipePromise, await destination);24 t.is(await secondPipePromise, await destination);22 assertLike(await source, {stdout: foobarString});23 assertLike(await secondSource, {stdout: foobarString});24 assertLike(await destination, {stdout: `${foobarString}\n${foobarString}`});25 assert.equal(await pipePromise, await destination);26 assert.equal(await secondPipePromise, await destination);27});2827test('Can pipe three sources to same destination', async t => {29test('Can pipe three sources to same destination', async () => {30 const source = execa('noop.js', [foobarString]);31 const secondSource = execa('noop.js', [foobarString]);32 const thirdSource = execa('noop.js', [foobarString]);33 const destination = execa('stdin.js');34 const pipePromise = source.pipe(destination);35 const secondPipePromise = secondSource.pipe(destination);36 const thirdPromise = thirdSource.pipe(destination);3736 t.like(await source, {stdout: foobarString});37 t.like(await secondSource, {stdout: foobarString});38 t.like(await thirdSource, {stdout: foobarString});39 t.like(await destination, {stdout: `${foobarString}\n${foobarString}\n${foobarString}`});40 t.is(await pipePromise, await destination);41 t.is(await secondPipePromise, await destination);42 t.is(await thirdPromise, await destination);38 assertLike(await source, {stdout: foobarString});39 assertLike(await secondSource, {stdout: foobarString});40 assertLike(await thirdSource, {stdout: foobarString});41 assertLike(await destination, {stdout: `${foobarString}\n${foobarString}\n${foobarString}`});42 assert.equal(await pipePromise, await destination);43 assert.equal(await secondPipePromise, await destination);44 assert.equal(await thirdPromise, await destination);45});4645test.serial('Can pipe many sources to same destination', async t => {46 const checkMaxListeners = assertMaxListeners(t);47test('Can pipe many sources to same destination', async () => {48 const checkMaxListeners = assertMaxListeners();4950 const expectedResults = Array.from({length: PARALLEL_COUNT}, (_, index) => `${index}`).sort();51 const sources = expectedResults.map(expectedResult => execa('noop.js', [expectedResult]));52 const destination = execa('stdin.js');53 const pipePromises = sources.map(source => source.pipe(destination));5455 const results = await Promise.all(sources);54 t.deepEqual(results.map(({stdout}) => stdout), expectedResults);56 assert.deepEqual(results.map(({stdout}) => stdout), expectedResults);57 const destinationResult = await destination;56 t.deepEqual(destinationResult.stdout.split('\n').sort(), expectedResults);57 t.deepEqual(await Promise.all(pipePromises), sources.map(() => destinationResult));58 assert.deepEqual(destinationResult.stdout.split('\n').sort(), expectedResults);59 assert.deepEqual(await Promise.all(pipePromises), sources.map(() => destinationResult));6061 checkMaxListeners();62});6362test.serial('Can pipe same source to many destinations', async t => {63 const checkMaxListeners = assertMaxListeners(t);64test('Can pipe same source to many destinations', async () => {65 const checkMaxListeners = assertMaxListeners();6667 const source = execa('noop-fd.js', ['1', foobarString]);68 const expectedResults = Array.from({length: PARALLEL_COUNT}, (_, index) => `${index}`);69 const destinations = expectedResults.map(expectedResult => execa('noop-stdin-double.js', [expectedResult]));70 const pipePromises = destinations.map(destination => source.pipe(destination));7170 t.like(await source, {stdout: foobarString});72 assertLike(await source, {stdout: foobarString});73 const results = await Promise.all(destinations);72 t.deepEqual(results.map(({stdout}) => stdout), expectedResults.map(result => `${foobarString} ${result}`));73 t.deepEqual(await Promise.all(pipePromises), results);74 assert.deepEqual(results.map(({stdout}) => stdout), expectedResults.map(result => `${foobarString} ${result}`));75 assert.deepEqual(await Promise.all(pipePromises), results);7677 checkMaxListeners();78});7978test('Can pipe two streams from same subprocess to same destination', async t => {80test('Can pipe two streams from same subprocess to same destination', async () => {81 const source = execa('noop-both.js', [foobarString]);82 const destination = execa('stdin.js');83 const pipePromise = source.pipe(destination);84 const secondPipePromise = source.pipe(destination, {from: 'stderr'});8584 t.like(await source, {stdout: foobarString, stderr: foobarString});85 t.like(await destination, {stdout: `${foobarString}\n${foobarString}`});86 t.is(await pipePromise, await destination);87 t.is(await secondPipePromise, await destination);86 assertLike(await source, {stdout: foobarString, stderr: foobarString});87 assertLike(await destination, {stdout: `${foobarString}\n${foobarString}`});88 assert.equal(await pipePromise, await destination);89 assert.equal(await secondPipePromise, await destination);90});9190test('Can pipe same source to two streams from same subprocess', async t => {92test('Can pipe same source to two streams from same subprocess', async () => {93 const source = execa('noop-fd.js', ['1', foobarString]);94 const destination = execa('stdin-fd-both.js', ['3'], fullReadableStdio());95 const pipePromise = source.pipe(destination);96 const secondPipePromise = source.pipe(destination, {to: 'fd3'});9796 t.like(await source, {stdout: foobarString});97 t.like(await destination, {stdout: `${foobarString}${foobarString}`});98 t.is(await pipePromise, await destination);99 t.is(await secondPipePromise, await destination);98 assertLike(await source, {stdout: foobarString});99 assertLike(await destination, {stdout: `${foobarString}${foobarString}`});100 assert.equal(await pipePromise, await destination);101 assert.equal(await secondPipePromise, await destination);102});103102test('Can pipe a new source to same destination after some source has already written', async t => {104test('Can pipe a new source to same destination after some source has already written', async () => {105 const passThroughStream = new PassThrough();106 const source = execa('stdin.js', {stdin: ['pipe', passThroughStream]});107 const destination = execa('stdin.js');108 const pipePromise = source.pipe(destination);109110 passThroughStream.write('foo');111 const firstWrite = await once(destination.stdout, 'data');110 t.is(firstWrite.toString(), 'foo');112 assert.equal(firstWrite.toString(), 'foo');113114 const secondSource = execa('noop.js', ['bar']);115 const secondPipePromise = secondSource.pipe(destination);116 passThroughStream.end();117116 t.like(await source, {stdout: 'foo'});117 t.like(await secondSource, {stdout: 'bar'});118 t.like(await destination, {stdout: 'foobar'});119 t.is(await pipePromise, await destination);120 t.is(await secondPipePromise, await destination);118 assertLike(await source, {stdout: 'foo'});119 assertLike(await secondSource, {stdout: 'bar'});120 assertLike(await destination, {stdout: 'foobar'});121 assert.equal(await pipePromise, await destination);122 assert.equal(await secondPipePromise, await destination);123});124123test('Can pipe a second source to same destination after destination has already ended', async t => {125test('Can pipe a second source to same destination after destination has already ended', async () => {126 const source = execa('noop.js', [foobarString]);127 const destination = execa('stdin.js');128 const pipePromise = source.pipe(destination);129128 t.like(await source, {stdout: foobarString});129 t.like(await destination, {stdout: foobarString});130 t.is(await pipePromise, await destination);130 assertLike(await source, {stdout: foobarString});131 assertLike(await destination, {stdout: foobarString});132 assert.equal(await pipePromise, await destination);133134 const secondSource = execa('noop.js', [foobarString]);135 const secondPipePromise = secondSource.pipe(destination);136135 t.like(await secondSource, {stdout: ''});136 t.is(await secondPipePromise, await destination);137 assertLike(await secondSource, {stdout: ''});138 assert.equal(await secondPipePromise, await destination);139});140139test('Can pipe same source to a second destination after source has already ended', async t => {141test('Can pipe same source to a second destination after source has already ended', async () => {142 const source = execa('noop.js', [foobarString]);143 const destination = execa('stdin.js');144 const pipePromise = source.pipe(destination);145144 t.like(await source, {stdout: foobarString});145 t.like(await destination, {stdout: foobarString});146 t.is(await pipePromise, await destination);146 assertLike(await source, {stdout: foobarString});147 assertLike(await destination, {stdout: foobarString});148 assert.equal(await pipePromise, await destination);149150 const secondDestination = execa('stdin.js');151 const secondPipePromise = source.pipe(secondDestination);152151 t.like(await secondDestination, {stdout: ''});152 t.is(await secondPipePromise, await secondDestination);153 assertLike(await secondDestination, {stdout: ''});154 assert.equal(await secondPipePromise, await secondDestination);155});156155test('Can pipe a new source to same destination after some but not all sources have ended', async t => {157test('Can pipe a new source to same destination after some but not all sources have ended', async () => {158 const source = execa('noop.js', [foobarString]);159 const passThroughStream = new PassThrough();160 const secondSource = execa('stdin.js', {stdin: ['pipe', passThroughStream]});161 const destination = execa('stdin.js');162 const pipePromise = source.pipe(destination);163 const secondPipePromise = secondSource.pipe(destination);164163 t.like(await source, {stdout: foobarString});165 assertLike(await source, {stdout: foobarString});166167 const thirdSource = execa('noop.js', [foobarString]);168 const thirdPipePromise = thirdSource.pipe(destination);169 passThroughStream.end(`${foobarString}\n`);170169 t.like(await secondSource, {stdout: foobarString});170 t.like(await thirdSource, {stdout: foobarString});171 t.like(await destination, {stdout: `${foobarString}\n${foobarString}\n${foobarString}`});172 t.is(await pipePromise, await destination);173 t.is(await secondPipePromise, await destination);174 t.is(await thirdPipePromise, await destination);171 assertLike(await secondSource, {stdout: foobarString});172 assertLike(await thirdSource, {stdout: foobarString});173 assertLike(await destination, {stdout: `${foobarString}\n${foobarString}\n${foobarString}`});174 assert.equal(await pipePromise, await destination);175 assert.equal(await secondPipePromise, await destination);176 assert.equal(await thirdPipePromise, await destination);177});178177test('Can pipe two subprocesses already ended', async t => {179test('Can pipe two subprocesses already ended', async () => {180 const source = execa('noop.js', [foobarString]);181 const destination = execa('stdin.js');182 destination.stdin.end('.');183 await Promise.all([source, destination]);184 const pipePromise = source.pipe(destination);185184 t.like(await source, {stdout: foobarString});185 t.like(await destination, {stdout: '.'});186 t.is(await pipePromise, await destination);186 assertLike(await source, {stdout: foobarString});187 assertLike(await destination, {stdout: '.'});188 assert.equal(await pipePromise, await destination);189});190189test('Can pipe to same destination through multiple paths', async t => {191test('Can pipe to same destination through multiple paths', async () => {192 const source = execa('noop.js', [foobarString]);193 const destination = execa('stdin.js');194 const secondDestination = execa('stdin.js');195 const pipePromise = source.pipe(destination);196 const secondPipePromise = pipePromise.pipe(secondDestination);197 const thirdPipePromise = source.pipe(secondDestination);198197 t.like(await source, {stdout: foobarString});198 t.like(await destination, {stdout: foobarString});199 t.like(await secondDestination, {stdout: `${foobarString}\n${foobarString}`});200 t.is(await pipePromise, await destination);201 t.is(await secondPipePromise, await secondDestination);202 t.is(await thirdPipePromise, await secondDestination);199 assertLike(await source, {stdout: foobarString});200 assertLike(await destination, {stdout: foobarString});201 assertLike(await secondDestination, {stdout: `${foobarString}\n${foobarString}`});202 assert.equal(await pipePromise, await destination);203 assert.equal(await secondPipePromise, await secondDestination);204 assert.equal(await thirdPipePromise, await secondDestination);205});206205test('Can pipe two sources to same destination in objectMode', async t => {207test('Can pipe two sources to same destination in objectMode', async () => {208 const stdoutTransform = {209 * transform() {210 yield [foobarString];211 },212 objectMode: true,213 };214 const source = execa('noop.js', [''], {stdout: stdoutTransform});215 const secondSource = execa('noop.js', [''], {stdout: stdoutTransform});214 t.true(source.stdout.readableObjectMode);215 t.true(secondSource.stdout.readableObjectMode);216 assert.equal(source.stdout.readableObjectMode, true);217 assert.equal(secondSource.stdout.readableObjectMode, true);218219 const stdinTransform = {220 * transform([chunk]) {221 yield chunk;
3 unmodified lines
225 const destination = execa('stdin.js', {stdin: stdinTransform});226 const pipePromise = source.pipe(destination);227 const secondPipePromise = secondSource.pipe(destination);228227 t.like(await source, {stdout: [[foobarString]]});228 t.like(await secondSource, {stdout: [[foobarString]]});229 t.like(await destination, {stdout: `${foobarString}\n${foobarString}`});230 t.is(await pipePromise, await destination);231 t.is(await secondPipePromise, await destination);229 assertLike(await source, {stdout: [[foobarString]]});230 assertLike(await secondSource, {stdout: [[foobarString]]});231 assertLike(await destination, {stdout: `${foobarString}\n${foobarString}`});232 assert.equal(await pipePromise, await destination);233 assert.equal(await secondPipePromise, await destination);234});235234test('Can pipe one source to two destinations', async t => {236test('Can pipe one source to two destinations', async () => {237 const source = execa('noop.js', [foobarString]);238 const destination = execa('stdin.js');239 const secondDestination = execa('stdin.js');240 const pipePromise = source.pipe(destination);241 const secondPipePromise = source.pipe(secondDestination);242241 t.like(await source, {stdout: foobarString});242 t.like(await destination, {stdout: foobarString});243 t.like(await secondDestination, {stdout: foobarString});244 t.is(await pipePromise, await destination);245 t.is(await secondPipePromise, await secondDestination);243 assertLike(await source, {stdout: foobarString});244 assertLike(await destination, {stdout: foobarString});245 assertLike(await secondDestination, {stdout: foobarString});246 assert.equal(await pipePromise, await destination);247 assert.equal(await secondPipePromise, await secondDestination);248});249248test('Can pipe one source to three destinations', async t => {250test('Can pipe one source to three destinations', async () => {251 const source = execa('noop.js', [foobarString]);252 const destination = execa('stdin.js');253 const secondDestination = execa('stdin.js');254 const thirdDestination = execa('stdin.js');255 const pipePromise = source.pipe(destination);256 const secondPipePromise = source.pipe(secondDestination);257 const thirdPipePromise = source.pipe(thirdDestination);258257 t.like(await source, {stdout: foobarString});258 t.like(await destination, {stdout: foobarString});259 t.like(await secondDestination, {stdout: foobarString});260 t.like(await thirdDestination, {stdout: foobarString});261 t.is(await pipePromise, await destination);262 t.is(await secondPipePromise, await secondDestination);263 t.is(await thirdPipePromise, await thirdDestination);259 assertLike(await source, {stdout: foobarString});260 assertLike(await destination, {stdout: foobarString});261 assertLike(await secondDestination, {stdout: foobarString});262 assertLike(await thirdDestination, {stdout: foobarString});263 assert.equal(await pipePromise, await destination);264 assert.equal(await secondPipePromise, await secondDestination);265 assert.equal(await thirdPipePromise, await thirdDestination);266});267266test('Can create a series of pipes', async t => {268test('Can create a series of pipes', async () => {269 const source = execa('noop.js', [foobarString]);270 const destination = execa('stdin.js');271 const secondDestination = execa('stdin.js');272 const pipePromise = source.pipe(destination);273 const secondPipePromise = pipePromise.pipe(secondDestination);274273 t.like(await source, {stdout: foobarString});274 t.like(await destination, {stdout: foobarString});275 t.like(await secondDestination, {stdout: foobarString});276 t.is(await pipePromise, await destination);277 t.is(await secondPipePromise, await secondDestination);275 assertLike(await source, {stdout: foobarString});276 assertLike(await destination, {stdout: foobarString});277 assertLike(await secondDestination, {stdout: foobarString});278 assert.equal(await pipePromise, await destination);279 assert.equal(await secondPipePromise, await secondDestination);280});281280test('Returns pipedFrom on success', async t => {282test('Returns pipedFrom on success', async () => {283 const source = execa('noop.js', [foobarString]);284 const destination = execa('stdin.js');285 const pipePromise = source.pipe(destination);286287 const destinationResult = await destination;286 t.deepEqual(destinationResult.pipedFrom, []);288 assert.deepEqual(destinationResult.pipedFrom, []);289 const sourceResult = await source;290289 t.like(await pipePromise, {pipedFrom: [sourceResult]});290 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);291 t.deepEqual(sourceResult.pipedFrom, []);291 assertLike(await pipePromise, {pipedFrom: [sourceResult]});292 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);293 assert.deepEqual(sourceResult.pipedFrom, []);294});295294test('Returns pipedFrom on deep success', async t => {296test('Returns pipedFrom on deep success', async () => {297 const source = execa('noop.js', [foobarString]);298 const destination = execa('stdin.js');299 const secondDestination = execa('stdin.js');300 const pipePromise = source.pipe(destination);301 const secondPipePromise = pipePromise.pipe(secondDestination);302303 const destinationResult = await destination;302 t.deepEqual(destinationResult.pipedFrom, []);304 assert.deepEqual(destinationResult.pipedFrom, []);305 const secondDestinationResult = await secondDestination;304 t.deepEqual(secondDestinationResult.pipedFrom, []);306 assert.deepEqual(secondDestinationResult.pipedFrom, []);307 const sourceResult = await source;308307 t.like(await secondPipePromise, {pipedFrom: [destinationResult]});308 t.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);309 t.like(await pipePromise, {pipedFrom: [sourceResult]});310 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);311 t.deepEqual(sourceResult.pipedFrom, []);309 assertLike(await secondPipePromise, {pipedFrom: [destinationResult]});310 assert.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);311 assertLike(await pipePromise, {pipedFrom: [sourceResult]});312 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);313 assert.deepEqual(sourceResult.pipedFrom, []);314});315314test('Returns pipedFrom on source failure', async t => {316test('Returns pipedFrom on source failure', async () => {317 const source = execa('noop-fail.js', ['1', foobarString]);318 const destination = execa('stdin.js');319 const pipePromise = source.pipe(destination);320321 const destinationResult = await destination;320 t.deepEqual(destinationResult.pipedFrom, []);321 const sourceResult = await t.throwsAsync(source);322 assert.deepEqual(destinationResult.pipedFrom, []);323 const sourceResult = await assertRejects(source);324323 t.like(await t.throwsAsync(pipePromise), {pipedFrom: []});324 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);325 t.deepEqual(sourceResult.pipedFrom, []);325 assertLike(await assertRejects(pipePromise), {pipedFrom: []});326 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);327 assert.deepEqual(sourceResult.pipedFrom, []);328});329328test('Returns pipedFrom on destination failure', async t => {330test('Returns pipedFrom on destination failure', async () => {331 const source = execa('noop.js', [foobarString]);332 const destination = execa('stdin-fail.js');333 const pipePromise = source.pipe(destination);334333 const destinationResult = await t.throwsAsync(destination);335 const destinationResult = await assertRejects(destination);336 const sourceResult = await source;337336 t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});337 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);338 t.deepEqual(sourceResult.pipedFrom, []);338 assertLike(await assertRejects(pipePromise), {pipedFrom: [sourceResult]});339 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);340 assert.deepEqual(sourceResult.pipedFrom, []);341});342341test('Returns pipedFrom on source + destination failure', async t => {343test('Returns pipedFrom on source + destination failure', async () => {344 const source = execa('noop-fail.js', ['1', foobarString]);345 const destination = execa('stdin-fail.js');346 const pipePromise = source.pipe(destination);347346 const destinationResult = await t.throwsAsync(destination);347 const sourceResult = await t.throwsAsync(source);348 const destinationResult = await assertRejects(destination);349 const sourceResult = await assertRejects(source);350349 t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});350 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);351 t.deepEqual(sourceResult.pipedFrom, []);351 assertLike(await assertRejects(pipePromise), {pipedFrom: [sourceResult]});352 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);353 assert.deepEqual(sourceResult.pipedFrom, []);354});355354test('Returns pipedFrom on deep failure', async t => {356test('Returns pipedFrom on deep failure', async () => {357 const source = execa('noop-fail.js', ['1', foobarString]);358 const destination = execa('stdin-fail.js');359 const secondDestination = execa('stdin.js');360 const pipePromise = source.pipe(destination);361 const secondPipePromise = pipePromise.pipe(secondDestination);362361 const destinationResult = await t.throwsAsync(destination);363 const destinationResult = await assertRejects(destination);364 const secondDestinationResult = await secondDestination;363 t.deepEqual(secondDestinationResult.pipedFrom, []);364 const sourceResult = await t.throwsAsync(source);365 assert.deepEqual(secondDestinationResult.pipedFrom, []);366 const sourceResult = await assertRejects(source);367366 t.like(await t.throwsAsync(secondPipePromise), {pipedFrom: [sourceResult]});367 t.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);368 t.like(await t.throwsAsync(pipePromise), {pipedFrom: [sourceResult]});369 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);370 t.deepEqual(sourceResult.pipedFrom, []);368 assertLike(await assertRejects(secondPipePromise), {pipedFrom: [sourceResult]});369 assert.deepEqual(secondDestinationResult.pipedFrom, [destinationResult]);370 assertLike(await assertRejects(pipePromise), {pipedFrom: [sourceResult]});371 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);372 assert.deepEqual(sourceResult.pipedFrom, []);373});374373test('Returns pipedFrom from multiple sources', async t => {375test('Returns pipedFrom from multiple sources', async () => {376 const source = execa('noop.js', [foobarString]);377 const secondSource = execa('noop.js', [foobarString]);378 const destination = execa('stdin.js');379 const pipePromise = source.pipe(destination);380 const secondPipePromise = secondSource.pipe(destination);381382 const destinationResult = await destination;381 t.deepEqual(destinationResult.pipedFrom, []);383 assert.deepEqual(destinationResult.pipedFrom, []);384 const sourceResult = await source;385 const secondSourceResult = await secondSource;386385 t.like(await pipePromise, {pipedFrom: [sourceResult, secondSourceResult]});386 t.like(await secondPipePromise, {pipedFrom: [sourceResult, secondSourceResult]});387 t.deepEqual(destinationResult.pipedFrom, [sourceResult, secondSourceResult]);388 t.deepEqual(sourceResult.pipedFrom, []);389 t.deepEqual(secondSourceResult.pipedFrom, []);387 assertLike(await pipePromise, {pipedFrom: [sourceResult, secondSourceResult]});388 assertLike(await secondPipePromise, {pipedFrom: [sourceResult, secondSourceResult]});389 assert.deepEqual(destinationResult.pipedFrom, [sourceResult, secondSourceResult]);390 assert.deepEqual(sourceResult.pipedFrom, []);391 assert.deepEqual(secondSourceResult.pipedFrom, []);392});393392test('Returns pipedFrom from already ended subprocesses', async t => {394test('Returns pipedFrom from already ended subprocesses', async () => {395 const source = execa('noop.js', [foobarString]);396 const destination = execa('stdin.js');397 destination.stdin.end('.');398 await Promise.all([source, destination]);399 const pipePromise = source.pipe(destination);400401 const destinationResult = await destination;400 t.deepEqual(destinationResult.pipedFrom, []);402 assert.deepEqual(destinationResult.pipedFrom, []);403 const sourceResult = await source;402 t.deepEqual(sourceResult.pipedFrom, []);404 assert.deepEqual(sourceResult.pipedFrom, []);405404 t.like(await pipePromise, {pipedFrom: [sourceResult]});405 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);406 t.deepEqual(sourceResult.pipedFrom, []);406 assertLike(await pipePromise, {pipedFrom: [sourceResult]});407 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);408 assert.deepEqual(sourceResult.pipedFrom, []);409});410409test('Does not return nor set pipedFrom on signal abort', async t => {411test('Does not return nor set pipedFrom on signal abort', async () => {412 const abortController = new AbortController();413 const source = execa('empty.js');414 const destination = execa('empty.js');415 const pipePromise = source.pipe(destination, {unpipeSignal: abortController.signal});416417 abortController.abort();416 t.like(await t.throwsAsync(pipePromise), {pipedFrom: []});418 assertLike(await assertRejects(pipePromise), {pipedFrom: []});419 const destinationResult = await destination;418 t.deepEqual(destinationResult.pipedFrom, []);420 assert.deepEqual(destinationResult.pipedFrom, []);421 const sourceResult = await source;420 t.deepEqual(sourceResult.pipedFrom, []);422 assert.deepEqual(sourceResult.pipedFrom, []);423});424423test('Can pipe same source to same destination twice', async t => {425test('Can pipe same source to same destination twice', async () => {426 const source = execa('noop.js', [foobarString]);427 const destination = execa('stdin.js');428 const pipePromise = source.pipe(destination);429 const secondPipePromise = source.pipe(destination);430431 const destinationResult = await destination;430 t.like(destinationResult, {pipedFrom: []});432 assertLike(destinationResult, {pipedFrom: []});433 const sourceResult = await source;432 t.like(sourceResult, {pipedFrom: []});434 assertLike(sourceResult, {pipedFrom: []});435434 t.like(await source, {stdout: foobarString});435 t.like(await destination, {stdout: foobarString});436 t.is(await pipePromise, destinationResult);437 t.is(await secondPipePromise, destinationResult);438 t.deepEqual(destinationResult.pipedFrom, [sourceResult]);439 t.deepEqual(sourceResult.pipedFrom, []);436 assertLike(await source, {stdout: foobarString});437 assertLike(await destination, {stdout: foobarString});438 assert.equal(await pipePromise, destinationResult);439 assert.equal(await secondPipePromise, destinationResult);440 assert.deepEqual(destinationResult.pipedFrom, [sourceResult]);441 assert.deepEqual(sourceResult.pipedFrom, []);442});443444// `to: 'fd3'` and higher requires the `stdio` option, which cannot be combined with the `stdin` option that piping sets by default443test('Can pipe to an additional file descriptor of a destination with the "stdio" option', async t => {445test('Can pipe to an additional file descriptor of a destination with the "stdio" option', async () => {446 const source = execa('noop.js', [foobarString]);447 const {stdout} = await source.pipe('stdin-fd.js', ['3'], {448 to: 'fd3',449 stdio: ['pipe', 'pipe', 'pipe', {value: 'pipe', input: true}],450 });449 t.is(stdout, foobarString);451 assert.equal(stdout, foobarString);452});
modified:test/pipe/throw.js+22 added-19 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa} from '../../index.js';4import {foobarString} from '../helpers/input.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {assertPipeError} from '../helpers/pipe.js';7import {assertLike} from '../helpers/assert.js';89setFixtureDirectory();109test('Destination stream is ended when first argument is invalid', async t => {11test('Destination stream is ended when first argument is invalid', async () => {12 const source = execa('empty.js', {stdout: 'ignore'});13 const destination = execa('stdin.js');14 const pipePromise = source.pipe(destination);1514 await assertPipeError(t, pipePromise, 'option is incompatible');16 await assertPipeError(pipePromise, 'option is incompatible');17 await source;16 t.like(await destination, {stdout: ''});18 assertLike(await destination, {stdout: ''});19});2019test('Destination stream is ended when first argument is invalid - $', async t => {21test('Destination stream is ended when first argument is invalid - $', async () => {22 const pipePromise = execa('empty.js', {stdout: 'ignore'}).pipe`stdin.js`;21 await assertPipeError(t, pipePromise, 'option is incompatible');23 await assertPipeError(pipePromise, 'option is incompatible');24});2524test('Source stream is aborted when second argument is invalid', async t => {26test('Source stream is aborted when second argument is invalid', async () => {27 const source = execa('noop.js', [foobarString]);28 const pipePromise = source.pipe(false);2928 await assertPipeError(t, pipePromise, 'an Execa subprocess');29 t.like(await source, {stdout: ''});30 await assertPipeError(pipePromise, 'an Execa subprocess');31 assertLike(await source, {stdout: ''});32});3332test('Both arguments might be invalid', async t => {34test('Both arguments might be invalid', async () => {35 const source = execa('empty.js', {stdout: 'ignore'});36 const pipePromise = source.pipe(false);3736 await assertPipeError(t, pipePromise, 'an Execa subprocess');37 t.like(await source, {stdout: undefined});38 await assertPipeError(pipePromise, 'an Execa subprocess');39 const {stdout} = await source;40 assert.equal(stdout, undefined);41});4243// The destination subprocess is spawned before the `to` option is validated, so its error must be handled.44// This runs in another process, since that is where the unhandled rejection crashes it.42test('Destination subprocess error is not unhandled when the "to" option is invalid', async t => {45test('Destination subprocess error is not unhandled when the "to" option is invalid', async () => {46 const {stdout} = await execa('pipe-destination-error.js', ['fail.js']);44 t.is(stdout, 'REACHED THE END');47 assert.equal(stdout, 'REACHED THE END');48});4947test('Destination subprocess is terminated when the "to" option is invalid', async t => {50test('Destination subprocess is terminated when the "to" option is invalid', async () => {51 const {stdout} = await execa('pipe-destination-error.js', ['stdin.js'], {timeout: 10_000});49 t.is(stdout, 'REACHED THE END');52 assert.equal(stdout, 'REACHED THE END');53});5452test('Destination subprocess passed by the user is not terminated when the "to" option is invalid', async t => {55test('Destination subprocess passed by the user is not terminated when the "to" option is invalid', async () => {56 const source = execa('empty.js', {stdout: 'ignore'});57 const destination = execa('stdin.js');58 const pipePromise = source.pipe(destination, {to: 'fd9'});5957 await assertPipeError(t, pipePromise, 'fd9');60 await assertPipeError(pipePromise, 'fd9');61 destination.stdin.end(foobarString);62 const {stdout} = await destination;60 t.is(stdout, foobarString);63 assert.equal(stdout, foobarString);64});
modified:test/resolve/all.js+152 added-134 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa, execaSync} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {defaultHighWaterMark} from '../helpers/stream.js';6import {foobarString} from '../helpers/input.js';
9 unmodified lines
16const doubleFoobarArrayFull = [foobarStringFull, foobarStringFull];17const doubleFoobarArray = [foobarString, foobarString];1819// eslint-disable-next-line max-params19const testAllBoth = async (t, expectedOutput, encoding, lines, stripFinalNewline, isFailure, execaMethod) => {20const testAllBoth = async (expectedOutput, encoding, lines, stripFinalNewline, isFailure, execaMethod) => {21 const fixtureName = isFailure ? 'noop-both-fail.js' : 'noop-both.js';22 const {exitCode, all} = await execaMethod(fixtureName, [foobarString], {23 all: true,24 encoding,25 lines,26 stripFinalNewline,27 reject: !isFailure,28 });28 t.is(exitCode, isFailure ? 1 : 0);29 t.deepEqual(all, expectedOutput);29 assert.equal(exitCode, isFailure ? 1 : 0);30 assert.deepEqual(all, expectedOutput);31};3233const fdOne = {stderr: true};34const fdBoth = {stdout: true, stderr: true};3535test('result.all is defined', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execa);36test('result.all is defined, encoding "buffer"', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execa);37test('result.all is defined, lines', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execa);38test('result.all is defined, lines, fd-specific one', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execa);39test('result.all is defined, lines, fd-specific both', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execa);40test('result.all is defined, stripFinalNewline', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execa);41test('result.all is defined, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execa);42test('result.all is defined, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execa);43test('result.all is defined, encoding "buffer", stripFinalNewline', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execa);44test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execa);45test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execa);46test('result.all is defined, lines, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execa);47test('result.all is defined, lines, fd-specific one, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execa);48test('result.all is defined, lines, fd-specific both, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execa);49test('result.all is defined, lines, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execa);50test('result.all is defined, lines, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execa);51test('result.all is defined, failure', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execa);52test('result.all is defined, encoding "buffer", failure', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execa);53test('result.all is defined, lines, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execa);54test('result.all is defined, lines, fd-specific one, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execa);55test('result.all is defined, lines, fd-specific both, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execa);56test('result.all is defined, stripFinalNewline, failure', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execa);57test('result.all is defined, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execa);58test('result.all is defined, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execa);59test('result.all is defined, encoding "buffer", stripFinalNewline, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execa);60test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execa);61test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execa);62test('result.all is defined, lines, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execa);63test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execa);64test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execa);65test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execa);66test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execa);67test('result.all is defined, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execaSync);68test('result.all is defined, encoding "buffer", sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execaSync);69test('result.all is defined, lines, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execaSync);70test('result.all is defined, lines, fd-specific one, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execaSync);71test('result.all is defined, lines, fd-specific both, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execaSync);72test('result.all is defined, stripFinalNewline, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execaSync);73test('result.all is defined, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execaSync);74test('result.all is defined, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execaSync);75test('result.all is defined, encoding "buffer", stripFinalNewline, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execaSync);76test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execaSync);77test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execaSync);78test('result.all is defined, lines, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execaSync);79test('result.all is defined, lines, fd-specific one, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execaSync);80test('result.all is defined, lines, fd-specific both, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execaSync);81test('result.all is defined, lines, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execaSync);82test('result.all is defined, lines, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execaSync);83test('result.all is defined, failure, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execaSync);84test('result.all is defined, encoding "buffer", failure, sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execaSync);85test('result.all is defined, lines, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execaSync);86test('result.all is defined, lines, fd-specific one, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execaSync);87test('result.all is defined, lines, fd-specific both, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execaSync);88test('result.all is defined, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execaSync);89test('result.all is defined, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execaSync);90test('result.all is defined, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execaSync);91test('result.all is defined, encoding "buffer", stripFinalNewline, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execaSync);92test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execaSync);93test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execaSync);94test('result.all is defined, lines, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execaSync);95test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execaSync);96test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execaSync);97test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execaSync);98test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execaSync);36test('result.all is defined', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, false, execa));37test('result.all is defined, encoding "buffer"', () => testAllBoth(doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execa));38test('result.all is defined, lines', () => testAllBoth(doubleFoobarArrayFull, 'utf8', true, false, false, execa));39test('result.all is defined, lines, fd-specific one', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdOne, false, false, execa));40test('result.all is defined, lines, fd-specific both', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execa));41test('result.all is defined, stripFinalNewline', () => testAllBoth(doubleFoobarString, 'utf8', false, true, false, execa));42test('result.all is defined, stripFinalNewline, fd-specific one', () => testAllBoth(doubleFoobarString, 'utf8', false, fdOne, false, execa));43test('result.all is defined, stripFinalNewline, fd-specific both', () => testAllBoth(doubleFoobarString, 'utf8', false, fdBoth, false, execa));44test('result.all is defined, encoding "buffer", stripFinalNewline', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, true, false, execa));45test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdOne, false, execa));46test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execa));47test('result.all is defined, lines, stripFinalNewline', () => testAllBoth(doubleFoobarArray, 'utf8', true, true, false, execa));48test('result.all is defined, lines, fd-specific one, stripFinalNewline', () => testAllBoth(doubleFoobarArray, 'utf8', fdOne, true, false, execa));49test('result.all is defined, lines, fd-specific both, stripFinalNewline', () => testAllBoth(doubleFoobarArray, 'utf8', fdBoth, true, false, execa));50test('result.all is defined, lines, stripFinalNewline, fd-specific one', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdOne, false, execa));51test('result.all is defined, lines, stripFinalNewline, fd-specific both', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdBoth, false, execa));52test('result.all is defined, failure', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, true, execa));53test('result.all is defined, encoding "buffer", failure', () => testAllBoth(doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execa));54test('result.all is defined, lines, failure', () => testAllBoth(doubleFoobarArrayFull, 'utf8', true, false, true, execa));55test('result.all is defined, lines, fd-specific one, failure', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdOne, false, true, execa));56test('result.all is defined, lines, fd-specific both, failure', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execa));57test('result.all is defined, stripFinalNewline, failure', () => testAllBoth(doubleFoobarString, 'utf8', false, true, true, execa));58test('result.all is defined, stripFinalNewline, fd-specific one, failure', () => testAllBoth(doubleFoobarString, 'utf8', false, fdOne, true, execa));59test('result.all is defined, stripFinalNewline, fd-specific both, failure', () => testAllBoth(doubleFoobarString, 'utf8', false, fdBoth, true, execa));60test('result.all is defined, encoding "buffer", stripFinalNewline, failure', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, true, true, execa));61test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdOne, true, execa));62test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execa));63test('result.all is defined, lines, stripFinalNewline, failure', () => testAllBoth(doubleFoobarArray, 'utf8', true, true, true, execa));64test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure', () => testAllBoth(doubleFoobarArray, 'utf8', fdOne, true, true, execa));65test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure', () => testAllBoth(doubleFoobarArray, 'utf8', fdBoth, true, true, execa));66test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdOne, true, execa));67test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdBoth, true, execa));68test('result.all is defined, sync', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, false, execaSync));69test('result.all is defined, encoding "buffer", sync', () => testAllBoth(doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execaSync));70test('result.all is defined, lines, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', true, false, false, execaSync));71test('result.all is defined, lines, fd-specific one, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdOne, false, false, execaSync));72test('result.all is defined, lines, fd-specific both, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execaSync));73test('result.all is defined, stripFinalNewline, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, true, false, execaSync));74test('result.all is defined, stripFinalNewline, fd-specific one, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, fdOne, false, execaSync));75test('result.all is defined, stripFinalNewline, fd-specific both, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, fdBoth, false, execaSync));76test('result.all is defined, encoding "buffer", stripFinalNewline, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, true, false, execaSync));77test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdOne, false, execaSync));78test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execaSync));79test('result.all is defined, lines, stripFinalNewline, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, true, false, execaSync));80test('result.all is defined, lines, fd-specific one, stripFinalNewline, sync', () => testAllBoth(doubleFoobarArray, 'utf8', fdOne, true, false, execaSync));81test('result.all is defined, lines, fd-specific both, stripFinalNewline, sync', () => testAllBoth(doubleFoobarArray, 'utf8', fdBoth, true, false, execaSync));82test('result.all is defined, lines, stripFinalNewline, fd-specific one, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdOne, false, execaSync));83test('result.all is defined, lines, stripFinalNewline, fd-specific both, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdBoth, false, execaSync));84test('result.all is defined, failure, sync', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, true, execaSync));85test('result.all is defined, encoding "buffer", failure, sync', () => testAllBoth(doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execaSync));86test('result.all is defined, lines, failure, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', true, false, true, execaSync));87test('result.all is defined, lines, fd-specific one, failure, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdOne, false, true, execaSync));88test('result.all is defined, lines, fd-specific both, failure, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execaSync));89test('result.all is defined, stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, true, true, execaSync));90test('result.all is defined, stripFinalNewline, fd-specific one, failure, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, fdOne, true, execaSync));91test('result.all is defined, stripFinalNewline, fd-specific both, failure, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, fdBoth, true, execaSync));92test('result.all is defined, encoding "buffer", stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, true, true, execaSync));93test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdOne, true, execaSync));94test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execaSync));95test('result.all is defined, lines, stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, true, true, execaSync));96test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', fdOne, true, true, execaSync));97test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', fdBoth, true, true, execaSync));98test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdOne, true, execaSync));99test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdBoth, true, execaSync));100100test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {101test('result.all shows both `stdout` and `stderr` intermixed', async () => {102 const {all} = await execa('noop-132.js', {all: true});102 t.is(all, '1\n2\n3');103 assert.equal(all, '1\n2\n3');104});105105test.serial('result.all shows both `stdout` and `stderr` not intermixed, sync', t => {106test('result.all shows both `stdout` and `stderr` not intermixed, sync', () => {107 const {all} = execaSync('noop-132.js', {all: true});107 t.is(all, '1\n3\n2');108 assert.equal(all, '1\n3\n2');109});110110const testAllIgnored = async (t, options, execaMethod) => {111const testAllIgnored = async (options, execaMethod) => {112 const {all} = await execaMethod('noop.js');112 t.is(all, undefined);113 assert.equal(all, undefined);114};115115test('result.all is undefined unless opts.all is true', testAllIgnored, {}, execa);116test('result.all is undefined if opts.all is false', testAllIgnored, {all: false}, execa);117test('result.all is undefined if ignored', testAllIgnored, {stdio: 'ignore', all: true}, execa);118test('result.all is undefined unless opts.all is true, sync', testAllIgnored, {}, execaSync);119test('result.all is undefined if opts.all is false, sync', testAllIgnored, {all: false}, execaSync);120test('result.all is undefined if ignored, sync', testAllIgnored, {stdio: 'ignore', all: true}, execaSync);116test('result.all is undefined unless opts.all is true', () => testAllIgnored({}, execa));117test('result.all is undefined if opts.all is false', () => testAllIgnored({all: false}, execa));118test('result.all is undefined if ignored', () => testAllIgnored({stdio: 'ignore', all: true}, execa));119test('result.all is undefined unless opts.all is true, sync', () => testAllIgnored({}, execaSync));120test('result.all is undefined if opts.all is false, sync', () => testAllIgnored({all: false}, execaSync));121test('result.all is undefined if ignored, sync', () => testAllIgnored({stdio: 'ignore', all: true}, execaSync));122122const testAllProperties = async (t, options) => {123const testAllProperties = async options => {124 const subprocess = execa('empty.js', {...options, all: true});124 t.is(subprocess.all.readableObjectMode, false);125 t.is(subprocess.all.readableHighWaterMark, defaultHighWaterMark);125 assert.equal(subprocess.all.readableObjectMode, false);126 assert.equal(subprocess.all.readableHighWaterMark, defaultHighWaterMark);127 await subprocess;128};129129test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});130test('subprocess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});131test('subprocess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});130test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', () => testAllProperties({}));131test('subprocess.all has the right objectMode and highWaterMark - stdout only', () => testAllProperties({stderr: 'ignore'}));132test('subprocess.all has the right objectMode and highWaterMark - stderr only', () => testAllProperties({stdout: 'ignore'}));133133const testAllIgnore = async (t, streamName, otherStreamName) => {134const testAllIgnore = async (streamName, otherStreamName) => {135 const subprocess = execa('noop-both.js', {[otherStreamName]: 'ignore', all: true});135 t.is(subprocess[otherStreamName], null);136 t.not(subprocess[streamName], null);137 t.not(subprocess.all, null);138 t.is(subprocess.all.readableObjectMode, subprocess[streamName].readableObjectMode);139 t.is(subprocess.all.readableHighWaterMark, subprocess[streamName].readableHighWaterMark);136 assert.equal(subprocess[otherStreamName], null);137 assert.notEqual(subprocess[streamName], null);138 assert.notEqual(subprocess.all, null);139 assert.equal(subprocess.all.readableObjectMode, subprocess[streamName].readableObjectMode);140 assert.equal(subprocess.all.readableHighWaterMark, subprocess[streamName].readableHighWaterMark);141142 const result = await subprocess;142 t.is(result[otherStreamName], undefined);143 t.is(result[streamName], foobarString);144 t.is(result.all, foobarString);143 assert.equal(result[otherStreamName], undefined);144 assert.equal(result[streamName], foobarString);145 assert.equal(result.all, foobarString);146};147147test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');148test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');148test('can use all: true with stdout: ignore', () => testAllIgnore('stderr', 'stdout'));149test('can use all: true with stderr: ignore', () => testAllIgnore('stdout', 'stderr'));150150const testAllIgnoreSync = (t, streamName, otherStreamName) => {151const testAllIgnoreSync = (streamName, otherStreamName) => {152 const result = execaSync('noop-both.js', {[otherStreamName]: 'ignore', all: true});152 t.is(result[otherStreamName], undefined);153 t.is(result[streamName], foobarString);154 t.is(result.all, foobarString);153 assert.equal(result[otherStreamName], undefined);154 assert.equal(result[streamName], foobarString);155 assert.equal(result.all, foobarString);156};157157test('can use all: true with stdout: ignore, sync', testAllIgnoreSync, 'stderr', 'stdout');158test('can use all: true with stderr: ignore, sync', testAllIgnoreSync, 'stdout', 'stderr');158test('can use all: true with stdout: ignore, sync', () => testAllIgnoreSync('stderr', 'stdout'));159test('can use all: true with stderr: ignore, sync', () => testAllIgnoreSync('stdout', 'stderr'));160160test('can use all: true with stdout: ignore + stderr: ignore', async t => {161test('can use all: true with stdout: ignore + stderr: ignore', async () => {162 const subprocess = execa('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});162 t.is(subprocess.stdout, null);163 t.is(subprocess.stderr, null);164 t.is(subprocess.all, undefined);163 assert.equal(subprocess.stdout, null);164 assert.equal(subprocess.stderr, null);165 assert.equal(subprocess.all, undefined);166167 const {stdout, stderr, all} = await subprocess;167 t.is(stdout, undefined);168 t.is(stderr, undefined);169 t.is(all, undefined);168 assert.equal(stdout, undefined);169 assert.equal(stderr, undefined);170 assert.equal(all, undefined);171});172172test('can use all: true with stdout: ignore + stderr: ignore, sync', t => {173test('can use all: true with stdout: ignore + stderr: ignore, sync', () => {174 const {stdout, stderr, all} = execaSync('noop-both.js', {stdout: 'ignore', stderr: 'ignore', all: true});174 t.is(stdout, undefined);175 t.is(stderr, undefined);176 t.is(all, undefined);175 assert.equal(stdout, undefined);176 assert.equal(stderr, undefined);177 assert.equal(all, undefined);178});179180// `all` is split into lines when the `lines` option applies to either file descriptor, even when only one of them uses it181const foobarTwoLines = `${foobarString}\n${foobarString}`;182// The fixture writes the same two lines to both `stdout` and `stderr`183const foobarTwoLinesArray = Array.from({length: 4}, () => `${foobarString}\n`);183const testAllBothLines = async (t, lines, execaMethod) => {184const testAllBothLines = async (lines, execaMethod) => {185 const {all} = await execaMethod('noop-both.js', [foobarTwoLines], {all: true, lines, stripFinalNewline: false});185 t.deepEqual(all, foobarTwoLinesArray);186 assert.deepEqual(all, foobarTwoLinesArray);187};188188test('result.all is split into lines when only stdout uses the lines option', testAllBothLines, {stdout: true}, execa);189test('result.all is split into lines when only stderr uses the lines option', testAllBothLines, {stderr: true}, execa);190test('result.all is split into lines when only stdout uses the lines option, sync', testAllBothLines, {stdout: true}, execaSync);191test('result.all is split into lines when only stderr uses the lines option, sync', testAllBothLines, {stderr: true}, execaSync);189test('result.all is split into lines when only stdout uses the lines option', () => testAllBothLines({stdout: true}, execa));190test('result.all is split into lines when only stderr uses the lines option', () => testAllBothLines({stderr: true}, execa));191test('result.all is split into lines when only stdout uses the lines option, sync', () => testAllBothLines({stdout: true}, execaSync));192test('result.all is split into lines when only stderr uses the lines option, sync', () => testAllBothLines({stderr: true}, execaSync));193194// When only one file descriptor is interleaved into `all`, it must follow that one exactly, including its `stripFinalNewline` value194const testAllOneFd = async (t, lines, execaMethod) => {195const testAllOneFd = async (lines, execaMethod) => {196 const {stderr, all} = await execaMethod('noop-both.js', [foobarString], {197 all: true,198 stdout: 'ignore',199 lines,200 stripFinalNewline: {stderr: false},201 });201 t.deepEqual(stderr, lines ? [`${foobarString}\n`] : `${foobarString}\n`);202 t.deepEqual(all, stderr);202 assert.deepEqual(stderr, lines ? [`${foobarString}\n`] : `${foobarString}\n`);203 assert.deepEqual(all, stderr);204};205205test('result.all follows stderr when stdout is ignored', testAllOneFd, false, execa);206test('result.all follows stderr when stdout is ignored, lines', testAllOneFd, true, execa);207test('result.all follows stderr when stdout is ignored, sync', testAllOneFd, false, execaSync);208test('result.all follows stderr when stdout is ignored, lines, sync', testAllOneFd, true, execaSync);206test('result.all follows stderr when stdout is ignored', () => testAllOneFd(false, execa));207test('result.all follows stderr when stdout is ignored, lines', () => testAllOneFd(true, execa));208test('result.all follows stderr when stdout is ignored, sync', () => testAllOneFd(false, execaSync));209test('result.all follows stderr when stdout is ignored, lines, sync', () => testAllOneFd(true, execaSync));210211// `all` is split into lines as soon as the `lines` option applies to either file descriptor, even the one which is not interleaved into `all`211const testAllOneFdOtherLines = async (t, linesFdName, ignoredFdName, stripFinalNewline, execaMethod) => {212const testAllOneFdOtherLines = async (linesFdName, ignoredFdName, stripFinalNewline, execaMethod) => {213 const {all} = await execaMethod('noop-both.js', [foobarString], {214 all: true,215 [ignoredFdName]: 'ignore',216 lines: {[linesFdName]: true},217 stripFinalNewline,218 });218 t.deepEqual(all, [stripFinalNewline ? foobarString : `${foobarString}\n`]);219 assert.deepEqual(all, [stripFinalNewline ? foobarString : `${foobarString}\n`]);220};221221test('result.all is split into lines when only stdout uses the lines option and stderr is ignored', testAllOneFdOtherLines, 'stdout', 'stderr', true, execa);222test('result.all is split into lines when only stdout uses the lines option and stderr is ignored, stripFinalNewline false', testAllOneFdOtherLines, 'stdout', 'stderr', false, execa);223test('result.all is split into lines when only stderr uses the lines option and stdout is ignored', testAllOneFdOtherLines, 'stderr', 'stdout', true, execa);224test('result.all is split into lines when only stdout uses the lines option and stderr is ignored, sync', testAllOneFdOtherLines, 'stdout', 'stderr', true, execaSync);225test('result.all is split into lines when only stderr uses the lines option and stdout is ignored, sync', testAllOneFdOtherLines, 'stderr', 'stdout', true, execaSync);222test('result.all is split into lines when only stdout uses the lines option and stderr is ignored', () => testAllOneFdOtherLines('stdout', 'stderr', true, execa));223test('result.all is split into lines when only stdout uses the lines option and stderr is ignored, stripFinalNewline false', () => testAllOneFdOtherLines('stdout', 'stderr', false, execa));224test('result.all is split into lines when only stderr uses the lines option and stdout is ignored', () => testAllOneFdOtherLines('stderr', 'stdout', true, execa));225test('result.all is split into lines when only stdout uses the lines option and stderr is ignored, sync', () => testAllOneFdOtherLines('stdout', 'stderr', true, execaSync));226test('result.all is split into lines when only stderr uses the lines option and stdout is ignored, sync', () => testAllOneFdOtherLines('stderr', 'stdout', true, execaSync));227228// `splitLinesSync()` passes a non-string chunk straight through, so an absent file descriptor229// must not be split, or it would be reported as a line holding `undefined`.230const testAllNoFd = async (lines, execaMethod) => {231 const {all} = await execaMethod('noop.js', [], {232 all: true,233 lines,234 stdout: 'ignore',235 stderr: 'ignore',236 });237 assert.equal(all, undefined);238};239240test('result.all is undefined when no file descriptor is buffered', () => testAllNoFd(false, execa));241test('result.all is undefined when no file descriptor is buffered, lines', () => testAllNoFd(true, execa));242test('result.all is undefined when no file descriptor is buffered, sync', () => testAllNoFd(false, execaSync));243test('result.all is undefined when no file descriptor is buffered, lines, sync', () => testAllNoFd(true, execaSync));
modified:test/resolve/buffer-end.js+42 added-41 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import test from 'node:test';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {fullStdio, getStdio} from '../helpers/stdio.js';89setFixtureDirectory();1010const testBufferIgnore = async (t, fdNumber, all) => {11 await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));11const testBufferIgnore = async (fdNumber, all) => {12 await assert.doesNotReject(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));13};1414test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);15test('Subprocess buffers stdout, which does not prevent exit if ignored', () => testBufferIgnore(1, false));16test('Subprocess buffers stderr, which does not prevent exit if ignored', () => testBufferIgnore(2, false));17test('Subprocess buffers all, which does not prevent exit if ignored', () => testBufferIgnore(1, true));1818const testBufferNotRead = async (t, fdNumber, all) => {19const testBufferNotRead = async (fdNumber, all) => {20 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});20 await t.notThrowsAsync(subprocess);21 await assert.doesNotReject(subprocess);22};2323test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);24test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', () => testBufferNotRead(1, false));25test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', () => testBufferNotRead(2, false));26test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', () => testBufferNotRead(3, false));27test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', () => testBufferNotRead(1, true));2828const testBufferRead = async (t, fdNumber, all) => {29const testBufferRead = async (fdNumber, all) => {30 const subprocess = execa('max-buffer.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});31 const stream = all ? subprocess.all : subprocess.stdio[fdNumber];32 stream.resume();32 await t.notThrowsAsync(subprocess);33 await assert.doesNotReject(subprocess);34};3535test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);36test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', () => testBufferRead(1, false));37test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', () => testBufferRead(2, false));38test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', () => testBufferRead(3, false));39test('Subprocess buffers all, which does not prevent exit if read and buffer is false', () => testBufferRead(1, true));4040const testBufferExit = async (t, fdNumber, fixtureName, reject) => {41const testBufferExit = async (fdNumber, fixtureName, reject) => {42 const subprocess = execa(fixtureName, [`${fdNumber}`], {...fullStdio, reject});43 await setTimeout(100);44 const {stdio} = await subprocess;44 t.is(stdio[fdNumber], 'foobar');45 assert.equal(stdio[fdNumber], 'foobar');46};4747test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);48test('Subprocess buffers stdout before it is read', () => testBufferExit(1, 'noop-delay.js', true));49test('Subprocess buffers stderr before it is read', () => testBufferExit(2, 'noop-delay.js', true));50test('Subprocess buffers stdio[*] before it is read', () => testBufferExit(3, 'noop-delay.js', true));51test('Subprocess buffers stdout right away, on successfully exit', () => testBufferExit(1, 'noop-fd.js', true));52test('Subprocess buffers stderr right away, on successfully exit', () => testBufferExit(2, 'noop-fd.js', true));53test('Subprocess buffers stdio[*] right away, on successfully exit', () => testBufferExit(3, 'noop-fd.js', true));54test('Subprocess buffers stdout right away, on failure', () => testBufferExit(1, 'noop-fail.js', false));55test('Subprocess buffers stderr right away, on failure', () => testBufferExit(2, 'noop-fail.js', false));56test('Subprocess buffers stdio[*] right away, on failure', () => testBufferExit(3, 'noop-fail.js', false));5757const testBufferDirect = async (t, fdNumber) => {58const testBufferDirect = async fdNumber => {59 const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);60 const data = await once(subprocess.stdio[fdNumber], 'data');60 t.is(data.toString().trim(), 'foobar');61 assert.equal(data.toString().trim(), 'foobar');62 const result = await subprocess;62 t.is(result.stdio[fdNumber], 'foobar');63 assert.equal(result.stdio[fdNumber], 'foobar');64};6565test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);66test('Subprocess buffers stdout right away, even if directly read', () => testBufferDirect(1));67test('Subprocess buffers stderr right away, even if directly read', () => testBufferDirect(2));68test('Subprocess buffers stdio[*] right away, even if directly read', () => testBufferDirect(3));6969const testBufferDestroyOnEnd = async (t, fdNumber) => {70const testBufferDestroyOnEnd = async fdNumber => {71 const subprocess = execa('noop-fd.js', [`${fdNumber}`], fullStdio);72 const result = await subprocess;72 t.is(result.stdio[fdNumber], 'foobar');73 t.true(subprocess.stdio[fdNumber].destroyed);73 assert.equal(result.stdio[fdNumber], 'foobar');74 assert.ok(subprocess.stdio[fdNumber].destroyed);75};7676test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);77test('subprocess.stdout must be read right away', () => testBufferDestroyOnEnd(1));78test('subprocess.stderr must be read right away', () => testBufferDestroyOnEnd(2));79test('subprocess.stdio[*] must be read right away', () => testBufferDestroyOnEnd(3));
modified:test/resolve/exit.js+36 added-34 removed
1import assert from 'node:assert/strict';2import process from 'node:process';2import test from 'ava';3import test from 'node:test';4import {assertRejects} from '../helpers/assert.js';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';78const isWindows = process.platform === 'win32';910setFixtureDirectory();1110test('exitCode is 0 on success', async t => {12test('exitCode is 0 on success', async () => {13 const {exitCode} = await execa('noop.js', ['foo']);12 t.is(exitCode, 0);14 assert.equal(exitCode, 0);15});1615const testExitCode = async (t, expectedExitCode) => {16 const {exitCode, originalMessage, shortMessage, message} = await t.throwsAsync(execa('exit.js', [`${expectedExitCode}`]));17 t.is(exitCode, expectedExitCode);18 t.is(originalMessage, undefined);19 t.is(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);20 t.is(message, shortMessage);17const testExitCode = async expectedExitCode => {18 const {exitCode, originalMessage, shortMessage, message} = await assertRejects(execa('exit.js', [`${expectedExitCode}`]));19 assert.equal(exitCode, expectedExitCode);20 assert.equal(originalMessage, undefined);21 assert.equal(shortMessage, `Command failed with exit code ${expectedExitCode}: exit.js ${expectedExitCode}`);22 assert.equal(message, shortMessage);23};2423test('exitCode is 2', testExitCode, 2);24test('exitCode is 3', testExitCode, 3);25test('exitCode is 4', testExitCode, 4);25test('exitCode is 2', () => testExitCode(2));26test('exitCode is 3', () => testExitCode(3));27test('exitCode is 4', () => testExitCode(4));2829if (!isWindows) {28 test('error.signal is SIGINT', async t => {30 test('error.signal is SIGINT', async () => {31 const subprocess = execa('forever.js');3233 process.kill(subprocess.pid, 'SIGINT');3433 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});34 t.is(signal, 'SIGINT');35 const {signal} = await assertRejects(subprocess, {message: /was killed with SIGINT/});36 assert.equal(signal, 'SIGINT');37 });3837 test('error.signalDescription is defined', async t => {39 test('error.signalDescription is defined', async () => {40 const subprocess = execa('forever.js');4142 process.kill(subprocess.pid, 'SIGINT');4342 const {signalDescription} = await t.throwsAsync(subprocess, {message: /User interruption with CTRL-C/});43 t.is(signalDescription, 'User interruption with CTRL-C');44 const {signalDescription} = await assertRejects(subprocess, {message: /User interruption with CTRL-C/});45 assert.equal(signalDescription, 'User interruption with CTRL-C');46 });4746 test('error.signal is SIGTERM', async t => {48 test('error.signal is SIGTERM', async () => {49 const subprocess = execa('forever.js');5051 process.kill(subprocess.pid, 'SIGTERM');5251 const {signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGTERM/});52 t.is(signal, 'SIGTERM');53 const {signal} = await assertRejects(subprocess, {message: /was killed with SIGTERM/});54 assert.equal(signal, 'SIGTERM');55 });5655 test('error.signal uses killSignal', async t => {56 const {signal} = await t.throwsAsync(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: /timed out after/}));57 t.is(signal, 'SIGINT');57 test('error.signal uses killSignal', async () => {58 const {signal} = await assertRejects(execa('forever.js', {killSignal: 'SIGINT', timeout: 1, message: /timed out after/}));59 assert.equal(signal, 'SIGINT');60 });6160 test('exitCode is undefined on signal termination', async t => {62 test('exitCode is undefined on signal termination', async () => {63 const subprocess = execa('forever.js');6465 process.kill(subprocess.pid);6665 const {exitCode} = await t.throwsAsync(subprocess);66 t.is(exitCode, undefined);67 const {exitCode} = await assertRejects(subprocess);68 assert.equal(exitCode, undefined);69 });70}7170test('result.signal is undefined for successful execution', async t => {72test('result.signal is undefined for successful execution', async () => {73 const {signal} = await execa('noop.js');72 t.is(signal, undefined);74 assert.equal(signal, undefined);75});7675test('result.signal is undefined if subprocess failed, but was not killed', async t => {76 const {signal} = await t.throwsAsync(execa('fail.js'));77 t.is(signal, undefined);77test('result.signal is undefined if subprocess failed, but was not killed', async () => {78 const {signal} = await assertRejects(execa('fail.js'));79 assert.equal(signal, undefined);80});8180test('result.signalDescription is undefined for successful execution', async t => {82test('result.signalDescription is undefined for successful execution', async () => {83 const {signalDescription} = await execa('noop.js');82 t.is(signalDescription, undefined);84 assert.equal(signalDescription, undefined);85});
modified:test/resolve/no-buffer.js+132 added-130 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';2import test from 'ava';3import test from 'node:test';4import getStream from 'get-stream';5import {assertRejects, assertLike} from '../helpers/assert.js';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {fullStdio} from '../helpers/stdio.js';9import {foobarString, foobarUppercase, foobarUppercaseUint8Array} from '../helpers/input.js';10import {resultGenerator, uppercaseGenerator, uppercaseBufferGenerator} from '../helpers/generator.js';1112setFixtureDirectory();1312const testLateStream = async (t, fdNumber, all) => {14const testLateStream = async (fdNumber, all) => {15 const subprocess = execa('noop-fd-ipc.js', [`${fdNumber}`, foobarString], {16 ...fullStdio,17 ipc: true,18 buffer: false,
5 unmodified lines
24 all ? getStream(subprocess.all) : undefined,25 subprocess,26 ]);2726 t.is(output, '');28 assert.equal(output, '');2930 if (all) {29 t.is(allOutput, '');31 assert.equal(allOutput, '');32 }33};3433test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);34test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);35test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);36test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);35test('Lacks some data when stdout is read too late `buffer` set to `false`', () => testLateStream(1, false));36test('Lacks some data when stderr is read too late `buffer` set to `false`', () => testLateStream(2, false));37test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', () => testLateStream(3, false));38test('Lacks some data when all is read too late `buffer` set to `false`', () => testLateStream(1, true));3940const getFirstDataEvent = async stream => {41 const [output] = await once(stream, 'data');42 return output.toString();43};4443// eslint-disable-next-line max-params44const testIterationBuffer = async (t, fdNumber, buffer, useDataEvents, all) => {45const testIterationBuffer = async (fdNumber, buffer, useDataEvents, all) => {46 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], {...fullStdio, buffer, all});47 const getOutput = useDataEvents ? getFirstDataEvent : getStream;48 const [result, output, allOutput] = await Promise.all([49 subprocess,
2 unmodified lines
52 ]);5354 const expectedResult = buffer ? foobarString : undefined;5555 t.is(result.stdio[fdNumber], expectedResult);56 t.is(output, foobarString);56 assert.equal(result.stdio[fdNumber], expectedResult);57 assert.equal(output, foobarString);5858 if (all) {59 t.is(result.all, expectedResult);60 t.is(allOutput, foobarString);59 if (!all) {60 return;61 }6263 assert.equal(result.all, expectedResult);64 assert.equal(allOutput, foobarString);65};6664test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);65test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);66test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);67test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);68test('Can iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);69test('Can iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);70test('Can iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);71test('Can iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);72test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);73test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);74test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);75test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);76test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);77test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);78test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);79test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);67test('Can iterate stdout when `buffer` set to `false`', () => testIterationBuffer(1, false, false, false));68test('Can iterate stderr when `buffer` set to `false`', () => testIterationBuffer(2, false, false, false));69test('Can iterate stdio[*] when `buffer` set to `false`', () => testIterationBuffer(3, false, false, false));70test('Can iterate all when `buffer` set to `false`', () => testIterationBuffer(1, false, false, true));71test('Can iterate stdout when `buffer` set to `true`', () => testIterationBuffer(1, true, false, false));72test('Can iterate stderr when `buffer` set to `true`', () => testIterationBuffer(2, true, false, false));73test('Can iterate stdio[*] when `buffer` set to `true`', () => testIterationBuffer(3, true, false, false));74test('Can iterate all when `buffer` set to `true`', () => testIterationBuffer(1, true, false, true));75test('Can listen to `data` events on stdout when `buffer` set to `false`', () => testIterationBuffer(1, false, true, false));76test('Can listen to `data` events on stderr when `buffer` set to `false`', () => testIterationBuffer(2, false, true, false));77test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', () => testIterationBuffer(3, false, true, false));78test('Can listen to `data` events on all when `buffer` set to `false`', () => testIterationBuffer(1, false, true, true));79test('Can listen to `data` events on stdout when `buffer` set to `true`', () => testIterationBuffer(1, true, true, false));80test('Can listen to `data` events on stderr when `buffer` set to `true`', () => testIterationBuffer(2, true, true, false));81test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', () => testIterationBuffer(3, true, true, false));82test('Can listen to `data` events on all when `buffer` set to `true`', () => testIterationBuffer(1, true, true, true));8381const testNoBufferStreamError = async (t, fdNumber, all) => {84const testNoBufferStreamError = async (fdNumber, all) => {85 const subprocess = execa('noop-fd.js', [`${fdNumber}`], {...fullStdio, buffer: false, all});86 const stream = all ? subprocess.all : subprocess.stdio[fdNumber];87 const cause = new Error('test');88 stream.destroy(cause);86 t.like(await t.throwsAsync(subprocess), {cause});89 assertLike(await assertRejects(subprocess), {cause});90};9189test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);90test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);91test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);92test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);92test('Listen to stdout errors even when `buffer` is `false`', () => testNoBufferStreamError(1, false));93test('Listen to stderr errors even when `buffer` is `false`', () => testNoBufferStreamError(2, false));94test('Listen to stdio[*] errors even when `buffer` is `false`', () => testNoBufferStreamError(3, false));95test('Listen to all errors even when `buffer` is `false`', () => testNoBufferStreamError(1, true));9694const testOutput = async (t, buffer, execaMethod) => {97const testOutput = async (buffer, execaMethod) => {98 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {buffer});96 t.is(stdout, foobarString);99 assert.equal(stdout, foobarString);100};10199test('buffer: true returns output', testOutput, true, execa);100test('buffer: true returns output, fd-specific', testOutput, {stderr: false}, execa);101test('buffer: default returns output', testOutput, undefined, execa);102test('buffer: default returns output, fd-specific', testOutput, {}, execa);102test('buffer: true returns output', () => testOutput(true, execa));103test('buffer: true returns output, fd-specific', () => testOutput({stderr: false}, execa));104test('buffer: default returns output', () => testOutput(undefined, execa));105test('buffer: default returns output, fd-specific', () => testOutput({}, execa));106104const testNoOutput = async (t, stdioOption, buffer, execaMethod) => {107const testNoOutput = async (stdioOption, buffer, execaMethod) => {108 const {stdout} = await execaMethod('noop.js', {stdout: stdioOption, buffer});106 t.is(stdout, undefined);109 assert.equal(stdout, undefined);110};111109test('buffer: false does not return output', testNoOutput, 'pipe', false, execa);110test('buffer: false does not return output, fd-specific', testNoOutput, 'pipe', {stdout: false}, execa);111test('buffer: false does not return output, stdout undefined', testNoOutput, undefined, false, execa);112test('buffer: false does not return output, stdout null', testNoOutput, null, false, execa);113test('buffer: false does not return output, stdout ["pipe"]', testNoOutput, ['pipe'], false, execa);114test('buffer: false does not return output, stdout [undefined]', testNoOutput, [undefined], false, execa);115test('buffer: false does not return output, stdout [null]', testNoOutput, [null], false, execa);116test('buffer: false does not return output, stdout ["pipe", undefined]', testNoOutput, ['pipe', undefined], false, execa);117test('buffer: false does not return output, sync', testNoOutput, 'pipe', false, execaSync);118test('buffer: false does not return output, fd-specific, sync', testNoOutput, 'pipe', {stdout: false}, execaSync);119test('buffer: false does not return output, stdout undefined, sync', testNoOutput, undefined, false, execaSync);120test('buffer: false does not return output, stdout null, sync', testNoOutput, null, false, execaSync);121test('buffer: false does not return output, stdout ["pipe"], sync', testNoOutput, ['pipe'], false, execaSync);122test('buffer: false does not return output, stdout [undefined], sync', testNoOutput, [undefined], false, execaSync);123test('buffer: false does not return output, stdout [null], sync', testNoOutput, [null], false, execaSync);124test('buffer: false does not return output, stdout ["pipe", undefined], sync', testNoOutput, ['pipe', undefined], false, execaSync);112test('buffer: false does not return output', () => testNoOutput('pipe', false, execa));113test('buffer: false does not return output, fd-specific', () => testNoOutput('pipe', {stdout: false}, execa));114test('buffer: false does not return output, stdout undefined', () => testNoOutput(undefined, false, execa));115test('buffer: false does not return output, stdout null', () => testNoOutput(null, false, execa));116test('buffer: false does not return output, stdout ["pipe"]', () => testNoOutput(['pipe'], false, execa));117test('buffer: false does not return output, stdout [undefined]', () => testNoOutput([undefined], false, execa));118test('buffer: false does not return output, stdout [null]', () => testNoOutput([null], false, execa));119test('buffer: false does not return output, stdout ["pipe", undefined]', () => testNoOutput(['pipe', undefined], false, execa));120test('buffer: false does not return output, sync', () => testNoOutput('pipe', false, execaSync));121test('buffer: false does not return output, fd-specific, sync', () => testNoOutput('pipe', {stdout: false}, execaSync));122test('buffer: false does not return output, stdout undefined, sync', () => testNoOutput(undefined, false, execaSync));123test('buffer: false does not return output, stdout null, sync', () => testNoOutput(null, false, execaSync));124test('buffer: false does not return output, stdout ["pipe"], sync', () => testNoOutput(['pipe'], false, execaSync));125test('buffer: false does not return output, stdout [undefined], sync', () => testNoOutput([undefined], false, execaSync));126test('buffer: false does not return output, stdout [null], sync', () => testNoOutput([null], false, execaSync));127test('buffer: false does not return output, stdout ["pipe", undefined], sync', () => testNoOutput(['pipe', undefined], false, execaSync));128129/*130With `buffer: false`, additional file descriptors must still be passed to the subprocess.131With synchronous methods, `ignore` is used to avoid buffering, but that only redirects `stdout`/`stderr` to `/dev/null`.132For other file descriptors, it does not pass them at all, which would make the subprocess fail when writing to them.133*/131const testNoOutputFdStays = async (t, buffer, execaMethod) => {134const testNoOutputFdStays = async (buffer, execaMethod) => {135 const {stdio, failed} = await execaMethod('noop-fd.js', ['3', foobarString], {...fullStdio, buffer});133 t.false(failed);134 t.is(stdio[3], undefined);136 assert.equal(failed, false);137 assert.equal(stdio[3], undefined);138};139137test('buffer: false keeps stdio[*] open', testNoOutputFdStays, false, execa);138test('buffer: false keeps stdio[*] open, fd-specific', testNoOutputFdStays, {fd3: false}, execa);139test('buffer: false keeps stdio[*] open, sync', testNoOutputFdStays, false, execaSync);140test('buffer: false keeps stdio[*] open, fd-specific, sync', testNoOutputFdStays, {fd3: false}, execaSync);140test('buffer: false keeps stdio[*] open', () => testNoOutputFdStays(false, execa));141test('buffer: false keeps stdio[*] open, fd-specific', () => testNoOutputFdStays({fd3: false}, execa));142test('buffer: false keeps stdio[*] open, sync', () => testNoOutputFdStays(false, execaSync));143test('buffer: false keeps stdio[*] open, fd-specific, sync', () => testNoOutputFdStays({fd3: false}, execaSync));144142const testNoOutputFail = async (t, execaMethod) => {145const testNoOutputFail = async execaMethod => {146 const {exitCode, stdout} = await execaMethod('fail.js', {buffer: false, reject: false});144 t.is(exitCode, 2);145 t.is(stdout, undefined);147 assert.equal(exitCode, 2);148 assert.equal(stdout, undefined);149};150148test('buffer: false does not return output, failure', testNoOutputFail, execa);149test('buffer: false does not return output, failure, sync', testNoOutputFail, execaSync);151test('buffer: false does not return output, failure', () => testNoOutputFail(execa));152test('buffer: false does not return output, failure, sync', () => testNoOutputFail(execaSync));153151// eslint-disable-next-line max-params152const testNoOutputAll = async (t, buffer, bufferStdout, bufferStderr, execaMethod) => {154const testNoOutputAll = async (buffer, bufferStdout, bufferStderr, execaMethod) => {155 const {stdout, stderr, all} = await execaMethod('noop-both.js', {all: true, buffer, stripFinalNewline: false});154 t.is(stdout, bufferStdout ? `${foobarString}\n` : undefined);155 t.is(stderr, bufferStderr ? `${foobarString}\n` : undefined);156 assert.equal(stdout, bufferStdout ? `${foobarString}\n` : undefined);157 assert.equal(stderr, bufferStderr ? `${foobarString}\n` : undefined);158 const stdoutStderr = [stdout, stderr].filter(Boolean);157 t.is(all, stdoutStderr.length === 0 ? undefined : stdoutStderr.join(''));159 assert.equal(all, stdoutStderr.length === 0 ? undefined : stdoutStderr.join(''));160};161160test('buffer: {}, all: true', testNoOutputAll, {}, true, true, execa);161test('buffer: {stdout: false}, all: true', testNoOutputAll, {stdout: false}, false, true, execa);162test('buffer: {stderr: false}, all: true', testNoOutputAll, {stderr: false}, true, false, execa);163test('buffer: {all: false}, all: true', testNoOutputAll, {all: false}, false, false, execa);164test('buffer: {}, all: true, sync', testNoOutputAll, {}, true, true, execaSync);165test('buffer: {stdout: false}, all: true, sync', testNoOutputAll, {stdout: false}, false, true, execaSync);166test('buffer: {stderr: false}, all: true, sync', testNoOutputAll, {stderr: false}, true, false, execaSync);167test('buffer: {all: false}, all: true, sync', testNoOutputAll, {all: false}, false, false, execaSync);162test('buffer: {}, all: true', () => testNoOutputAll({}, true, true, execa));163test('buffer: {stdout: false}, all: true', () => testNoOutputAll({stdout: false}, false, true, execa));164test('buffer: {stderr: false}, all: true', () => testNoOutputAll({stderr: false}, true, false, execa));165test('buffer: {all: false}, all: true', () => testNoOutputAll({all: false}, false, false, execa));166test('buffer: {}, all: true, sync', () => testNoOutputAll({}, true, true, execaSync));167test('buffer: {stdout: false}, all: true, sync', () => testNoOutputAll({stdout: false}, false, true, execaSync));168test('buffer: {stderr: false}, all: true, sync', () => testNoOutputAll({stderr: false}, true, false, execaSync));169test('buffer: {all: false}, all: true, sync', () => testNoOutputAll({all: false}, false, false, execaSync));170171// `result.all` only contains the buffered file descriptors, so its `stripFinalNewline` must only follow those170const testNoOutputAllStripFinalNewline = async (t, buffer, stripFinalNewline, execaMethod) => {172const testNoOutputAllStripFinalNewline = async (buffer, stripFinalNewline, execaMethod) => {173 const {all} = await execaMethod('noop-both.js', {all: true, buffer, stripFinalNewline});172 t.is(all, `${foobarString}\n`);174 assert.equal(all, `${foobarString}\n`);175};176175test('buffer: {stderr: false} only follows the buffered "stripFinalNewline" in result.all', testNoOutputAllStripFinalNewline, {stderr: false}, {stdout: false, stderr: true}, execa);176test('buffer: {stdout: false} only follows the buffered "stripFinalNewline" in result.all', testNoOutputAllStripFinalNewline, {stdout: false}, {stdout: true, stderr: false}, execa);177test('buffer: {stderr: false} only follows the buffered "stripFinalNewline" in result.all, sync', testNoOutputAllStripFinalNewline, {stderr: false}, {stdout: false, stderr: true}, execaSync);178test('buffer: {stdout: false} only follows the buffered "stripFinalNewline" in result.all, sync', testNoOutputAllStripFinalNewline, {stdout: false}, {stdout: true, stderr: false}, execaSync);177test('buffer: {stderr: false} only follows the buffered "stripFinalNewline" in result.all', () => testNoOutputAllStripFinalNewline({stderr: false}, {stdout: false, stderr: true}, execa));178test('buffer: {stdout: false} only follows the buffered "stripFinalNewline" in result.all', () => testNoOutputAllStripFinalNewline({stdout: false}, {stdout: true, stderr: false}, execa));179test('buffer: {stderr: false} only follows the buffered "stripFinalNewline" in result.all, sync', () => testNoOutputAllStripFinalNewline({stderr: false}, {stdout: false, stderr: true}, execaSync));180test('buffer: {stdout: false} only follows the buffered "stripFinalNewline" in result.all, sync', () => testNoOutputAllStripFinalNewline({stdout: false}, {stdout: true, stderr: false}, execaSync));181182// `result.all` requires the `all` option, even when only one of the two file descriptors is buffered181const testNoAllWithoutOption = async (t, buffer, execaMethod) => {183const testNoAllWithoutOption = async (buffer, execaMethod) => {184 const {all} = await execaMethod('noop-both.js', {buffer, stripFinalNewline: false});183 t.is(all, undefined);185 assert.equal(all, undefined);186};187186test('buffer: {stdout: false} does not set result.all', testNoAllWithoutOption, {stdout: false}, execa);187test('buffer: {stderr: false} does not set result.all', testNoAllWithoutOption, {stderr: false}, execa);188test('buffer: {stdout: false} does not set result.all, sync', testNoAllWithoutOption, {stdout: false}, execaSync);189test('buffer: {stderr: false} does not set result.all, sync', testNoAllWithoutOption, {stderr: false}, execaSync);188test('buffer: {stdout: false} does not set result.all', () => testNoAllWithoutOption({stdout: false}, execa));189test('buffer: {stderr: false} does not set result.all', () => testNoAllWithoutOption({stderr: false}, execa));190test('buffer: {stdout: false} does not set result.all, sync', () => testNoAllWithoutOption({stdout: false}, execaSync));191test('buffer: {stderr: false} does not set result.all, sync', () => testNoAllWithoutOption({stderr: false}, execaSync));192191const testTransform = async (t, objectMode, execaMethod) => {193const testTransform = async (objectMode, execaMethod) => {194 const lines = [];195 const {stdout} = await execaMethod('noop.js', {196 buffer: false,197 stdout: [uppercaseGenerator(objectMode), resultGenerator(lines)(objectMode)],198 });197 t.is(stdout, undefined);198 t.deepEqual(lines, [foobarUppercase]);199 assert.equal(stdout, undefined);200 assert.deepEqual(lines, [foobarUppercase]);201};202201test('buffer: false still runs transforms', testTransform, false, execa);202test('buffer: false still runs transforms, objectMode', testTransform, true, execa);203test('buffer: false still runs transforms, sync', testTransform, false, execaSync);204test('buffer: false still runs transforms, objectMode, sync', testTransform, true, execaSync);203test('buffer: false still runs transforms', () => testTransform(false, execa));204test('buffer: false still runs transforms, objectMode', () => testTransform(true, execa));205test('buffer: false still runs transforms, sync', () => testTransform(false, execaSync));206test('buffer: false still runs transforms, objectMode, sync', () => testTransform(true, execaSync));207206const testTransformBinary = async (t, objectMode, execaMethod) => {208const testTransformBinary = async (objectMode, execaMethod) => {209 const lines = [];210 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {211 buffer: false,212 stdout: [uppercaseBufferGenerator(objectMode, true), resultGenerator(lines)(objectMode)],213 encoding: 'buffer',214 });213 t.is(stdout, undefined);214 t.deepEqual(lines, [foobarUppercaseUint8Array]);215 assert.equal(stdout, undefined);216 assert.deepEqual(lines, [foobarUppercaseUint8Array]);217};218217test('buffer: false still runs transforms, encoding "buffer"', testTransformBinary, false, execa);218test('buffer: false still runs transforms, encoding "buffer", objectMode', testTransformBinary, true, execa);219test('buffer: false still runs transforms, encoding "buffer", sync', testTransformBinary, false, execaSync);220test('buffer: false still runs transforms, encoding "buffer", objectMode, sync', testTransformBinary, true, execaSync);219test('buffer: false still runs transforms, encoding "buffer"', () => testTransformBinary(false, execa));220test('buffer: false still runs transforms, encoding "buffer", objectMode', () => testTransformBinary(true, execa));221test('buffer: false still runs transforms, encoding "buffer", sync', () => testTransformBinary(false, execaSync));222test('buffer: false still runs transforms, encoding "buffer", objectMode, sync', () => testTransformBinary(true, execaSync));223222const testStreamEnd = async (t, fdNumber, buffer) => {224const testStreamEnd = async (fdNumber, buffer) => {225 const subprocess = execa('wrong command', {...fullStdio, buffer});226 await Promise.all([225 t.throwsAsync(subprocess, {message: /wrong command/}),227 assertRejects(subprocess, {message: /wrong command/}),228 once(subprocess.stdio[fdNumber], 'end'),229 ]);230};231230test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);231test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);232test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);233test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);234test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);235test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);232test('buffer: false > emits end event on stdout when promise is rejected', () => testStreamEnd(1, false));233test('buffer: false > emits end event on stderr when promise is rejected', () => testStreamEnd(2, false));234test('buffer: false > emits end event on stdio[*] when promise is rejected', () => testStreamEnd(3, false));235test('buffer: true > emits end event on stdout when promise is rejected', () => testStreamEnd(1, true));236test('buffer: true > emits end event on stderr when promise is rejected', () => testStreamEnd(2, true));237test('buffer: true > emits end event on stdio[*] when promise is rejected', () => testStreamEnd(3, true));238239// When only one file descriptor is buffered, `result.all` is read from its own stream, not from `subprocess.all`.240// `subprocess.all` still merges both file descriptors, so it must be drained. Otherwise, it fills up and applies backpressure on them, hanging the subprocess which is still writing to them.241const LARGE_OUTPUT = 1e6;242241const testNoBufferAllBackpressure = async (t, fdNumber, buffer) => {243const testNoBufferAllBackpressure = async (fdNumber, buffer) => {244 const {exitCode, all} = await execa('noop-fd-large.js', [`${fdNumber}`, `${LARGE_OUTPUT}`], {all: true, buffer});243 t.is(exitCode, 0);244 t.is(all.length, LARGE_OUTPUT);245 assert.equal(exitCode, 0);246 assert.equal(all.length, LARGE_OUTPUT);247};248247// Without the fix, the subprocess hangs, so it is given a `timeout` to turn the hang into a failed assertion248test('all: true does not hang on a large stdout with buffer: {stderr: false}', testNoBufferAllBackpressure, 1, {stderr: false});249test('all: true does not hang on a large stderr with buffer: {stdout: false}', testNoBufferAllBackpressure, 2, {stdout: false});249// Without the fix, the subprocess hangs until the test times out250test('all: true does not hang on a large stdout with buffer: {stderr: false}', () => testNoBufferAllBackpressure(1, {stderr: false}));251test('all: true does not hang on a large stderr with buffer: {stdout: false}', () => testNoBufferAllBackpressure(2, {stdout: false}));252253// `subprocess.all` must keep interleaving a file descriptor which is not buffered, even though Execa does not read it itself252const testAllStreamWithNoBuffer = async (t, fdNumber, optionName) => {254const testAllStreamWithNoBuffer = async (fdNumber, optionName) => {255 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], {all: true, buffer: {[optionName]: false}});256 const [, allContents] = await Promise.all([subprocess, getStream(subprocess.all)]);255 t.is(allContents, foobarString);257 assert.equal(allContents, foobarString);258};259258test('subprocess.all includes an unbuffered stdout', testAllStreamWithNoBuffer, 1, 'stdout');259test('subprocess.all includes an unbuffered stderr', testAllStreamWithNoBuffer, 2, 'stderr');260test('subprocess.all includes an unbuffered stdout', () => testAllStreamWithNoBuffer(1, 'stdout'));261test('subprocess.all includes an unbuffered stderr', () => testAllStreamWithNoBuffer(2, 'stderr'));
modified:test/resolve/stdio.js+66 added-54 removed
1import assert from 'node:assert/strict';2import {setTimeout} from 'node:timers/promises';2import test from 'ava';3import {execa} from '../../index.js';3import test from 'node:test';4import {assertRejects} from '../helpers/assert.js';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {8 fullStdio,9 getStdio,
8 unmodified lines
18 ? getStdio(3, [new Uint8Array(), infiniteGenerator()])19 : {});20const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});2120const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {21 t.is(exitCode, 0);22 t.is(signal, undefined);23 t.false(isTerminated);24 t.true(failed);22const assertStreamInputError = ({exitCode, signal, isTerminated, failed}) => {23 assert.equal(exitCode, 0);24 assert.equal(signal, undefined);25 assert.equal(isTerminated, false);26 assert.equal(failed, true);27};2827const assertStreamOutputError = (t, fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {29const assertStreamOutputError = (fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {30 if (fdNumber !== 3) {29 t.is(exitCode, 1);31 assert.equal(exitCode, 1);32 }3332 t.is(signal, undefined);33 t.false(isTerminated);34 t.true(failed);34 assert.equal(signal, undefined);35 assert.equal(isTerminated, false);36 assert.equal(failed, true);3736 assertEpipe(t, stderr, fdNumber);38 assertEpipe(stderr, fdNumber);39};4039const testStreamInputAbort = async (t, fdNumber) => {41const testStreamInputAbort = async fdNumber => {42 const subprocess = getStreamInputSubprocess(fdNumber);43 subprocess.stdio[fdNumber].destroy();42 const error = await t.throwsAsync(subprocess, prematureClose);43 assertStreamInputError(t, error);44 const error = await assertRejects(subprocess, prematureClose);45 assertStreamInputError(error);46};4746test('Aborting stdin should not make the subprocess exit', testStreamInputAbort, 0);47test('Aborting input stdio[*] should not make the subprocess exit', testStreamInputAbort, 3);48test('Aborting stdin should not make the subprocess exit', () => testStreamInputAbort(0));49test('Aborting input stdio[*] should not make the subprocess exit', () => testStreamInputAbort(3));5049const testStreamOutputAbort = async (t, fdNumber) => {51const testStreamOutputAbort = async fdNumber => {52 const subprocess = getStreamOutputSubprocess(fdNumber);53 subprocess.stdio[fdNumber].destroy();52 const error = await t.throwsAsync(subprocess);53 assertStreamOutputError(t, fdNumber, error);54 const error = await assertRejects(subprocess);55 assertStreamOutputError(fdNumber, error);56};5756test('Aborting stdout should not make the subprocess exit', testStreamOutputAbort, 1);57test('Aborting stderr should not make the subprocess exit', testStreamOutputAbort, 2);58test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);58test('Aborting stdout should not make the subprocess exit', () => testStreamOutputAbort(1));59test('Aborting stderr should not make the subprocess exit', () => testStreamOutputAbort(2));60test('Aborting output stdio[*] should not make the subprocess exit', () => testStreamOutputAbort(3));6160const testStreamInputDestroy = async (t, fdNumber) => {62const testStreamInputDestroy = async fdNumber => {63 const subprocess = getStreamInputSubprocess(fdNumber);64 const cause = new Error('test');65 subprocess.stdio[fdNumber].destroy(cause);64 const error = await t.throwsAsync(subprocess);65 t.is(error.cause, cause);66 assertStreamInputError(t, error);66 const error = await assertRejects(subprocess);67 assert.equal(error.cause, cause);68 assertStreamInputError(error);69};7069test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);70test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);71test('Destroying stdin should not make the subprocess exit', () => testStreamInputDestroy(0));72test('Destroying input stdio[*] should not make the subprocess exit', () => testStreamInputDestroy(3));7372const testStreamOutputDestroy = async (t, fdNumber) => {74const testStreamOutputDestroy = async fdNumber => {75 const subprocess = getStreamOutputSubprocess(fdNumber);76 const cause = new Error('test');77 subprocess.stdio[fdNumber].destroy(cause);76 const error = await t.throwsAsync(subprocess);77 t.is(error.cause, cause);78 assertStreamOutputError(t, fdNumber, error);78 const error = await assertRejects(subprocess);79 assert.equal(error.cause, cause);80 assertStreamOutputError(fdNumber, error);81};8281test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);82test('Destroying stderr should not make the subprocess exit', testStreamOutputDestroy, 2);83test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);83test('Destroying stdout should not make the subprocess exit', () => testStreamOutputDestroy(1));84test('Destroying stderr should not make the subprocess exit', () => testStreamOutputDestroy(2));85test('Destroying output stdio[*] should not make the subprocess exit', () => testStreamOutputDestroy(3));8685const testStreamInputError = async (t, fdNumber) => {87const testStreamInputError = async fdNumber => {88 const subprocess = getStreamInputSubprocess(fdNumber);89 const cause = new Error('test');90 const stream = subprocess.stdio[fdNumber];91 stream.emit('error', cause);92 stream.end();91 const error = await t.throwsAsync(subprocess);92 t.is(error.cause, cause);93 assertStreamInputError(t, error);93 const error = await assertRejects(subprocess);94 assert.equal(error.cause, cause);95 assertStreamInputError(error);96};9796test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);97test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);98test('Errors on stdin should not make the subprocess exit', () => testStreamInputError(0));99test('Errors on input stdio[*] should not make the subprocess exit', () => testStreamInputError(3));10099const testStreamOutputError = async (t, fdNumber) => {101const testStreamOutputError = async fdNumber => {102 const subprocess = getStreamOutputSubprocess(fdNumber);103 const cause = new Error('test');104 const stream = subprocess.stdio[fdNumber];105 stream.emit('error', cause);104 const error = await t.throwsAsync(subprocess);105 t.is(error.cause, cause);106 assertStreamOutputError(t, fdNumber, error);106 const error = await assertRejects(subprocess);107 assert.equal(error.cause, cause);108 assertStreamOutputError(fdNumber, error);109};110109test('Errors on stdout should make the subprocess exit', testStreamOutputError, 1);110test('Errors on stderr should make the subprocess exit', testStreamOutputError, 2);111test('Errors on output stdio[*] should make the subprocess exit', testStreamOutputError, 3);111test('Errors on stdout should make the subprocess exit', () => testStreamOutputError(1));112test('Errors on stderr should make the subprocess exit', () => testStreamOutputError(2));113test('Errors on output stdio[*] should make the subprocess exit', () => testStreamOutputError(3));114113const testWaitOnStreamEnd = async (t, fdNumber) => {115const testWaitOnStreamEnd = async fdNumber => {116 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], fullStdio);117 await setTimeout(100);118 subprocess.stdio[fdNumber].end('foobar');119 const {stdout} = await subprocess;118 t.is(stdout, 'foobar');120 assert.equal(stdout, 'foobar');121};122121test('Subprocess waits on stdin before exiting', testWaitOnStreamEnd, 0);122test('Subprocess waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);123test('Subprocess waits on stdin before exiting', () => testWaitOnStreamEnd(0));124test('Subprocess waits on stdio[*] before exiting', () => testWaitOnStreamEnd(3));125126// A failed spawn has no output at all, so `result.stdio` must still have one entry per127// file descriptor, the same as a successful spawn and the same as asynchronous methods.128const testFailedSpawnStdioLength = async (stdio, expectedLength, execaMethod) => {129 const {stdio: stdioResult} = await execaMethod('unknown-file.js', {stdio, reject: false});130 assert.equal(stdioResult.length, expectedLength);131};132133test('result.stdio has one entry per file descriptor when the spawn fails', () => testFailedSpawnStdioLength(fullStdio.stdio, 4, execa));134test('result.stdio has one entry per file descriptor when the spawn fails, sync', () => testFailedSpawnStdioLength(fullStdio.stdio, 4, execaSync));
modified:test/resolve/wait-abort.js+61 added-62 removed
1import assert from 'node:assert/strict';2import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import test from 'node:test';4import {assertRejects, assertLike} from '../helpers/assert.js';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {prematureClose} from '../helpers/stdio.js';8import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';
7 unmodified lines
16setFixtureDirectory();1718const noop = () => {};1918// eslint-disable-next-line max-params19const testStreamAbortWait = async (t, streamMethod, stream, fdNumber, useTransform) => {20const testStreamAbortWait = async (streamMethod, stream, fdNumber, useTransform) => {21 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));22 streamMethod({stream, subprocess, fdNumber});23 subprocess.stdin.end();24 await setImmediate();25 stream.destroy();2627 const {stdout} = await subprocess;27 t.is(stdout, '');28 t.true(stream.destroyed);28 assert.equal(stdout, '');29 assert.equal(stream.destroyed, true);30};3131test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);32test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);33test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);34test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);35test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);36test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);32test('Keeps running when stdin option is used and subprocess.stdin ends', () => testStreamAbortWait(noop, noopReadable(), 0, false));33test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', () => testStreamAbortWait(noop, noopDuplex(), 0, false));34test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', () => testStreamAbortWait(noop, noopReadable(), 3, false));35test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', () => testStreamAbortWait(noop, noopReadable(), 0, true));36test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', () => testStreamAbortWait(noop, noopDuplex(), 0, true));37test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', () => testStreamAbortWait(noop, noopReadable(), 3, true));3838// eslint-disable-next-line max-params39const testStreamAbortSuccess = async (t, streamMethod, stream, fdNumber, useTransform) => {39const testStreamAbortSuccess = async (streamMethod, stream, fdNumber, useTransform) => {40 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));41 streamMethod({stream, subprocess, fdNumber});42 subprocess.stdin.end();4344 const {stdout} = await subprocess;45 t.is(stdout, '');46 t.true(stream.destroyed);45 assert.equal(stdout, '');46 assert.equal(stream.destroyed, true);47};4849test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);50test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);51test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);52test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);53test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);54test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);55test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);56test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);57test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);58test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);59test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);60test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);61test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);62test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);63test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);64test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);65test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);66test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);67test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);68test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);69test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);70test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);71test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);72test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);49test('Passes when stdin option aborts', () => testStreamAbortSuccess(destroyOptionStream, noopReadable(), 0, false));50test('Passes when stdin option Duplex aborts', () => testStreamAbortSuccess(destroyOptionStream, noopDuplex(), 0, false));51test('Passes when input stdio[*] option aborts', () => testStreamAbortSuccess(destroyOptionStream, noopReadable(), 3, false));52test('Passes when stdout option ends with no more writes', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 1, false));53test('Passes when stderr option ends with no more writes', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 2, false));54test('Passes when output stdio[*] option ends with no more writes', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 3, false));55test('Passes when subprocess.stdout aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 1, false));56test('Passes when subprocess.stdout Duplex aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 1, false));57test('Passes when subprocess.stderr aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 2, false));58test('Passes when subprocess.stderr Duplex aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 2, false));59test('Passes when output subprocess.stdio[*] aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 3, false));60test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 3, false));61test('Passes when stdin option aborts, with a transform', () => testStreamAbortSuccess(destroyOptionStream, noopReadable(), 0, true));62test('Passes when stdin option Duplex aborts, with a transform', () => testStreamAbortSuccess(destroyOptionStream, noopDuplex(), 0, true));63test('Passes when input stdio[*] option aborts, with a transform', () => testStreamAbortSuccess(destroyOptionStream, noopReadable(), 3, true));64test('Passes when stdout option ends with no more writes, with a transform', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 1, true));65test('Passes when stderr option ends with no more writes, with a transform', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 2, true));66test('Passes when output stdio[*] option ends with no more writes, with a transform', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 3, true));67test('Passes when subprocess.stdout aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 1, true));68test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 1, true));69test('Passes when subprocess.stderr aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 2, true));70test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 2, true));71test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 3, true));72test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 3, true));7374// eslint-disable-next-line max-params75const testStreamAbortFail = async (t, streamMethod, stream, fdNumber, useTransform) => {74const testStreamAbortFail = async (streamMethod, stream, fdNumber, useTransform) => {75 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));76 streamMethod({stream, subprocess, fdNumber});77 if (fdNumber !== 0) {78 subprocess.stdin.end();79 }8082 const error = await t.throwsAsync(subprocess);83 t.like(error, {...prematureClose, exitCode: 0});84 t.true(stream.destroyed);81 const error = await assertRejects(subprocess);82 assertLike(error, {...prematureClose, exitCode: 0});83 assert.equal(stream.destroyed, true);84};8587test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);88test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);89test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);90test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);91test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);92test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);93test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);94test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);95test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);96test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);97test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);98test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);99test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);100test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);101test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);102test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);103test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);104test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);86test('Throws abort error when subprocess.stdin aborts', () => testStreamAbortFail(destroySubprocessStream, noopReadable(), 0, false));87test('Throws abort error when subprocess.stdin Duplex aborts', () => testStreamAbortFail(destroySubprocessStream, noopDuplex(), 0, false));88test('Throws abort error when input subprocess.stdio[*] aborts', () => testStreamAbortFail(destroySubprocessStream, noopReadable(), 3, false));89test('Throws abort error when stdout option aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 1, false));90test('Throws abort error when stdout option Duplex aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 1, false));91test('Throws abort error when stderr option aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 2, false));92test('Throws abort error when stderr option Duplex aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 2, false));93test('Throws abort error when output stdio[*] option aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 3, false));94test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 3, false));95test('Throws abort error when subprocess.stdin aborts, with a transform', () => testStreamAbortFail(destroySubprocessStream, noopReadable(), 0, true));96test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', () => testStreamAbortFail(destroySubprocessStream, noopDuplex(), 0, true));97test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', () => testStreamAbortFail(destroySubprocessStream, noopReadable(), 3, true));98test('Throws abort error when stdout option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 1, true));99test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 1, true));100test('Throws abort error when stderr option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 2, true));101test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 2, true));102test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 3, true));103test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 3, true));
modified:test/resolve/wait-epipe.js+39 added-38 removed
1import assert from 'node:assert/strict';2import {setImmediate} from 'node:timers/promises';2import test from 'ava';3import test from 'node:test';4import {assertRejects} from '../helpers/assert.js';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {assertEpipe} from '../helpers/stdio.js';8import {foobarString} from '../helpers/input.js';
6 unmodified lines
15} from '../helpers/wait.js';1617setFixtureDirectory();1817// eslint-disable-next-line max-params18const testStreamEpipeFail = async (t, streamMethod, stream, fdNumber, useTransform) => {19const testStreamEpipeFail = async (streamMethod, stream, fdNumber, useTransform) => {20 const subprocess = execa('noop-stdin-fd.js', [`${fdNumber}`], getStreamStdio(fdNumber, stream, useTransform));21 streamMethod({stream, subprocess, fdNumber});22 await setImmediate();23 subprocess.stdin.end(foobarString);2424 const {exitCode, stdio, stderr} = await t.throwsAsync(subprocess);25 t.is(exitCode, 1);26 t.is(stdio[fdNumber], '');27 t.true(stream.destroyed);28 assertEpipe(t, stderr, fdNumber);25 const {exitCode, stdio, stderr} = await assertRejects(subprocess);26 assert.equal(exitCode, 1);27 assert.equal(stdio[fdNumber], '');28 assert.equal(stream.destroyed, true);29 assertEpipe(stderr, fdNumber);30};3131test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);32test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);33test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);34test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);35test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);36test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);37test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);38test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);39test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);40test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);41test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);42test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);43test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);44test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);45test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);46test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);47test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);48test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);49test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);50test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);51test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);52test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);53test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);54test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);55test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);56test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);57test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);58test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);59test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);60test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, true);32test('Throws EPIPE when stdout option ends with more writes', () => testStreamEpipeFail(endOptionStream, noopWritable(), 1, false));33test('Throws EPIPE when stdout option aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 1, false));34test('Throws EPIPE when stdout option Duplex aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 1, false));35test('Throws EPIPE when stderr option ends with more writes', () => testStreamEpipeFail(endOptionStream, noopWritable(), 2, false));36test('Throws EPIPE when stderr option aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 2, false));37test('Throws EPIPE when stderr option Duplex aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 2, false));38test('Throws EPIPE when output stdio[*] option ends with more writes', () => testStreamEpipeFail(endOptionStream, noopWritable(), 3, false));39test('Throws EPIPE when output stdio[*] option aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 3, false));40test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 3, false));41test('Throws EPIPE when subprocess.stdout aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 1, false));42test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 1, false));43test('Throws EPIPE when subprocess.stderr aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 2, false));44test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 2, false));45test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 3, false));46test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 3, false));47test('Throws EPIPE when stdout option ends with more writes, with a transform', () => testStreamEpipeFail(endOptionStream, noopWritable(), 1, true));48test('Throws EPIPE when stdout option aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 1, true));49test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 1, true));50test('Throws EPIPE when stderr option ends with more writes, with a transform', () => testStreamEpipeFail(endOptionStream, noopWritable(), 2, true));51test('Throws EPIPE when stderr option aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 2, true));52test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 2, true));53test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', () => testStreamEpipeFail(endOptionStream, noopWritable(), 3, true));54test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 3, true));55test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 3, true));56test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 1, true));57test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 1, true));58test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 2, true));59test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 2, true));60test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 3, true));61test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 3, true));
modified:test/resolve/wait-error.js+47 added-46 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';7import {destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';89setFixtureDirectory();109// eslint-disable-next-line max-params10const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {11const testStreamError = async (streamMethod, stream, fdNumber, useTransform) => {12 const subprocess = execa('empty.js', getStreamStdio(fdNumber, stream, useTransform));13 const cause = new Error('test');14 streamMethod({15 stream,
1 unmodified line
17 fdNumber,18 error: cause,19 });2020 const error = await t.throwsAsync(subprocess);21 t.is(error.cause, cause);22 t.is(error.exitCode, 0);23 t.is(error.signal, undefined);24 t.false(error.isTerminated);25 t.true(error.failed);26 t.true(stream.destroyed);21 const error = await assertRejects(subprocess);22 assert.equal(error.cause, cause);23 assert.equal(error.exitCode, 0);24 assert.equal(error.signal, undefined);25 assert.equal(error.isTerminated, false);26 assert.equal(error.failed, true);27 assert.equal(stream.destroyed, true);28};2929test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);30test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);31test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);32test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);33test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);34test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);35test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);36test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);37test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);38test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);39test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);40test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);41test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);42test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);43test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);44test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);45test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);46test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);47test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);48test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);49test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);50test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);51test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);52test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);53test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);54test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);55test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);56test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);57test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);58test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);59test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);60test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);61test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);62test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);63test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);64test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);30test('Throws stream error when stdin option errors', () => testStreamError(destroyOptionStream, noopReadable(), 0, false));31test('Throws stream error when stdin option Duplex errors', () => testStreamError(destroyOptionStream, noopDuplex(), 0, false));32test('Throws stream error when stdout option errors', () => testStreamError(destroyOptionStream, noopWritable(), 1, false));33test('Throws stream error when stdout option Duplex errors', () => testStreamError(destroyOptionStream, noopDuplex(), 1, false));34test('Throws stream error when stderr option errors', () => testStreamError(destroyOptionStream, noopWritable(), 2, false));35test('Throws stream error when stderr option Duplex errors', () => testStreamError(destroyOptionStream, noopDuplex(), 2, false));36test('Throws stream error when output stdio[*] option errors', () => testStreamError(destroyOptionStream, noopWritable(), 3, false));37test('Throws stream error when output stdio[*] Duplex option errors', () => testStreamError(destroyOptionStream, noopDuplex(), 3, false));38test('Throws stream error when input stdio[*] option errors', () => testStreamError(destroyOptionStream, noopReadable(), 3, false));39test('Throws stream error when subprocess.stdin errors', () => testStreamError(destroySubprocessStream, noopReadable(), 0, false));40test('Throws stream error when subprocess.stdin Duplex errors', () => testStreamError(destroySubprocessStream, noopDuplex(), 0, false));41test('Throws stream error when subprocess.stdout errors', () => testStreamError(destroySubprocessStream, noopWritable(), 1, false));42test('Throws stream error when subprocess.stdout Duplex errors', () => testStreamError(destroySubprocessStream, noopDuplex(), 1, false));43test('Throws stream error when subprocess.stderr errors', () => testStreamError(destroySubprocessStream, noopWritable(), 2, false));44test('Throws stream error when subprocess.stderr Duplex errors', () => testStreamError(destroySubprocessStream, noopDuplex(), 2, false));45test('Throws stream error when output subprocess.stdio[*] errors', () => testStreamError(destroySubprocessStream, noopWritable(), 3, false));46test('Throws stream error when output subprocess.stdio[*] Duplex errors', () => testStreamError(destroySubprocessStream, noopDuplex(), 3, false));47test('Throws stream error when input subprocess.stdio[*] errors', () => testStreamError(destroySubprocessStream, noopReadable(), 3, false));48test('Throws stream error when stdin option errors, with a transform', () => testStreamError(destroyOptionStream, noopReadable(), 0, true));49test('Throws stream error when stdin option Duplex errors, with a transform', () => testStreamError(destroyOptionStream, noopDuplex(), 0, true));50test('Throws stream error when stdout option errors, with a transform', () => testStreamError(destroyOptionStream, noopWritable(), 1, true));51test('Throws stream error when stdout option Duplex errors, with a transform', () => testStreamError(destroyOptionStream, noopDuplex(), 1, true));52test('Throws stream error when stderr option errors, with a transform', () => testStreamError(destroyOptionStream, noopWritable(), 2, true));53test('Throws stream error when stderr option Duplex errors, with a transform', () => testStreamError(destroyOptionStream, noopDuplex(), 2, true));54test('Throws stream error when output stdio[*] option errors, with a transform', () => testStreamError(destroyOptionStream, noopWritable(), 3, true));55test('Throws stream error when output stdio[*] Duplex option errors, with a transform', () => testStreamError(destroyOptionStream, noopDuplex(), 3, true));56test('Throws stream error when input stdio[*] option errors, with a transform', () => testStreamError(destroyOptionStream, noopReadable(), 3, true));57test('Throws stream error when subprocess.stdin errors, with a transform', () => testStreamError(destroySubprocessStream, noopReadable(), 0, true));58test('Throws stream error when subprocess.stdin Duplex errors, with a transform', () => testStreamError(destroySubprocessStream, noopDuplex(), 0, true));59test('Throws stream error when subprocess.stdout errors, with a transform', () => testStreamError(destroySubprocessStream, noopWritable(), 1, true));60test('Throws stream error when subprocess.stdout Duplex errors, with a transform', () => testStreamError(destroySubprocessStream, noopDuplex(), 1, true));61test('Throws stream error when subprocess.stderr errors, with a transform', () => testStreamError(destroySubprocessStream, noopWritable(), 2, true));62test('Throws stream error when subprocess.stderr Duplex errors, with a transform', () => testStreamError(destroySubprocessStream, noopDuplex(), 2, true));63test('Throws stream error when output subprocess.stdio[*] errors, with a transform', () => testStreamError(destroySubprocessStream, noopWritable(), 3, true));64test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', () => testStreamError(destroySubprocessStream, noopDuplex(), 3, true));65test('Throws stream error when input subprocess.stdio[*] errors, with a transform', () => testStreamError(destroySubprocessStream, noopReadable(), 3, true));
modified:test/resolve/wait-subprocess.js+28 added-27 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa, execaSync} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {getStdio} from '../helpers/stdio.js';67setFixtureDirectory();88const testIgnore = async (t, fdNumber, execaMethod) => {9const testIgnore = async (fdNumber, execaMethod) => {10 const result = await execaMethod('noop.js', getStdio(fdNumber, 'ignore'));10 t.is(result.stdio[fdNumber], undefined);11 assert.equal(result.stdio[fdNumber], undefined);12};1313test('stdout is undefined if ignored', testIgnore, 1, execa);14test('stderr is undefined if ignored', testIgnore, 2, execa);15test('stdio[*] is undefined if ignored', testIgnore, 3, execa);16test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);14test('stdout is undefined if ignored', () => testIgnore(1, execa));15test('stderr is undefined if ignored', () => testIgnore(2, execa));16test('stdio[*] is undefined if ignored', () => testIgnore(3, execa));17test('stdout is undefined if ignored - sync', () => testIgnore(1, execaSync));18test('stderr is undefined if ignored - sync', () => testIgnore(2, execaSync));19test('stdio[*] is undefined if ignored - sync', () => testIgnore(3, execaSync));2020const testSubprocessEventsCleanup = async (t, fixtureName) => {21const testSubprocessEventsCleanup = async fixtureName => {22 const subprocess = execa(fixtureName, {reject: false});22 t.deepEqual(subprocess.nodeChildProcess.eventNames().map(String).sort(), ['error', 'exit', 'spawn']);23 assert.deepEqual(subprocess.nodeChildProcess.eventNames().map(String).sort(), ['error', 'exit', 'spawn']);24 await subprocess;24 t.deepEqual(subprocess.nodeChildProcess.eventNames(), []);25 assert.deepEqual(subprocess.nodeChildProcess.eventNames(), []);26};2727test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');28test('subprocess listeners are cleaned up on success', () => testSubprocessEventsCleanup('empty.js'));29test('subprocess listeners are cleaned up on failure', () => testSubprocessEventsCleanup('fail.js'));3030test('Aborting stdout should not abort stderr nor all', async t => {31test('Aborting stdout should not abort stderr nor all', async () => {32 const subprocess = execa('empty.js', {all: true});3334 subprocess.stdout.destroy();34 t.false(subprocess.stdout.readable);35 t.true(subprocess.stderr.readable);36 t.true(subprocess.all.readable);35 assert.equal(subprocess.stdout.readable, false);36 assert.equal(subprocess.stderr.readable, true);37 assert.equal(subprocess.all.readable, true);3839 await subprocess;4040 t.false(subprocess.stdout.readableEnded);41 t.is(subprocess.stdout.errored, null);42 t.true(subprocess.stdout.destroyed);43 t.true(subprocess.stderr.readableEnded);44 t.is(subprocess.stderr.errored, null);45 t.true(subprocess.stderr.destroyed);46 t.true(subprocess.all.readableEnded);47 t.is(subprocess.all.errored, null);48 t.true(subprocess.all.destroyed);41 assert.equal(subprocess.stdout.readableEnded, false);42 assert.equal(subprocess.stdout.errored, null);43 assert.equal(subprocess.stdout.destroyed, true);44 assert.equal(subprocess.stderr.readableEnded, true);45 assert.equal(subprocess.stderr.errored, null);46 assert.equal(subprocess.stderr.destroyed, true);47 assert.equal(subprocess.all.readableEnded, true);48 assert.equal(subprocess.all.errored, null);49 assert.equal(subprocess.all.destroyed, true);50});
modified:test/return/duration.js+32 added-30 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows, assertRejects} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';78setFixtureDirectory();98const assertDurationMs = (t, durationMs) => {9 t.is(typeof durationMs, 'number');10 t.true(Number.isFinite(durationMs));11 t.not(durationMs, 0);12 t.true(durationMs > 0);10const assertDurationMs = durationMs => {11 assert.equal(typeof durationMs, 'number');12 assert.ok(Number.isFinite(durationMs));13 assert.notEqual(durationMs, 0);14 assert.ok(durationMs > 0);15};1615test('result.durationMs', async t => {17test('result.durationMs', async () => {18 const {durationMs} = await execa('empty.js');17 assertDurationMs(t, durationMs);19 assertDurationMs(durationMs);20});2120test('result.durationMs - sync', t => {22test('result.durationMs - sync', () => {23 const {durationMs} = execaSync('empty.js');22 assertDurationMs(t, durationMs);24 assertDurationMs(durationMs);25});2625test('error.durationMs', async t => {26 const {durationMs} = await t.throwsAsync(execa('fail.js'));27 assertDurationMs(t, durationMs);27test('error.durationMs', async () => {28 const {durationMs} = await assertRejects(execa('fail.js'));29 assertDurationMs(durationMs);30});3130test('error.durationMs - sync', t => {31 const {durationMs} = t.throws(() => {32test('error.durationMs - sync', () => {33 const {durationMs} = assertThrows(() => {34 execaSync('fail.js');35 });34 assertDurationMs(t, durationMs);36 assertDurationMs(durationMs);37});3837test('error.durationMs - early validation', async t => {38 const {durationMs} = await t.throwsAsync(getEarlyErrorSubprocess());39 assertDurationMs(t, durationMs);39test('error.durationMs - early validation', async () => {40 const {durationMs} = await assertRejects(getEarlyErrorSubprocess());41 assertDurationMs(durationMs);42});4342test('error.durationMs - early validation, sync', t => {43 const {durationMs} = t.throws(getEarlyErrorSubprocessSync);44 assertDurationMs(t, durationMs);44test('error.durationMs - early validation, sync', () => {45 const {durationMs} = assertThrows(getEarlyErrorSubprocessSync);46 assertDurationMs(durationMs);47});4847test('error.durationMs - unpipeSignal', async t => {48 const {durationMs} = await t.throwsAsync(execa('noop.js').pipe('stdin.js', {signal: AbortSignal.abort()}));49 assertDurationMs(t, durationMs);49test('error.durationMs - unpipeSignal', async () => {50 const {durationMs} = await assertRejects(execa('noop.js').pipe('stdin.js', {signal: AbortSignal.abort()}));51 assertDurationMs(durationMs);52});5352test('error.durationMs - pipe validation', async t => {53 const {durationMs} = await t.throwsAsync(execa('noop.js').pipe(false));54 assertDurationMs(t, durationMs);54test('error.durationMs - pipe validation', async () => {55 const {durationMs} = await assertRejects(execa('noop.js').pipe(false));56 assertDurationMs(durationMs);57});5857test.serial('result.durationMs is accurate', async t => {59test('result.durationMs is accurate', async () => {60 const minDurationMs = 1e3;61 const {durationMs} = await execa('delay.js', [minDurationMs]);60 t.true(durationMs >= minDurationMs);62 assert.ok(durationMs >= minDurationMs);63});
modified:test/return/early-error.js+132 added-123 removed
1import assert from 'node:assert/strict';2import {arch} from 'node:os';3import process from 'node:process';4import {once} from 'node:events';5import {finished} from 'node:stream/promises';4import test from 'ava';5import {execa, execaSync, $, ExecaError, ExecaSyncError} from '../../index.js';6import test from 'node:test';7import {assertThrows, assertRejects} from '../helpers/assert.js';8import {9 execa,10 execaSync,11 $,12 ExecaError,13 ExecaSyncError,14} from '../../index.js';15import {setFixtureDirectory} from '../helpers/fixtures-directory.js';16import {foobarString, foobarUint8Array} from '../helpers/input.js';17import {fullStdio} from '../helpers/stdio.js';18import {
9 unmodified lines
28const isWindows = process.platform === 'win32';29const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;3031// A nonexistent command fails asynchronously, so it does not go through the early error path, but the subprocess still has no process to signal23test('kill() does not signal the current process when the command does not exist', async t => {32test('kill() does not signal the current process when the command does not exist', async () => {33 const subprocess = execa('nonexistent-command-for-execa');25 t.is(subprocess.pid, undefined);26 t.is(subprocess.kill(), false);27 t.is((await t.throwsAsync(subprocess)).code, 'ENOENT');34 assert.equal(subprocess.pid, undefined);35 assert.equal(subprocess.kill(), false);36 const {code} = await assertRejects(subprocess);37 assert.equal(code, 'ENOENT');38});3930test('execaSync() throws error if ENOENT', t => {31 t.throws(() => {40test('execaSync() throws error if ENOENT', () => {41 assertThrows(() => {42 execaSync('foo');43 }, {message: ENOENT_REGEXP});44});4536const testEarlyErrorShape = async (t, reject) => {46const testEarlyErrorShape = async reject => {47 const subprocess = getEarlyErrorSubprocess({reject});38 t.notThrows(() => {48 assert.doesNotThrow(() => {49 subprocess.catch(() => {});50 subprocess.nodeChildProcess.unref();51 subprocess.nodeChildProcess.on('error', () => {});52 });53};5445test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);46test('child_process.spawn() early errors have correct shape - reject false', testEarlyErrorShape, false);55test('child_process.spawn() early errors have correct shape', () => testEarlyErrorShape(true));56test('child_process.spawn() early errors have correct shape - reject false', () => testEarlyErrorShape(false));5758// The subprocess never spawned, so there is no process to signal.59// `ChildProcess.prototype.kill()` would signal the current process group instead, since its process id is `0`.60// The handle is replaced by a stub, so that a regression is caught by an assertion instead of killing this test process.51test('kill() does not signal the current process on early errors', async t => {61test('kill() does not signal the current process on early errors', async () => {62 const subprocess = getEarlyErrorSubprocess({reject: false});63 let isSignaled = false;64 subprocess.nodeChildProcess._handle = {65 kill() {
1 unmodified line
67 return 0;68 },69 };7061 t.is(subprocess.kill(), false);62 t.false(isSignaled);71 assert.equal(subprocess.kill(), false);72 assert.equal(isSignaled, false);73 const {failed, isCanceled} = await subprocess;64 t.true(failed);65 t.false(isCanceled);74 assert.equal(failed, true);75 assert.equal(isCanceled, false);76});7768test('child_process.spawn() early errors are propagated', async t => {69 await t.throwsAsync(getEarlyErrorSubprocess(), expectedEarlyError);78test('child_process.spawn() early errors are propagated', async () => {79 await assertRejects(getEarlyErrorSubprocess(), expectedEarlyError);80});8172test('child_process.spawn() early errors are returned', async t => {82test('child_process.spawn() early errors are returned', async () => {83 const {failed} = await getEarlyErrorSubprocess({reject: false});74 t.true(failed);84 assert.equal(failed, true);85});8677test('child_process.spawnSync() early errors are propagated with a correct shape', t => {78 t.throws(getEarlyErrorSubprocessSync, expectedEarlyErrorSync);87test('child_process.spawnSync() early errors are propagated with a correct shape', () => {88 assertThrows(getEarlyErrorSubprocessSync, expectedEarlyErrorSync);89});9081test('child_process.spawnSync() early errors are propagated with a correct shape - reject false', t => {91test('child_process.spawnSync() early errors are propagated with a correct shape - reject false', () => {92 const {failed} = getEarlyErrorSubprocessSync({reject: false});83 t.true(failed);93 assert.equal(failed, true);94});9596if (!isWindows) {87 test('execa() rejects if running non-executable', async t => {88 await t.throwsAsync(execa('non-executable.js'));97 test('execa() rejects if running non-executable', async () => {98 await assertRejects(execa('non-executable.js'));99 });10091 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async t => {92 await t.throwsAsync(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES/});101 test('execa() rejects with correct error and doesn\'t throw if running non-executable with input', async () => {102 await assertRejects(execa('non-executable.js', {input: 'Hey!'}), {message: /EACCES/});103 });104105 if (arch() === 'x64') {96 test('write to fast-exit subprocess', async t => {97 t.plan(1);98106 test('write to fast-exit subprocess', async () => {107 // Try-catch here is necessary, because this test is not 100% accurate108 // Sometimes subprocess can manage to accept input before exiting109 // eslint-disable-next-line node-test/prefer-assert-throws -- either outcome is acceptable, see comment above110 try {111 await execa(`fast-exit-${process.platform}`, [], {input: 'data'});103 t.pass();112 } catch (error) {105 // eslint-disable-next-line ava/no-conditional-assertion -- either outcome is acceptable, see comment above106 t.is(error.code, 'EPIPE');113 assert.equal(error.code, 'EPIPE');114 }115 });116 }117}118112const testEarlyErrorPipe = async (t, getSubprocess) => {113 await t.throwsAsync(getSubprocess(), expectedEarlyError);119const testEarlyErrorPipe = async getSubprocess => {120 await assertRejects(getSubprocess(), expectedEarlyError);121};122116test('child_process.spawn() early errors on source can use .pipe()', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(execa('empty.js')));117test('child_process.spawn() early errors on destination can use .pipe()', testEarlyErrorPipe, () => execa('empty.js').pipe(getEarlyErrorSubprocess()));118test('child_process.spawn() early errors on source and destination can use .pipe()', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess()));119test('child_process.spawn() early errors can use .pipe() multiple times', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess()).pipe(getEarlyErrorSubprocess()));120test('child_process.spawn() early errors can use .pipe``', testEarlyErrorPipe, () => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`);121test('child_process.spawn() early errors can use .pipe`` multiple times', testEarlyErrorPipe, () => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`.pipe`empty.js`);123test('child_process.spawn() early errors on source can use .pipe()', () => testEarlyErrorPipe(() => getEarlyErrorSubprocess().pipe(execa('empty.js'))));124test('child_process.spawn() early errors on destination can use .pipe()', () => testEarlyErrorPipe(() => execa('empty.js').pipe(getEarlyErrorSubprocess())));125test('child_process.spawn() early errors on source and destination can use .pipe()', () => testEarlyErrorPipe(() => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess())));126test('child_process.spawn() early errors can use .pipe() multiple times', () => testEarlyErrorPipe(() => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess()).pipe(getEarlyErrorSubprocess())));127test('child_process.spawn() early errors can use .pipe``', () => testEarlyErrorPipe(() => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`));128test('child_process.spawn() early errors can use .pipe`` multiple times', () => testEarlyErrorPipe(() => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`.pipe`empty.js`));129123const testEarlyErrorConvertor = async (t, streamMethod) => {130const testEarlyErrorConvertor = async streamMethod => {131 const subprocess = getEarlyErrorSubprocess();132 const stream = subprocess[streamMethod]();126 stream.on('close', () => {});133 const errorPromise = once(stream, 'error');134 stream.read?.();135 stream.write?.('.');129 await t.throwsAsync(subprocess);136 const [streamError] = await errorPromise;137 assert.equal(streamError, await assertRejects(subprocess));138};139132test('child_process.spawn() early errors can use .readable()', testEarlyErrorConvertor, 'readable');133test('child_process.spawn() early errors can use .writable()', testEarlyErrorConvertor, 'writable');134test('child_process.spawn() early errors can use .duplex()', testEarlyErrorConvertor, 'duplex');140test('child_process.spawn() early errors can use .readable()', () => testEarlyErrorConvertor('readable'));141test('child_process.spawn() early errors can use .writable()', () => testEarlyErrorConvertor('writable'));142test('child_process.spawn() early errors can use .duplex()', () => testEarlyErrorConvertor('duplex'));143136const testEarlyErrorWebConvertor = async (t, streamMethod) => {144const testEarlyErrorWebConvertor = async streamMethod => {145 const subprocess = getEarlyErrorSubprocess();146 subprocess[streamMethod]();139 await t.throwsAsync(subprocess);147 await assertRejects(subprocess);148};149142test('child_process.spawn() early errors can use .readableStream()', testEarlyErrorWebConvertor, 'readableStream');143test('child_process.spawn() early errors can use .writableStream()', testEarlyErrorWebConvertor, 'writableStream');144test('child_process.spawn() early errors can use .transformStream()', testEarlyErrorWebConvertor, 'transformStream');150test('child_process.spawn() early errors can use .readableStream()', () => testEarlyErrorWebConvertor('readableStream'));151test('child_process.spawn() early errors can use .writableStream()', () => testEarlyErrorWebConvertor('writableStream'));152test('child_process.spawn() early errors can use .transformStream()', () => testEarlyErrorWebConvertor('transformStream'));153154// The subprocess never started, so those streams have no contents.147// They must end right away, like `subprocess.stdout` and `.iterable()` do, instead of hanging forever.148const testEarlyErrorReadableEnd = async (t, streamMethod) => {155// Like when the subprocess did start, they error with its error, or end with `reject: false`, instead of hanging forever.156const readEarlyErrorStream = (subprocess, streamMethod) => Array.fromAsync(subprocess[streamMethod]?.() ?? subprocess);157158const testEarlyErrorReadableEnd = async streamMethod => {159 const subprocess = getEarlyErrorSubprocess();150 const chunks = await Array.fromAsync(subprocess[streamMethod]());160 const streamError = await assertRejects(readEarlyErrorStream(subprocess, streamMethod));161 assert.equal(streamError, await assertRejects(subprocess));162};163152 t.deepEqual(chunks, []);153 await t.throwsAsync(subprocess);164test('child_process.spawn() early errors make .readable() fail', () => testEarlyErrorReadableEnd('readable'));165test('child_process.spawn() early errors make .duplex() fail', () => testEarlyErrorReadableEnd('duplex'));166test('child_process.spawn() early errors make .readableStream() fail', () => testEarlyErrorReadableEnd('readableStream'));167test('child_process.spawn() early errors make .iterable() fail', () => testEarlyErrorReadableEnd('iterable'));168test('child_process.spawn() early errors make Symbol.asyncIterator fail', () => testEarlyErrorReadableEnd());169170const testEarlyErrorReadableEndNoReject = async streamMethod => {171 const subprocess = getEarlyErrorSubprocess({reject: false});172 assert.deepEqual(await readEarlyErrorStream(subprocess, streamMethod), []);173 const {failed} = await subprocess;174 assert.equal(failed, true);175};176156test('child_process.spawn() early errors end .readable()', testEarlyErrorReadableEnd, 'readable');157test('child_process.spawn() early errors end .duplex()', testEarlyErrorReadableEnd, 'duplex');158test('child_process.spawn() early errors end .readableStream()', testEarlyErrorReadableEnd, 'readableStream');177test('child_process.spawn() early errors end .readable() with reject: false', () => testEarlyErrorReadableEndNoReject('readable'));178test('child_process.spawn() early errors end .duplex() with reject: false', () => testEarlyErrorReadableEndNoReject('duplex'));179test('child_process.spawn() early errors end .readableStream() with reject: false', () => testEarlyErrorReadableEndNoReject('readableStream'));180test('child_process.spawn() early errors end .iterable() with reject: false', () => testEarlyErrorReadableEndNoReject('iterable'));181test('child_process.spawn() early errors end Symbol.asyncIterator with reject: false', () => testEarlyErrorReadableEndNoReject());182160const testEarlyErrorWritableEnd = async (t, streamMethod) => {161 const subprocess = getEarlyErrorSubprocess();183const writeEarlyErrorStream = async (subprocess, streamMethod) => {184 const stream = subprocess[streamMethod]();185 stream.end(foobarString);186 await finished(stream, {readable: false});165166 t.false(stream.writable);167 await t.throwsAsync(subprocess);187};188170test('child_process.spawn() early errors end .writable()', testEarlyErrorWritableEnd, 'writable');171test('child_process.spawn() early errors end .duplex() writable side', testEarlyErrorWritableEnd, 'duplex');172173test('child_process.spawn() early errors end .writableStream()', async t => {174 const subprocess = getEarlyErrorSubprocess();175 const writer = subprocess.writableStream().getWriter();189const writeEarlyErrorWebStream = async (subprocess, streamMethod) => {190 const stream = subprocess[streamMethod]();191 const writer = (stream.writable ?? stream).getWriter();192 await writer.write(foobarUint8Array);193 await writer.close();194};195179 await t.throwsAsync(subprocess);180});181182test('child_process.spawn() early errors end .transformStream()', async t => {196const testEarlyErrorWritableEnd = async (streamMethod, writeStream) => {197 const subprocess = getEarlyErrorSubprocess();184 const {readable, writable} = subprocess.transformStream();185 const writer = writable.getWriter();186 await writer.write(foobarUint8Array);187 await writer.close();188 const chunks = await Array.fromAsync(readable);198 const streamError = await assertRejects(writeStream(subprocess, streamMethod));199 assert.equal(streamError, await assertRejects(subprocess));200};201190 t.deepEqual(chunks, []);191 await t.throwsAsync(subprocess);192});202test('child_process.spawn() early errors make .writable() fail', () => testEarlyErrorWritableEnd('writable', writeEarlyErrorStream));203test('child_process.spawn() early errors make .duplex() writable side fail', () => testEarlyErrorWritableEnd('duplex', writeEarlyErrorStream));204test('child_process.spawn() early errors make .writableStream() fail', () => testEarlyErrorWritableEnd('writableStream', writeEarlyErrorWebStream));205test('child_process.spawn() early errors make .transformStream() fail', () => testEarlyErrorWritableEnd('transformStream', writeEarlyErrorWebStream));206194const testEarlyErrorIpc = async (t, runIpcMethod) => {207const testEarlyErrorWritableEndNoReject = async (streamMethod, writeStream) => {208 const subprocess = getEarlyErrorSubprocess({reject: false});209 await writeStream(subprocess, streamMethod);210 const {failed} = await subprocess;211 assert.equal(failed, true);212};213214test('child_process.spawn() early errors end .writable() with reject: false', () => testEarlyErrorWritableEndNoReject('writable', writeEarlyErrorStream));215test('child_process.spawn() early errors end .duplex() writable side with reject: false', () => testEarlyErrorWritableEndNoReject('duplex', writeEarlyErrorStream));216test('child_process.spawn() early errors end .writableStream() with reject: false', () => testEarlyErrorWritableEndNoReject('writableStream', writeEarlyErrorWebStream));217test('child_process.spawn() early errors end .transformStream() with reject: false', () => testEarlyErrorWritableEndNoReject('transformStream', writeEarlyErrorWebStream));218219const testEarlyErrorIpc = async runIpcMethod => {220 const subprocess = getEarlyErrorSubprocess({ipc: true});196 t.throws(() => {221 assertThrows(() => {222 runIpcMethod(subprocess);223 }, {message: /cannot be used: the subprocess has already exited or disconnected/});199 await t.throwsAsync(subprocess, expectedEarlyError);224 await assertRejects(subprocess, expectedEarlyError);225};226202test('child_process.spawn() early errors can use .sendMessage()', testEarlyErrorIpc, subprocess => subprocess.sendMessage('.'));203test('child_process.spawn() early errors can use .getOneMessage()', testEarlyErrorIpc, subprocess => subprocess.getOneMessage());204test('child_process.spawn() early errors can use .getEachMessage()', testEarlyErrorIpc, subprocess => subprocess.getEachMessage());227test('child_process.spawn() early errors can use .sendMessage()', () => testEarlyErrorIpc(subprocess => subprocess.sendMessage('.')));228test('child_process.spawn() early errors can use .getOneMessage()', () => testEarlyErrorIpc(subprocess => subprocess.getOneMessage()));229test('child_process.spawn() early errors can use .getEachMessage()', () => testEarlyErrorIpc(subprocess => subprocess.getEachMessage()));230206test('child_process.spawn() early errors can use .iterable()', async t => {207 const subprocess = getEarlyErrorSubprocess();208 const lines = await Array.fromAsync(subprocess.iterable());209210 t.deepEqual(lines, []);211 await t.throwsAsync(subprocess);212});213214test('child_process.spawn() early errors can use Symbol.asyncIterator', async t => {215 const subprocess = getEarlyErrorSubprocess();216 const lines = await Array.fromAsync(subprocess);217218 t.deepEqual(lines, []);219 await t.throwsAsync(subprocess);220});221222const testEarlyErrorStream = async (t, getStreamProperty, options) => {231const testEarlyErrorStream = async (getStreamProperty, options) => {232 const subprocess = getEarlyErrorSubprocess(options);233 const stream = getStreamProperty(subprocess);234 stream.on('close', () => {});235 stream.read?.();236 stream.end?.();228 await t.throwsAsync(subprocess);237 await assertRejects(subprocess);238};239231test('child_process.spawn() early errors can use .stdin', testEarlyErrorStream, ({stdin}) => stdin);232test('child_process.spawn() early errors can use .stdout', testEarlyErrorStream, ({stdout}) => stdout);233test('child_process.spawn() early errors can use .stderr', testEarlyErrorStream, ({stderr}) => stderr);234test('child_process.spawn() early errors can use .stdio[1]', testEarlyErrorStream, ({stdio}) => stdio[1]);235test('child_process.spawn() early errors can use .stdio[3]', testEarlyErrorStream, ({stdio}) => stdio[3], fullStdio);236test('child_process.spawn() early errors can use .all', testEarlyErrorStream, ({all}) => all, {all: true});240test('child_process.spawn() early errors can use .stdin', () => testEarlyErrorStream(({stdin}) => stdin));241test('child_process.spawn() early errors can use .stdout', () => testEarlyErrorStream(({stdout}) => stdout));242test('child_process.spawn() early errors can use .stderr', () => testEarlyErrorStream(({stderr}) => stderr));243test('child_process.spawn() early errors can use .stdio[1]', () => testEarlyErrorStream(({stdio}) => stdio[1]));244test('child_process.spawn() early errors can use .stdio[3]', () => testEarlyErrorStream(({stdio}) => stdio[3], fullStdio));245test('child_process.spawn() early errors can use .all', () => testEarlyErrorStream(({all}) => all, {all: true}));246247// Reading the `inputFile` happens after the file descriptors are set up, so a missing file is reported as an early error, like with asynchronous methods239test('inputFile which does not exist is an early error', async t => {240 const error = await t.throwsAsync(execa('stdin.js', {inputFile: 'does_not_exist'}));241 t.true(error instanceof ExecaError);242 t.is(error.cause.code, 'ENOENT');248test('inputFile which does not exist is an early error', async () => {249 const error = await assertRejects(execa('stdin.js', {inputFile: 'does_not_exist'}));250 assert.ok(error instanceof ExecaError);251 assert.equal(error.cause.code, 'ENOENT');252});253245test('inputFile which does not exist is an early error, sync', t => {246 const error = t.throws(() => {254test('inputFile which does not exist is an early error, sync', () => {255 const error = assertThrows(() => {256 execaSync('stdin.js', {inputFile: 'does_not_exist'});257 });249 t.true(error instanceof ExecaSyncError);250 t.is(error.cause.code, 'ENOENT');258 assert.ok(error instanceof ExecaSyncError);259 assert.equal(error.cause.code, 'ENOENT');260});
modified:test/return/final-error.js+85 added-83 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows, assertRejects} from '../helpers/assert.js';4import {5 execa,6 execaSync,7 ExecaError,
4 unmodified lines
12import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';1314setFixtureDirectory();1514const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {16const testUnusualError = async (error, expectedOriginalMessage = String(error)) => {17 const subprocess = execa('empty.js');18 subprocess.nodeChildProcess.emit('error', error);17 const {originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);18 t.is(originalMessage, expectedOriginalMessage === '' ? undefined : expectedOriginalMessage);19 t.true(shortMessage.includes(expectedOriginalMessage));20 t.is(message, shortMessage);19 const {originalMessage, shortMessage, message} = await assertRejects(subprocess);20 assert.equal(originalMessage, expectedOriginalMessage === '' ? undefined : expectedOriginalMessage);21 assert.ok(shortMessage.includes(expectedOriginalMessage));22 assert.equal(message, shortMessage);23};2423test('error instance can be null', testUnusualError, null);24test('error instance can be false', testUnusualError, false);25test('error instance can be a string', testUnusualError, 'test');26test('error instance can be a number', testUnusualError, 0);27test('error instance can be a BigInt', testUnusualError, 0n);28test('error instance can be a symbol', testUnusualError, Symbol('test'));29test('error instance can be a function', testUnusualError, () => {});30test('error instance can be an array', testUnusualError, ['test', 'test']);25test('error instance can be null', () => testUnusualError(null));26test('error instance can be false', () => testUnusualError(false));27test('error instance can be a string', () => testUnusualError('test'));28test('error instance can be a number', () => testUnusualError(0));29test('error instance can be a BigInt', () => testUnusualError(0n));30test('error instance can be a symbol', () => testUnusualError(Symbol('test')));31test('error instance can be a function', () => testUnusualError(() => {}));32test('error instance can be an array', () => testUnusualError(['test', 'test']));33// eslint-disable-next-line unicorn/error-message32test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');33test('error instance can be undefined', testUnusualError, undefined, 'undefined');34test('error instance can be an error with an empty message', () => testUnusualError(new Error(''), ''));35test('error instance can be undefined', () => testUnusualError(undefined, 'undefined'));3635test('error instance can be a plain object', async t => {37test('error instance can be a plain object', async () => {38 const subprocess = execa('empty.js');39 subprocess.nodeChildProcess.emit('error', {message: foobarString});38 await t.throwsAsync(subprocess, {message: new RegExp(foobarString)});40 await assertRejects(subprocess, {message: new RegExp(foobarString)});41});4241const runAndFail = (t, fixtureName, argument, error) => {43const runAndFail = (fixtureName, argument, error) => {44 const subprocess = execa(fixtureName, [argument]);45 subprocess.nodeChildProcess.emit('error', error);44 return t.throwsAsync(subprocess);46 return assertRejects(subprocess);47};4847const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {49const testErrorCopy = async (getPreviousArgument, argument = 'two') => {50 const fixtureName = 'empty.js';51 const firstArgument = 'foo';5251 const previousArgument = await getPreviousArgument(t, fixtureName);52 const previousError = await runAndFail(t, fixtureName, firstArgument, previousArgument);53 const error = await runAndFail(t, fixtureName, argument, previousError);53 const previousArgument = await getPreviousArgument(fixtureName);54 const previousError = await runAndFail(fixtureName, firstArgument, previousArgument);55 const error = await runAndFail(fixtureName, argument, previousError);56 const message = `Command failed: ${fixtureName} ${argument}\n${foobarString}`;5756 t.not(error, previousError);57 t.is(error.cause, previousError);58 t.is(error.command, `${fixtureName} ${argument}`);59 t.is(error.message, message);60 t.true(error.stack.includes(message));61 t.is(error.shortMessage, message);62 t.is(error.originalMessage, foobarString);58 assert.notEqual(error, previousError);59 assert.equal(error.cause, previousError);60 assert.equal(error.command, `${fixtureName} ${argument}`);61 assert.equal(error.message, message);62 assert.ok(error.stack.includes(message));63 assert.equal(error.shortMessage, message);64 assert.equal(error.originalMessage, foobarString);65};6665test('error instance can be shared', testErrorCopy, () => new Error(foobarString));66test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));67test('error string can be shared', testErrorCopy, () => foobarString);68test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));69test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');67test('error instance can be shared', () => testErrorCopy(() => new Error(foobarString)));68test('error TypeError can be shared', () => testErrorCopy(() => new TypeError(foobarString)));69test('error string can be shared', () => testErrorCopy(() => foobarString));70test('error copy can be shared', () => testErrorCopy(fixtureName => runAndFail(fixtureName, 'bar', new Error(foobarString))));71test('error with same message can be shared', () => testErrorCopy(() => new Error(foobarString), 'foo'));7271test('error.cause is not set if error.exitCode is not 0', async t => {72 const {exitCode, cause} = await t.throwsAsync(execa('fail.js'));73 t.is(exitCode, 2);74 t.is(cause, undefined);73test('error.cause is not set if error.exitCode is not 0', async () => {74 const {exitCode, cause} = await assertRejects(execa('fail.js'));75 assert.equal(exitCode, 2);76 assert.equal(cause, undefined);77});7877test('error.cause is not set if error.isTerminated', async t => {79test('error.cause is not set if error.isTerminated', async () => {80 const subprocess = execa('forever.js');81 subprocess.kill();80 const {isTerminated, cause} = await t.throwsAsync(subprocess);81 t.true(isTerminated);82 t.is(cause, undefined);82 const {isTerminated, cause} = await assertRejects(subprocess);83 assert.equal(isTerminated, true);84 assert.equal(cause, undefined);85});8685test('error.cause is not set if error.timedOut', async t => {86 const {timedOut, cause} = await t.throwsAsync(execa('forever.js', {timeout: 1}));87 t.true(timedOut);88 t.is(cause, undefined);87test('error.cause is not set if error.timedOut', async () => {88 const {timedOut, cause} = await assertRejects(execa('forever.js', {timeout: 1}));89 assert.equal(timedOut, true);90 assert.equal(cause, undefined);91});9291test('error.cause is set on error event', async t => {93test('error.cause is set on error event', async () => {94 const subprocess = execa('empty.js');95 const error = new Error(foobarString);96 subprocess.nodeChildProcess.emit('error', error);95 const {cause} = await t.throwsAsync(subprocess);96 t.is(cause, error);97 const {cause} = await assertRejects(subprocess);98 assert.equal(cause, error);99});10099test('error.cause is set if error.isCanceled', async t => {101test('error.cause is set if error.isCanceled', async () => {102 const controller = new AbortController();103 const subprocess = execa('forever.js', {cancelSignal: controller.signal});104 const cause = new Error('test');105 controller.abort(cause);104 const error = await t.throwsAsync(subprocess);105 t.true(error.isCanceled);106 t.true(error.isTerminated);107 t.is(error.signal, 'SIGTERM');108 t.is(error.cause, cause);106 const error = await assertRejects(subprocess);107 assert.equal(error.isCanceled, true);108 assert.equal(error.isTerminated, true);109 assert.equal(error.signal, 'SIGTERM');110 assert.equal(error.cause, cause);111});112111test('error.cause is not set if error.isTerminated with .kill(error)', async t => {113test('error.cause is not set if error.isTerminated with .kill(error)', async () => {114 const subprocess = execa('forever.js');115 const error = new Error('test');116 subprocess.kill(error);115 const {isTerminated, cause} = await t.throwsAsync(subprocess);116 t.true(isTerminated);117 t.is(cause, error);117 const {isTerminated, cause} = await assertRejects(subprocess);118 assert.equal(isTerminated, true);119 assert.equal(cause, error);120});121120test('Error is instanceof ExecaError', async t => {121 await t.throwsAsync(execa('fail.js'), {instanceOf: ExecaError});122test('Error is instanceof ExecaError', async () => {123 await assertRejects(execa('fail.js'), {instanceOf: ExecaError});124});125124test('Early error is instanceof ExecaError', async t => {125 await t.throwsAsync(getEarlyErrorSubprocess(), {instanceOf: ExecaError});126test('Early error is instanceof ExecaError', async () => {127 await assertRejects(getEarlyErrorSubprocess(), {instanceOf: ExecaError});128});129128test('Error is instanceof ExecaSyncError', t => {129 t.throws(() => {130test('Error is instanceof ExecaSyncError', () => {131 assertThrows(() => {132 execaSync('fail.js');133 }, {instanceOf: ExecaSyncError});134});135134test('Early error is instanceof ExecaSyncError', t => {135 t.throws(() => {136test('Early error is instanceof ExecaSyncError', () => {137 assertThrows(() => {138 getEarlyErrorSubprocessSync();139 }, {instanceOf: ExecaSyncError});140});141140test('Pipe error is instanceof ExecaError', async t => {141 await t.throwsAsync(execa('empty.js').pipe(false), {instanceOf: ExecaError});142test('Pipe error is instanceof ExecaError', async () => {143 await assertRejects(execa('empty.js').pipe(false), {instanceOf: ExecaError});144});145144const assertNameShape = (t, error) => {145 t.false(Object.hasOwn(error, 'name'));146 t.true(Object.hasOwn(Object.getPrototypeOf(error), 'name'));147 t.false(propertyIsEnumerable.call(Object.getPrototypeOf(error), 'name'));146const assertNameShape = error => {147 assert.ok(!Object.hasOwn(error, 'name'));148 assert.ok(Object.hasOwn(Object.getPrototypeOf(error), 'name'));149 assert.ok(!propertyIsEnumerable.call(Object.getPrototypeOf(error), 'name'));150};151152const {propertyIsEnumerable} = Object.prototype;153152test('error.name is properly set', async t => {153 const error = await t.throwsAsync(execa('fail.js'));154 t.is(error.name, 'ExecaError');155 assertNameShape(t, error);154test('error.name is properly set', async () => {155 const error = await assertRejects(execa('fail.js'));156 assert.equal(error.name, 'ExecaError');157 assertNameShape(error);158});159158test('error.name is properly set - sync', async t => {159 const error = await t.throws(() => {160test('error.name is properly set - sync', async () => {161 const error = await assertThrows(() => {162 execaSync('fail.js');163 });162 t.is(error.name, 'ExecaSyncError');163 assertNameShape(t, error);164 assert.equal(error.name, 'ExecaSyncError');165 assertNameShape(error);166});
modified:test/return/message.js+73 added-72 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';7import {foobarString, foobarObject, foobarObjectInspect} from '../helpers/input.js';
1 unmodified line
9import {noopGenerator, outputObjectGenerator} from '../helpers/generator.js';1011setFixtureDirectory();1211test('error.message contains the command', async t => {12 await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});13test('error.message contains the command', async () => {14 await assertRejects(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});15});1615// eslint-disable-next-line max-params16const testStdioMessage = async (t, encoding, all, objectMode, execaMethod) => {17const testStdioMessage = async (encoding, all, objectMode, execaMethod) => {18 const {exitCode, message} = await execaMethod('echo-fail.js', {19 ...getStdio(1, noopGenerator(objectMode, false, true), 4),20 encoding,21 all,22 reject: false,23 });23 t.is(exitCode, 1);24 assert.equal(exitCode, 1);25 const output = all ? 'stdout\nstderr' : 'stderr\n\nstdout';25 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));26 assert.ok(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));27};2828test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false, execa);29test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false, execa);30test('error.message contains all if available', testStdioMessage, 'utf8', true, false, execa);31test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false, execa);32test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true, execa);33test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true, execa);34test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true, execa);35test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true, execa);36test('error.message contains stdout/stderr/stdio if available, sync', testStdioMessage, 'utf8', false, false, execaSync);37test('error.message contains stdout/stderr/stdio even with encoding "buffer", sync', testStdioMessage, 'buffer', false, false, execaSync);38test('error.message contains all if available, sync', testStdioMessage, 'utf8', true, false, execaSync);39test('error.message contains all even with encoding "buffer", sync', testStdioMessage, 'buffer', true, false, execaSync);40test('error.message contains stdout/stderr/stdio if available, objectMode, sync', testStdioMessage, 'utf8', false, true, execaSync);41test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode, sync', testStdioMessage, 'buffer', false, true, execaSync);42test('error.message contains all if available, objectMode, sync', testStdioMessage, 'utf8', true, true, execaSync);43test('error.message contains all even with encoding "buffer", objectMode, sync', testStdioMessage, 'buffer', true, true, execaSync);29test('error.message contains stdout/stderr/stdio if available', () => testStdioMessage('utf8', false, false, execa));30test('error.message contains stdout/stderr/stdio even with encoding "buffer"', () => testStdioMessage('buffer', false, false, execa));31test('error.message contains all if available', () => testStdioMessage('utf8', true, false, execa));32test('error.message contains all even with encoding "buffer"', () => testStdioMessage('buffer', true, false, execa));33test('error.message contains stdout/stderr/stdio if available, objectMode', () => testStdioMessage('utf8', false, true, execa));34test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', () => testStdioMessage('buffer', false, true, execa));35test('error.message contains all if available, objectMode', () => testStdioMessage('utf8', true, true, execa));36test('error.message contains all even with encoding "buffer", objectMode', () => testStdioMessage('buffer', true, true, execa));37test('error.message contains stdout/stderr/stdio if available, sync', () => testStdioMessage('utf8', false, false, execaSync));38test('error.message contains stdout/stderr/stdio even with encoding "buffer", sync', () => testStdioMessage('buffer', false, false, execaSync));39test('error.message contains all if available, sync', () => testStdioMessage('utf8', true, false, execaSync));40test('error.message contains all even with encoding "buffer", sync', () => testStdioMessage('buffer', true, false, execaSync));41test('error.message contains stdout/stderr/stdio if available, objectMode, sync', () => testStdioMessage('utf8', false, true, execaSync));42test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode, sync', () => testStdioMessage('buffer', false, true, execaSync));43test('error.message contains all if available, objectMode, sync', () => testStdioMessage('utf8', true, true, execaSync));44test('error.message contains all even with encoding "buffer", objectMode, sync', () => testStdioMessage('buffer', true, true, execaSync));4545const testLinesMessage = async (t, encoding, stripFinalNewline, execaMethod) => {46const testLinesMessage = async (encoding, stripFinalNewline, execaMethod) => {47 const {failed, message} = await execaMethod('noop-fail.js', ['1', `${foobarString}\n${foobarString}\n`], {48 lines: true,49 encoding,50 stripFinalNewline,51 reject: false,52 });52 t.true(failed);53 t.true(message.endsWith(`noop-fail.js 1 ${QUOTE}${foobarString}\\n${foobarString}\\n${QUOTE}\n\n${foobarString}\n${foobarString}`));53 assert.equal(failed, true);54 assert.ok(message.endsWith(`noop-fail.js 1 ${QUOTE}${foobarString}\\n${foobarString}\\n${QUOTE}\n\n${foobarString}\n${foobarString}`));55};5656test('error.message handles "lines: true"', testLinesMessage, 'utf8', false, execa);57test('error.message handles "lines: true", stripFinalNewline', testLinesMessage, 'utf8', true, execa);58test('error.message handles "lines: true", buffer', testLinesMessage, 'buffer', false, execa);59test('error.message handles "lines: true", buffer, stripFinalNewline', testLinesMessage, 'buffer', true, execa);60test('error.message handles "lines: true", sync', testLinesMessage, 'utf8', false, execaSync);61test('error.message handles "lines: true", stripFinalNewline, sync', testLinesMessage, 'utf8', true, execaSync);62test('error.message handles "lines: true", buffer, sync', testLinesMessage, 'buffer', false, execaSync);63test('error.message handles "lines: true", buffer, stripFinalNewline, sync', testLinesMessage, 'buffer', true, execaSync);57test('error.message handles "lines: true"', () => testLinesMessage('utf8', false, execa));58test('error.message handles "lines: true", stripFinalNewline', () => testLinesMessage('utf8', true, execa));59test('error.message handles "lines: true", buffer', () => testLinesMessage('buffer', false, execa));60test('error.message handles "lines: true", buffer, stripFinalNewline', () => testLinesMessage('buffer', true, execa));61test('error.message handles "lines: true", sync', () => testLinesMessage('utf8', false, execaSync));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));6565const testPartialIgnoreMessage = async (t, fdNumber, stdioOption, output) => {66 const {message} = await t.throwsAsync(execa('echo-fail.js', getStdio(fdNumber, stdioOption, 4)));67 t.true(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));66const testPartialIgnoreMessage = async (fdNumber, stdioOption, output) => {67 const {message} = await assertRejects(execa('echo-fail.js', getStdio(fdNumber, stdioOption, 4)));68 assert.ok(message.endsWith(`echo-fail.js\n\n${output}\n\nfd3`));69};7070test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');71test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');72test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator(), 'stderr');73test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator(), 'stdout');71test('error.message does not contain stdout if not available', () => testPartialIgnoreMessage(1, 'ignore', 'stderr'));72test('error.message does not contain stderr if not available', () => testPartialIgnoreMessage(2, 'ignore', 'stdout'));73test('error.message does not contain stdout if it is an object', () => testPartialIgnoreMessage(1, outputObjectGenerator(), 'stderr'));74test('error.message does not contain stderr if it is an object', () => testPartialIgnoreMessage(2, outputObjectGenerator(), 'stdout'));7575const testFullIgnoreMessage = async (t, options, resultProperty) => {76 const result = await t.throwsAsync(execa('echo-fail.js', options));76const testFullIgnoreMessage = async (options, resultProperty) => {77 const result = await assertRejects(execa('echo-fail.js', options));78 const message = result[resultProperty];78 t.false(message.includes('stderr'));79 t.false(message.includes('stdout'));80 t.false(message.includes('fd3'));79 assert.ok(!message.includes('stderr'));80 assert.ok(!message.includes('stdout'));81 assert.ok(!message.includes('fd3'));82};8383test('error.message does not contain stdout/stderr/stdio if not available', testFullIgnoreMessage, {stdio: 'ignore'}, 'message');84test('error.shortMessage does not contain stdout/stderr/stdio', testFullIgnoreMessage, fullStdio, 'shortMessage');84test('error.message does not contain stdout/stderr/stdio if not available', () => testFullIgnoreMessage({stdio: 'ignore'}, 'message'));85test('error.shortMessage does not contain stdout/stderr/stdio', () => testFullIgnoreMessage(fullStdio, 'shortMessage'));8686const testErrorMessageConsistent = async (t, stdout) => {87 const {message} = await t.throwsAsync(execa('noop-both-fail-strict.js', [stdout, 'stderr']));88 t.true(message.endsWith(' stderr\n\nstderr\n\nstdout'));87const testErrorMessageConsistent = async stdout => {88 const {message} = await assertRejects(execa('noop-both-fail-strict.js', [stdout, 'stderr']));89 assert.ok(message.endsWith(' stderr\n\nstderr\n\nstdout'));90};9191test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');92test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');92test('error.message newlines are consistent - no newline', () => testErrorMessageConsistent('stdout'));93test('error.message newlines are consistent - newline', () => testErrorMessageConsistent('stdout\n'));9494test('Original error.message is kept', async t => {95 const {originalMessage} = await t.throwsAsync(execa('noop.js', {windowsHide: 'true'}));96 t.is(originalMessage, 'The "options.windowsHide" property must be of type boolean. Received type string (\'true\')');95test('Original error.message is kept', async () => {96 const {originalMessage} = await assertRejects(execa('noop.js', {windowsHide: 'true'}));97 assert.equal(originalMessage, 'The "options.windowsHide" property must be of type boolean. Received type string (\'true\')');98});9999const testIpcOutput = async (t, doubles, ipcInput, returnedMessage) => {100const testIpcOutput = async (doubles, ipcInput, returnedMessage) => {101 const fixtureName = doubles ? 'ipc-echo-twice-fail.js' : 'ipc-echo-fail.js';101 const {exitCode, message, ipcOutput} = await t.throwsAsync(execa(fixtureName, {ipcInput}));102 t.is(exitCode, 1);103 t.true(message.endsWith(`\n\n${doubles ? `${returnedMessage}\n${returnedMessage}` : returnedMessage}`));104 t.deepEqual(ipcOutput, doubles ? [ipcInput, ipcInput] : [ipcInput]);102 const {exitCode, message, ipcOutput} = await assertRejects(execa(fixtureName, {ipcInput}));103 assert.equal(exitCode, 1);104 assert.ok(message.endsWith(`\n\n${doubles ? `${returnedMessage}\n${returnedMessage}` : returnedMessage}`));105 assert.deepEqual(ipcOutput, doubles ? [ipcInput, ipcInput] : [ipcInput]);106};107107test('error.message contains IPC messages, single string', testIpcOutput, false, foobarString, foobarString);108test('error.message contains IPC messages, two strings', testIpcOutput, true, foobarString, foobarString);109test('error.message contains IPC messages, single object', testIpcOutput, false, foobarObject, foobarObjectInspect);110test('error.message contains IPC messages, two objects', testIpcOutput, true, foobarObject, foobarObjectInspect);111test('error.message contains IPC messages, multiline string', testIpcOutput, false, `${foobarString}\n${foobarString}`, `${foobarString}\n${foobarString}`);112test('error.message contains IPC messages, control characters', testIpcOutput, false, '\0', '\\u0000');108test('error.message contains IPC messages, single string', () => testIpcOutput(false, foobarString, foobarString));109test('error.message contains IPC messages, two strings', () => testIpcOutput(true, foobarString, foobarString));110test('error.message contains IPC messages, single object', () => testIpcOutput(false, foobarObject, foobarObjectInspect));111test('error.message contains IPC messages, two objects', () => testIpcOutput(true, foobarObject, foobarObjectInspect));112test('error.message contains IPC messages, multiline string', () => testIpcOutput(false, `${foobarString}\n${foobarString}`, `${foobarString}\n${foobarString}`));113test('error.message contains IPC messages, control characters', () => testIpcOutput(false, '\0', '\\u0000'));114114test('error.message does not contain IPC messages, buffer false', async t => {115 const {exitCode, message, ipcOutput} = await t.throwsAsync(execa('ipc-echo-fail.js', {ipcInput: foobarString, buffer: false}));116 t.is(exitCode, 1);117 t.true(message.endsWith('ipc-echo-fail.js'));118 t.deepEqual(ipcOutput, []);115test('error.message does not contain IPC messages, buffer false', async () => {116 const {exitCode, message, ipcOutput} = await assertRejects(execa('ipc-echo-fail.js', {ipcInput: foobarString, buffer: false}));117 assert.equal(exitCode, 1);118 assert.ok(message.endsWith('ipc-echo-fail.js'));119 assert.deepEqual(ipcOutput, []);120});
modified:test/return/output.js+76 added-74 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows, assertRejects, assertLike} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {fullStdio, getStdio} from '../helpers/stdio.js';7import {foobarString} from '../helpers/input.js';
5 unmodified lines
13} from '../helpers/early-error.js';1415setFixtureDirectory();1615const testOutput = async (t, fdNumber, execaMethod) => {17const testOutput = async (fdNumber, execaMethod) => {18 const {stdout, stderr, stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], fullStdio);17 t.is(stdio[fdNumber], foobarString);19 assert.equal(stdio[fdNumber], foobarString);2021 if (fdNumber === 1) {20 t.is(stdio[fdNumber], stdout);22 assert.equal(stdio[fdNumber], stdout);23 } else if (fdNumber === 2) {22 t.is(stdio[fdNumber], stderr);24 assert.equal(stdio[fdNumber], stderr);25 }26};2726test('can return stdout', testOutput, 1, execa);27test('can return stderr', testOutput, 2, execa);28test('can return output stdio[*]', testOutput, 3, execa);29test('can return stdout, sync', testOutput, 1, execaSync);30test('can return stderr, sync', testOutput, 2, execaSync);31test('can return output stdio[*], sync', testOutput, 3, execaSync);28test('can return stdout', () => testOutput(1, execa));29test('can return stderr', () => testOutput(2, execa));30test('can return output stdio[*]', () => testOutput(3, execa));31test('can return stdout, sync', () => testOutput(1, execaSync));32test('can return stderr, sync', () => testOutput(2, execaSync));33test('can return output stdio[*], sync', () => testOutput(3, execaSync));3433const testNoStdin = async (t, execaMethod) => {35const testNoStdin = async execaMethod => {36 const {stdio} = await execaMethod('noop.js', [foobarString]);35 t.is(stdio[0], undefined);37 assert.equal(stdio[0], undefined);38};3938test('cannot return stdin', testNoStdin, execa);39test('cannot return stdin, sync', testNoStdin, execaSync);40test('cannot return stdin', () => testNoStdin(execa));41test('cannot return stdin, sync', () => testNoStdin(execaSync));4241test('cannot return input stdio[*]', async t => {43test('cannot return input stdio[*]', async () => {44 const {stdio} = await execa('stdin-fd.js', ['3'], getStdio(3, [[foobarString]]));43 t.is(stdio[3], undefined);45 assert.equal(stdio[3], undefined);46});4746test('do not try to consume streams twice', async t => {48test('do not try to consume streams twice', async () => {49 const subprocess = execa('noop.js', ['foo']);50 const {stdout} = await subprocess;51 const {stdout: stdout2} = await subprocess;50 t.is(stdout, 'foo');51 t.is(stdout2, 'foo');52 assert.equal(stdout, 'foo');53 assert.equal(stdout2, 'foo');54});5554const testEmptyErrorStdio = async (t, execaMethod) => {56const testEmptyErrorStdio = async execaMethod => {57 const {failed, stdout, stderr, stdio} = await execaMethod('fail.js', {reject: false});56 t.true(failed);57 t.is(stdout, '');58 t.is(stderr, '');59 t.deepEqual(stdio, [undefined, '', '']);58 assert.equal(failed, true);59 assert.equal(stdout, '');60 assert.equal(stderr, '');61 assert.deepEqual(stdio, [undefined, '', '']);62};6362test('empty error.stdout/stderr/stdio', testEmptyErrorStdio, execa);63test('empty error.stdout/stderr/stdio, sync', testEmptyErrorStdio, execaSync);64test('empty error.stdout/stderr/stdio', () => testEmptyErrorStdio(execa));65test('empty error.stdout/stderr/stdio, sync', () => testEmptyErrorStdio(execaSync));6665const testUndefinedErrorStdio = async (t, execaMethod) => {67const testUndefinedErrorStdio = async execaMethod => {68 const {stdout, stderr, stdio} = await execaMethod('empty.js', {stdio: 'ignore'});67 t.is(stdout, undefined);68 t.is(stderr, undefined);69 t.deepEqual(stdio, [undefined, undefined, undefined]);69 assert.equal(stdout, undefined);70 assert.equal(stderr, undefined);71 assert.deepEqual(stdio, [undefined, undefined, undefined]);72};7372test('undefined error.stdout/stderr/stdio', testUndefinedErrorStdio, execa);73test('undefined error.stdout/stderr/stdio, sync', testUndefinedErrorStdio, execaSync);74test('undefined error.stdout/stderr/stdio', () => testUndefinedErrorStdio(execa));75test('undefined error.stdout/stderr/stdio, sync', () => testUndefinedErrorStdio(execaSync));7675const testEmptyAll = async (t, options, expectedValue, execaMethod) => {77const testEmptyAll = async (options, expectedValue, execaMethod) => {78 const {all} = await execaMethod('empty.js', options);77 t.is(all, expectedValue);79 assert.equal(all, expectedValue);80};8180test('empty error.all', testEmptyAll, {all: true}, '', execa);81test('undefined error.all', testEmptyAll, {}, undefined, execa);82test('ignored error.all', testEmptyAll, {all: true, stdio: 'ignore'}, undefined, execa);83test('empty error.all, sync', testEmptyAll, {all: true}, '', execaSync);84test('undefined error.all, sync', testEmptyAll, {}, undefined, execaSync);85test('ignored error.all, sync', testEmptyAll, {all: true, stdio: 'ignore'}, undefined, execaSync);82test('empty error.all', () => testEmptyAll({all: true}, '', execa));83test('undefined error.all', () => testEmptyAll({}, undefined, execa));84test('ignored error.all', () => testEmptyAll({all: true, stdio: 'ignore'}, undefined, execa));85test('empty error.all, sync', () => testEmptyAll({all: true}, '', execaSync));86test('undefined error.all, sync', () => testEmptyAll({}, undefined, execaSync));87test('ignored error.all, sync', () => testEmptyAll({all: true, stdio: 'ignore'}, undefined, execaSync));8887test('empty error.stdio[0] even with input', async t => {88 const {stdio} = await t.throwsAsync(execa('fail.js', {input: 'test'}));89 t.is(stdio[0], undefined);89test('empty error.stdio[0] even with input', async () => {90 const {stdio} = await assertRejects(execa('fail.js', {input: 'test'}));91 assert.equal(stdio[0], undefined);92});9392const validateSpawnErrorStdio = (t, {stdout, stderr, stdio, all}) => {93 t.is(stdout, undefined);94 t.is(stderr, undefined);95 t.is(all, undefined);96 t.deepEqual(stdio, [undefined, undefined, undefined]);94const 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]);99};10099test('stdout/stderr/all/stdio on subprocess spawning errors', async t => {100 const error = await t.throwsAsync(getEarlyErrorSubprocess({all: true}));101 t.like(error, expectedEarlyError);102 validateSpawnErrorStdio(t, error);101test('stdout/stderr/all/stdio on subprocess spawning errors', async () => {102 const error = await assertRejects(getEarlyErrorSubprocess({all: true}));103 assertLike(error, expectedEarlyError);104 validateSpawnErrorStdio(error);105});106105test('stdout/stderr/all/stdio on subprocess spawning errors, sync', t => {106 const error = t.throws(() => getEarlyErrorSubprocessSync({all: true}));107 t.like(error, expectedEarlyErrorSync);108 validateSpawnErrorStdio(t, error);107test('stdout/stderr/all/stdio on subprocess spawning errors, sync', () => {108 const error = assertThrows(() => getEarlyErrorSubprocessSync({all: true}));109 assertLike(error, expectedEarlyErrorSync);110 validateSpawnErrorStdio(error);111});112111const testErrorOutput = async (t, execaMethod) => {113const testErrorOutput = async execaMethod => {114 const {failed, stdout, stderr, stdio} = await execaMethod('echo-fail.js', {...fullStdio, reject: false});113 t.true(failed);114 t.is(stdout, 'stdout');115 t.is(stderr, 'stderr');116 t.deepEqual(stdio, [undefined, 'stdout', 'stderr', 'fd3']);115 assert.equal(failed, true);116 assert.equal(stdout, 'stdout');117 assert.equal(stderr, 'stderr');118 assert.deepEqual(stdio, [undefined, 'stdout', 'stderr', 'fd3']);119};120119test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);120test('error.stdout/stderr/stdio is defined, sync', testErrorOutput, execaSync);121test('error.stdout/stderr/stdio is defined', () => testErrorOutput(execa));122test('error.stdout/stderr/stdio is defined, sync', () => testErrorOutput(execaSync));123122test('ipc on subprocess spawning errors', async t => {123 const error = await t.throwsAsync(getEarlyErrorSubprocess({ipc: true}));124 t.like(error, expectedEarlyError);125 t.deepEqual(error.ipcOutput, []);124test('ipc on subprocess spawning errors', async () => {125 const error = await assertRejects(getEarlyErrorSubprocess({ipc: true}));126 assertLike(error, expectedEarlyError);127 assert.deepEqual(error.ipcOutput, []);128});129128const testEarlyErrorNoIpc = async (t, options) => {129 const error = await t.throwsAsync(getEarlyErrorSubprocess(options));130 t.like(error, expectedEarlyError);131 t.deepEqual(error.ipcOutput, []);130const testEarlyErrorNoIpc = async options => {131 const error = await assertRejects(getEarlyErrorSubprocess(options));132 assertLike(error, expectedEarlyError);133 assert.deepEqual(error.ipcOutput, []);134};135134test('ipc on subprocess spawning errors, ipc false', testEarlyErrorNoIpc, {ipc: false});135test('ipc on subprocess spawning errors, buffer false', testEarlyErrorNoIpc, {buffer: false});136test('ipc on subprocess spawning errors, ipc false', () => testEarlyErrorNoIpc({ipc: false}));137test('ipc on subprocess spawning errors, buffer false', () => testEarlyErrorNoIpc({buffer: false}));
modified:test/return/reject.js+6 added-5 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa, execaSync} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';56setFixtureDirectory();77test('skip throwing when using reject option', async t => {8test('skip throwing when using reject option', async () => {9 const {exitCode} = await execa('fail.js', {reject: false});9 t.is(exitCode, 2);10 assert.equal(exitCode, 2);11});1212test('skip throwing when using reject option in sync mode', t => {13test('skip throwing when using reject option in sync mode', () => {14 const {exitCode} = execaSync('fail.js', {reject: false});14 t.is(exitCode, 2);15 assert.equal(exitCode, 2);16});
modified:test/return/result.js+52 added-47 removed
1import assert from 'node:assert/strict';2import process from 'node:process';2import test from 'ava';3import test from 'node:test';4import {assertThrows, assertRejects} from '../helpers/assert.js';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {fullStdio} from '../helpers/stdio.js';8/* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */910const isWindows = process.platform === 'win32';1112setFixtureDirectory();1311const testSuccessShape = async (t, execaMethod) => {14const testSuccessShape = async execaMethod => {15 const result = await execaMethod('empty.js', {...fullStdio, all: true});13 t.deepEqual(Reflect.ownKeys(result), [16 assert.deepEqual(Reflect.ownKeys(result), [17 'command',18 'escapedCommand',19 'cwd',20 'durationMs',
13 unmodified lines
34 'pipedFrom',35 ]);36};3735test('Return value properties are not missing and are ordered', testSuccessShape, execa);36test('Return value properties are not missing and are ordered, sync', testSuccessShape, execaSync);38test('Return value properties are not missing and are ordered', () => testSuccessShape(execa));39test('Return value properties are not missing and are ordered, sync', () => testSuccessShape(execaSync));4038const testErrorShape = async (t, execaMethod) => {41const testErrorShape = async execaMethod => {42 const error = await execaMethod('fail.js', {...fullStdio, all: true, reject: false});40 t.is(error.exitCode, 2);41 t.deepEqual(Reflect.ownKeys(error), [43 assert.equal(error.exitCode, 2);44 assert.deepEqual(Reflect.ownKeys(error), [45 'stack',46 'message',47 'shortMessage',48 'command',
16 unmodified lines
65 'pipedFrom',66 ]);67};6866test('Error properties are not missing and are ordered', testErrorShape, execa);67test('Error properties are not missing and are ordered, sync', testErrorShape, execaSync);69test('Error properties are not missing and are ordered', () => testErrorShape(execa));70test('Error properties are not missing and are ordered, sync', () => testErrorShape(execaSync));7169test('failed is false on success', async t => {72test('failed is false on success', async () => {73 const {failed} = await execa('noop.js', ['foo']);71 t.false(failed);74 assert.equal(failed, false);75});7674test('failed is true on failure', async t => {75 const {failed} = await t.throwsAsync(execa('fail.js'));76 t.true(failed);77test('failed is true on failure', async () => {78 const {failed} = await assertRejects(execa('fail.js'));79 assert.equal(failed, true);80});8179test('error.isTerminated is true if subprocess was killed directly', async t => {82test('error.isTerminated is true if subprocess was killed directly', async () => {83 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});8485 subprocess.kill();8684 const {isTerminated, signal, originalMessage, message, shortMessage} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});85 t.true(isTerminated);86 t.is(signal, 'SIGINT');87 t.is(originalMessage, undefined);88 t.is(shortMessage, 'Command was killed with SIGINT (User interruption with CTRL-C): forever.js');89 t.is(message, shortMessage);87 const {isTerminated, signal, originalMessage, message, shortMessage} = await assertRejects(subprocess, {message: /was killed with SIGINT/});88 assert.equal(isTerminated, true);89 assert.equal(signal, 'SIGINT');90 assert.equal(originalMessage, undefined);91 assert.equal(shortMessage, 'Command was killed with SIGINT (User interruption with CTRL-C): forever.js');92 assert.equal(message, shortMessage);93});9492test('error.isTerminated is true if subprocess was killed indirectly', async t => {95test('error.isTerminated is true if subprocess was killed indirectly', async () => {96 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});9798 process.kill(subprocess.pid, 'SIGINT');99100 // `subprocess.kill()` is emulated by Node.js on Windows101 if (isWindows) {99 const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /failed with exit code 1/});100 t.false(isTerminated);101 t.is(signal, undefined);102 const {isTerminated, signal} = await assertRejects(subprocess, {message: /failed with exit code 1/});103 assert.equal(isTerminated, false);104 assert.equal(signal, undefined);105 } else {103 const {isTerminated, signal} = await t.throwsAsync(subprocess, {message: /was killed with SIGINT/});104 t.true(isTerminated);105 t.is(signal, 'SIGINT');106 const {isTerminated, signal} = await assertRejects(subprocess, {message: /was killed with SIGINT/});107 assert.equal(isTerminated, true);108 assert.equal(signal, 'SIGINT');109 }110});111109test('result.isTerminated is false if not killed', async t => {112test('result.isTerminated is false if not killed', async () => {113 const {isTerminated} = await execa('noop.js');111 t.false(isTerminated);114 assert.equal(isTerminated, false);115});116114test('result.isTerminated is false if not killed and subprocess.kill() was called', async t => {117test('result.isTerminated is false if not killed and subprocess.kill() was called', async () => {118 const subprocess = execa('noop.js');119 subprocess.kill(0);117 t.true(subprocess.nodeChildProcess.killed);120 assert.equal(subprocess.nodeChildProcess.killed, true);121 const {isTerminated} = await subprocess;119 t.false(isTerminated);122 assert.equal(isTerminated, false);123});124122test('result.isTerminated is false if not killed, in sync mode', t => {125test('result.isTerminated is false if not killed, in sync mode', () => {126 const {isTerminated} = execaSync('noop.js');124 t.false(isTerminated);127 assert.equal(isTerminated, false);128});129127test('result.isTerminated is false on subprocess error', async t => {128 const {isTerminated} = await t.throwsAsync(execa('wrong command'));129 t.false(isTerminated);130test('result.isTerminated is false on subprocess error', async () => {131 const {isTerminated} = await assertRejects(execa('wrong command'));132 assert.equal(isTerminated, false);133});134132test('result.isTerminated is false on subprocess error, in sync mode', t => {133 const {isTerminated} = t.throws(() => {135test('result.isTerminated is false on subprocess error, in sync mode', () => {136 const {isTerminated} = assertThrows(() => {137 execaSync('wrong command');138 });136 t.false(isTerminated);139 assert.equal(isTerminated, false);140});141139test('error.code is undefined on success', async t => {142test('error.code is undefined on success', async () => {143 const {code} = await execa('noop.js');141 t.is(code, undefined);144 assert.equal(code, undefined);145});146144test('error.code is defined on failure if applicable', async t => {145 const {code} = await t.throwsAsync(execa('noop.js', {uid: true}));146 t.is(code, 'ERR_INVALID_ARG_TYPE');147test('error.code is defined on failure if applicable', async () => {148 const {code} = await assertRejects(execa('noop.js', {uid: true}));149 assert.equal(code, 'ERR_INVALID_ARG_TYPE');150});151152/* eslint-enable node-test/no-conditional-assertion */
modified:test/stdio/direction.js+105 added-91 removed
1import assert from 'node:assert/strict';2import {readFile, writeFile, rm} from 'node:fs/promises';3import process from 'node:process';3import test from 'ava';4import test from 'node:test';5import tempfile from 'tempfile';6import {assertThrows} from '../helpers/assert.js';7import {execa, execaSync} from '../../index.js';8import {getStdio} from '../helpers/stdio.js';9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10import {foobarString} from '../helpers/input.js';11import {noopReadable, noopWritable} from '../helpers/stream.js';1213setFixtureDirectory();1413const testInputOutput = (t, stdioOption, execaMethod) => {14 t.throws(() => {15const testInputOutput = (stdioOption, execaMethod) => {16 assertThrows(() => {17 execaMethod('empty.js', getStdio(3, [new ReadableStream(), stdioOption]));18 }, {message: /readable and writable/});19};2019test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);20test('Cannot pass both readable and writable values to stdio[*] - 1', testInputOutput, 1, execa);21test('Cannot pass both readable and writable values to stdio[*] - 2', testInputOutput, 2, execa);22test('Cannot pass both readable and writable values to stdio[*] - process.stdout', testInputOutput, process.stdout, execa);23test('Cannot pass both readable and writable values to stdio[*] - process.stderr', testInputOutput, process.stderr, execa);24test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', testInputOutput, new WritableStream(), execaSync);25test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', testInputOutput, 1, execaSync);26test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', testInputOutput, 2, execaSync);27test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', testInputOutput, process.stdout, execaSync);28test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);21test('Cannot pass both readable and writable values to stdio[*] - WritableStream', () => testInputOutput(new WritableStream(), execa));22test('Cannot pass both readable and writable values to stdio[*] - 1', () => testInputOutput(1, execa));23test('Cannot pass both readable and writable values to stdio[*] - 2', () => testInputOutput(2, execa));24test('Cannot pass both readable and writable values to stdio[*] - process.stdout', () => testInputOutput(process.stdout, execa));25test('Cannot pass both readable and writable values to stdio[*] - process.stderr', () => testInputOutput(process.stderr, execa));26test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', () => testInputOutput(new WritableStream(), execaSync));27test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', () => testInputOutput(1, execaSync));28test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', () => testInputOutput(2, execaSync));29test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', () => testInputOutput(process.stdout, execaSync));30test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', () => testInputOutput(process.stderr, execaSync));3130const testAmbiguousDirection = async (t, execaMethod) => {32const testAmbiguousDirection = async execaMethod => {33 const [filePathOne, filePathTwo] = [tempfile(), tempfile()];34 await execaMethod('noop-fd.js', ['3', foobarString], getStdio(3, [{file: filePathOne}, {file: filePathTwo}]));33 t.deepEqual(35 assert.deepEqual(36 await Promise.all([readFile(filePathOne, 'utf8'), readFile(filePathTwo, 'utf8')]),37 [foobarString, foobarString],38 );39 await Promise.all([rm(filePathOne), rm(filePathTwo)]);40};4140test('stdio[*] default direction is output', testAmbiguousDirection, execa);41test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);42test('stdio[*] default direction is output', () => testAmbiguousDirection(execa));43test('stdio[*] default direction is output - sync', () => testAmbiguousDirection(execaSync));4443const testAmbiguousMultiple = async (t, fdNumber) => {45const testAmbiguousMultiple = async fdNumber => {46 const filePath = tempfile();47 await writeFile(filePath, foobarString);48 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [{file: filePath}, ['foo', 'bar']]));47 t.is(stdout, `${foobarString}${foobarString}`);49 assert.equal(stdout, `${foobarString}${foobarString}`);50 await rm(filePath);51};5251test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);52test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 3);53test('stdin ambiguous direction is influenced by other values', () => testAmbiguousMultiple(0));54test('stdio[*] ambiguous direction is influenced by other values', () => testAmbiguousMultiple(3));5554const testDirectionInputPipe = async (t, stdioOption) => {56const testDirectionInputPipe = async stdioOption => {57 const subprocess = execa('stdin-fd.js', ['3'], getStdio(3, stdioOption));58 subprocess.stdio[3].end(foobarString);59 const {stdout} = await subprocess;58 t.is(stdout, foobarString);60 assert.equal(stdout, foobarString);61};6261test('stdio[*] { value: "pipe", input: true } sets the direction to input', testDirectionInputPipe, {value: 'pipe', input: true});62test('stdio[*] { value: "overlapped", input: true } sets the direction to input', testDirectionInputPipe, {value: 'overlapped', input: true});63test('stdio[*] { value: "pipe", input: true } sets the direction to input', () => testDirectionInputPipe({value: 'pipe', input: true}));64test('stdio[*] { value: "overlapped", input: true } sets the direction to input', () => testDirectionInputPipe({value: 'overlapped', input: true}));6566const uppercaseGenerator = function * (line) {67 yield line.toUpperCase();68};6968test('stdio[*] { value: generator, input: true } sets the direction to input', async t => {70test('stdio[*] { value: generator, input: true } sets the direction to input', async () => {71 const subprocess = execa('stdin-fd.js', ['3'], getStdio(3, {value: uppercaseGenerator, input: true}));72 subprocess.stdio[3].end(foobarString);73 const {stdout} = await subprocess;72 t.is(stdout, foobarString.toUpperCase());74 assert.equal(stdout, foobarString.toUpperCase());75});7675test('stdio[*] { value: {file}, input: true } sets the direction to input', async t => {77test('stdio[*] { value: {file}, input: true } sets the direction to input', async () => {78 const filePath = tempfile();79 await writeFile(filePath, foobarString);80 const {stdout} = await execa('stdin-fd.js', ['3'], getStdio(3, {value: {file: filePath}, input: true}));79 t.is(stdout, foobarString);81 assert.equal(stdout, foobarString);82 await rm(filePath);83});8483const testInputFixedDirection = (t, stdioOption, execaMethod) => {84 t.throws(() => {85const testInputFixedDirection = (stdioOption, execaMethod) => {86 assertThrows(() => {87 execaMethod('empty.js', getStdio(3, {value: stdioOption, input: true}));88 }, {message: /cannot be used with a writable value/});89};9089test('stdio[*] { value: WritableStream, input: true } is invalid', testInputFixedDirection, new WritableStream(), execa);90test('stdio[*] { value: WritableStream, input: true } is invalid - sync', testInputFixedDirection, new WritableStream(), execaSync);91test('stdio[*] { value: process.stdout, input: true } is invalid', testInputFixedDirection, process.stdout, execa);92test('stdio[*] { value: process.stdout, input: true } is invalid - sync', testInputFixedDirection, process.stdout, execaSync);91test('stdio[*] { value: WritableStream, input: true } is invalid', () => testInputFixedDirection(new WritableStream(), execa));92test('stdio[*] { value: WritableStream, input: true } is invalid - sync', () => testInputFixedDirection(new WritableStream(), execaSync));93test('stdio[*] { value: process.stdout, input: true } is invalid', () => testInputFixedDirection(process.stdout, execa));94test('stdio[*] { value: process.stdout, input: true } is invalid - sync', () => testInputFixedDirection(process.stdout, execaSync));9594test('stdio[*] { value: "pipe", input: true } cannot be used in sync mode', t => {95 t.throws(() => {96test('stdio[*] { value: "pipe", input: true } cannot be used in sync mode', () => {97 assertThrows(() => {98 execaSync('empty.js', getStdio(3, {value: 'pipe', input: true}));99 }, {message: /can be an input pipe with synchronous methods/});100});101100test('stdio[*] { value: "pipe", input: true } cannot be used in sync mode with buffer false', t => {101 t.throws(() => {102test('stdio[*] { value: "pipe", input: true } cannot be used in sync mode with buffer false', () => {103 assertThrows(() => {104 execaSync('empty.js', {...getStdio(3, {value: 'pipe', input: true}), buffer: false});105 }, {message: /can be an input pipe with synchronous methods/});106});107106const testDirectionOutputPipe = async (t, stdioOption, execaMethod) => {108const testDirectionOutputPipe = async (stdioOption, execaMethod) => {109 const {stdio} = await execaMethod('noop-fd.js', ['3', foobarString], getStdio(3, stdioOption));108 t.is(stdio[3], foobarString);110 assert.equal(stdio[3], foobarString);111};112111test('stdio[*] { value: "pipe" } keeps the default output direction', testDirectionOutputPipe, {value: 'pipe'}, execa);112test('stdio[*] { value: "pipe" } keeps the default output direction - sync', testDirectionOutputPipe, {value: 'pipe'}, execaSync);113test('stdio[*] { value: "pipe", input: false } keeps the default output direction', testDirectionOutputPipe, {value: 'pipe', input: false}, execa);114test('stdio[*] { value: "pipe", input: false } keeps the default output direction - sync', testDirectionOutputPipe, {value: 'pipe', input: false}, execaSync);113test('stdio[*] { value: "pipe" } keeps the default output direction', () => testDirectionOutputPipe({value: 'pipe'}, execa));114test('stdio[*] { value: "pipe" } keeps the default output direction - sync', () => testDirectionOutputPipe({value: 'pipe'}, execaSync));115test('stdio[*] { value: "pipe", input: false } keeps the default output direction', () => testDirectionOutputPipe({value: 'pipe', input: false}, execa));116test('stdio[*] { value: "pipe", input: false } keeps the default output direction - sync', () => testDirectionOutputPipe({value: 'pipe', input: false}, execaSync));117116const testDirectionConflict = (t, execaMethod) => {117 t.throws(() => {118const testDirectionConflict = execaMethod => {119 assertThrows(() => {120 execaMethod('empty.js', getStdio(3, [{value: 'pipe', input: true}, 1]));121 }, {message: /readable and writable/});122};123122test('Cannot pass { value: "pipe", input: true } with a writable value to stdio[*]', testDirectionConflict, execa);123test('Cannot pass { value: "pipe", input: true } with a writable value to stdio[*] - sync', testDirectionConflict, execaSync);124test('Cannot pass { value: "pipe", input: true } with a writable value to stdio[*]', () => testDirectionConflict(execa));125test('Cannot pass { value: "pipe", input: true } with a writable value to stdio[*] - sync', () => testDirectionConflict(execaSync));126125const testInputBoolean = (t, execaMethod) => {126 t.throws(() => {127const testInputBoolean = execaMethod => {128 assertThrows(() => {129 execaMethod('empty.js', getStdio(3, {value: 'pipe', input: 'yes'}));130 }, {message: /`stdio\[3\]\.input` option must use a boolean/});131};132131test('stdio[*].input must be a boolean', testInputBoolean, execa);132test('stdio[*].input must be a boolean - sync', testInputBoolean, execaSync);133test('stdio[*].input must be a boolean', () => testInputBoolean(execa));134test('stdio[*].input must be a boolean - sync', () => testInputBoolean(execaSync));135134test('stdout.input must be a boolean with buffer false - sync', t => {135 t.throws(() => {136test('stdout.input must be a boolean with buffer false - sync', () => {137 assertThrows(() => {138 execaSync('empty.js', {stdout: {value: 'pipe', input: 'yes'}, buffer: false});139 }, {message: /`stdout\.input` option must use a boolean/});140});141
1 unmodified line
143`stdin`/`stdout`/`stderr` have a fixed direction, so values that are intrinsically the other direction144are invalid, like with additional file descriptors.145Otherwise, asynchronous methods pipe in the wrong direction and crash, e.g. with `dest.end is not a function`.146*/145const testFixedDirection = (t, options, expectedMessage, execaMethod) => {146 t.throws(() => {147const testFixedDirection = (options, expectedMessage, execaMethod) => {148 assertThrows(() => {149 execaMethod('empty.js', options);150 }, {message: expectedMessage});151};152153const readableOutputMessage = /a readable value is always an input, but `std(?:out|err)` is an output/;154153test('stdout cannot use a readable Node.js stream', testFixedDirection, {stdout: [noopReadable(), 'pipe']}, readableOutputMessage, execa);154test('stdout cannot use a readable Node.js stream - sync', testFixedDirection, {stdout: [noopReadable(), 'pipe']}, readableOutputMessage, execaSync);155test('stderr cannot use a readable Node.js stream', testFixedDirection, {stderr: [noopReadable(), 'pipe']}, readableOutputMessage, execa);156test('stdout cannot use a readable web stream', testFixedDirection, {stdout: new ReadableStream()}, readableOutputMessage, execa);157test('stdout cannot use a readable web stream - sync', testFixedDirection, {stdout: new ReadableStream()}, readableOutputMessage, execaSync);158test('stdout { value: readable, input: true } is invalid', testFixedDirection, {stdout: {value: noopReadable(), input: true}}, readableOutputMessage, execa);155test('stdout cannot use a readable Node.js stream', () => testFixedDirection({stdout: [noopReadable(), 'pipe']}, readableOutputMessage, execa));156test('stdout cannot use a readable Node.js stream - sync', () => testFixedDirection({stdout: [noopReadable(), 'pipe']}, readableOutputMessage, execaSync));157test('stderr cannot use a readable Node.js stream', () => testFixedDirection({stderr: [noopReadable(), 'pipe']}, readableOutputMessage, execa));158test('stdout cannot use a readable web stream', () => testFixedDirection({stdout: new ReadableStream()}, readableOutputMessage, execa));159test('stdout cannot use a readable web stream - sync', () => testFixedDirection({stdout: new ReadableStream()}, readableOutputMessage, execaSync));160test('stdout { value: readable, input: true } is invalid', () => testFixedDirection({stdout: {value: noopReadable(), input: true}}, readableOutputMessage, execa));161160test('stdin cannot use a writable Node.js stream', testFixedDirection, {stdin: [noopWritable(), 'pipe']}, /a writable value is always an output/, execa);161test('stdin cannot use a writable Node.js stream - sync', testFixedDirection, {stdin: [noopWritable(), 'pipe']}, /a writable value is always an output/, execaSync);162test('stdin cannot use a writable web stream', testFixedDirection, {stdin: new WritableStream()}, /a writable value is always an output/, execa);163test('stdin cannot use a writable web stream - sync', testFixedDirection, {stdin: new WritableStream()}, /a writable value is always an output/, execaSync);162test('stdin cannot use a writable Node.js stream', () => testFixedDirection({stdin: [noopWritable(), 'pipe']}, /a writable value is always an output/, execa));163test('stdin cannot use a writable Node.js stream - sync', () => testFixedDirection({stdin: [noopWritable(), 'pipe']}, /a writable value is always an output/, execaSync));164test('stdin cannot use a writable web stream', () => testFixedDirection({stdin: new WritableStream()}, /a writable value is always an output/, execa));165test('stdin cannot use a writable web stream - sync', () => testFixedDirection({stdin: new WritableStream()}, /a writable value is always an output/, execaSync));166165test('stdout { value: writable, input: true } is invalid', testFixedDirection, {stdout: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execa);166test('stdout { value: writable, input: true } is invalid - sync', testFixedDirection, {stdout: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execaSync);167test('stdout { value: readable, input: true } is invalid - sync', testFixedDirection, {stdout: {value: noopReadable(), input: true}}, readableOutputMessage, execaSync);168test('stderr cannot use a readable Node.js stream - sync', testFixedDirection, {stderr: [noopReadable(), 'pipe']}, readableOutputMessage, execaSync);169test('stderr cannot use a readable web stream', testFixedDirection, {stderr: new ReadableStream()}, readableOutputMessage, execa);170test('stderr cannot use a readable web stream - sync', testFixedDirection, {stderr: new ReadableStream()}, readableOutputMessage, execaSync);171test('stderr { value: readable, input: true } is invalid', testFixedDirection, {stderr: {value: noopReadable(), input: true}}, readableOutputMessage, execa);172test('stderr { value: readable, input: true } is invalid - sync', testFixedDirection, {stderr: {value: noopReadable(), input: true}}, readableOutputMessage, execaSync);173test('stderr { value: web readable, input: true } is invalid', testFixedDirection, {stderr: {value: new ReadableStream(), input: true}}, readableOutputMessage, execa);174test('stderr { value: web readable, input: true } is invalid - sync', testFixedDirection, {stderr: {value: new ReadableStream(), input: true}}, readableOutputMessage, execaSync);167test('stdout { value: writable, input: true } is invalid', () => testFixedDirection({stdout: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execa));168test('stdout { value: writable, input: true } is invalid - sync', () => testFixedDirection({stdout: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execaSync));169test('stdout { value: readable, input: true } is invalid - sync', () => testFixedDirection({stdout: {value: noopReadable(), input: true}}, readableOutputMessage, execaSync));170test('stderr cannot use a readable Node.js stream - sync', () => testFixedDirection({stderr: [noopReadable(), 'pipe']}, readableOutputMessage, execaSync));171test('stderr cannot use a readable web stream', () => testFixedDirection({stderr: new ReadableStream()}, readableOutputMessage, execa));172test('stderr cannot use a readable web stream - sync', () => testFixedDirection({stderr: new ReadableStream()}, readableOutputMessage, execaSync));173test('stderr { value: readable, input: true } is invalid', () => testFixedDirection({stderr: {value: noopReadable(), input: true}}, readableOutputMessage, execa));174test('stderr { value: readable, input: true } is invalid - sync', () => testFixedDirection({stderr: {value: noopReadable(), input: true}}, readableOutputMessage, execaSync));175test('stderr { value: web readable, input: true } is invalid', () => testFixedDirection({stderr: {value: new ReadableStream(), input: true}}, readableOutputMessage, execa));176test('stderr { value: web readable, input: true } is invalid - sync', () => testFixedDirection({stderr: {value: new ReadableStream(), input: true}}, readableOutputMessage, execaSync));177176test('stdin { value: writable, input: true } is invalid', testFixedDirection, {stdin: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execa);177test('stdin { value: writable, input: true } is invalid - sync', testFixedDirection, {stdin: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execaSync);178test('stdin { value: writable web stream, input: true } is invalid', testFixedDirection, {stdin: {value: new WritableStream(), input: true}}, /cannot be used with a writable value/, execa);179test('stdin { value: writable web stream, input: true } is invalid - sync', testFixedDirection, {stdin: {value: new WritableStream(), input: true}}, /cannot be used with a writable value/, execaSync);178test('stdin { value: writable, input: true } is invalid', () => testFixedDirection({stdin: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execa));179test('stdin { value: writable, input: true } is invalid - sync', () => testFixedDirection({stdin: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execaSync));180test('stdin { value: writable web stream, input: true } is invalid', () => testFixedDirection({stdin: {value: new WritableStream(), input: true}}, /cannot be used with a writable value/, execa));181test('stdin { value: writable web stream, input: true } is invalid - sync', () => testFixedDirection({stdin: {value: new WritableStream(), input: true}}, /cannot be used with a writable value/, execaSync));182183const writableStdinMessage = /a writable value is always an output/;184183test('stdin cannot use a writable Node.js stream after another value', testFixedDirection, {stdin: ['pipe', noopWritable()]}, writableStdinMessage, execa);184test('stdin cannot use a writable Node.js stream after another value - sync', testFixedDirection, {stdin: ['pipe', noopWritable()]}, writableStdinMessage, execaSync);185test('stdin cannot use a writable web stream in an array', testFixedDirection, {stdin: [new WritableStream(), 'pipe']}, writableStdinMessage, execa);186test('stdin cannot use a writable web stream in an array - sync', testFixedDirection, {stdin: [new WritableStream(), 'pipe']}, writableStdinMessage, execaSync);187test('stdin cannot use both readable and writable values', testFixedDirection, {stdin: [noopReadable(), noopWritable()]}, writableStdinMessage, execa);188test('stdin cannot use both readable and writable values - sync', testFixedDirection, {stdin: [noopReadable(), noopWritable()]}, writableStdinMessage, execaSync);185test('stdin cannot use a writable Node.js stream after another value', () => testFixedDirection({stdin: ['pipe', noopWritable()]}, writableStdinMessage, execa));186test('stdin cannot use a writable Node.js stream after another value - sync', () => testFixedDirection({stdin: ['pipe', noopWritable()]}, writableStdinMessage, execaSync));187test('stdin cannot use a writable web stream in an array', () => testFixedDirection({stdin: [new WritableStream(), 'pipe']}, writableStdinMessage, execa));188test('stdin cannot use a writable web stream in an array - sync', () => testFixedDirection({stdin: [new WritableStream(), 'pipe']}, writableStdinMessage, execaSync));189test('stdin cannot use both readable and writable values', () => testFixedDirection({stdin: [noopReadable(), noopWritable()]}, writableStdinMessage, execa));190test('stdin cannot use both readable and writable values - sync', () => testFixedDirection({stdin: [noopReadable(), noopWritable()]}, writableStdinMessage, execaSync));191190test('stdout cannot use a readable Node.js stream after another value', testFixedDirection, {stdout: ['pipe', noopReadable()]}, readableOutputMessage, execa);191test('stdout cannot use a readable Node.js stream after another value - sync', testFixedDirection, {stdout: ['pipe', noopReadable()]}, readableOutputMessage, execaSync);192test('stdout cannot use a readable web stream in an array', testFixedDirection, {stdout: [new ReadableStream(), 'pipe']}, readableOutputMessage, execa);193test('stdout cannot use a readable web stream in an array - sync', testFixedDirection, {stdout: [new ReadableStream(), 'pipe']}, readableOutputMessage, execaSync);192test('stdout cannot use a readable Node.js stream after another value', () => testFixedDirection({stdout: ['pipe', noopReadable()]}, readableOutputMessage, execa));193test('stdout cannot use a readable Node.js stream after another value - sync', () => testFixedDirection({stdout: ['pipe', noopReadable()]}, readableOutputMessage, execaSync));194test('stdout cannot use a readable web stream in an array', () => testFixedDirection({stdout: [new ReadableStream(), 'pipe']}, readableOutputMessage, execa));195test('stdout cannot use a readable web stream in an array - sync', () => testFixedDirection({stdout: [new ReadableStream(), 'pipe']}, readableOutputMessage, execaSync));196197// A single native value is passed as is to `child_process.spawn()`, which handles it, so its direction is not checked198const testSingleNativeOtherDirection = async (options, execaMethod) => {199 const {exitCode} = await execaMethod('empty.js', options);200 assert.equal(exitCode, 0);201};202203test('stdin can be a single output file descriptor', () => testSingleNativeOtherDirection({stdin: 1}, execa));204test('stdin can be a single output file descriptor - sync', () => testSingleNativeOtherDirection({stdin: 1}, execaSync));205test('stdout can be a single input file descriptor', () => testSingleNativeOtherDirection({stdout: 0}, execa));206test('stdout can be a single input file descriptor - sync', () => testSingleNativeOtherDirection({stdout: 0}, execaSync));207test('stdout can be process.stdin', () => testSingleNativeOtherDirection({stdout: process.stdin}, execa));
modified:test/stdio/duplex.js+22 added-20 removed
1import assert from 'node:assert/strict';2import {createHash} from 'node:crypto';3import {promisify} from 'node:util';4import {createGzip, gunzip} from 'node:zlib';4import test from 'ava';5import test from 'node:test';6import {assertThrows} from '../helpers/assert.js';7import {execa} from '../../index.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9import {10 foobarString,
4 unmodified lines
15import {uppercaseEncodingDuplex, getOutputDuplex} from '../helpers/duplex.js';1617setFixtureDirectory();1817test('Can use crypto.createHash()', async t => {19test('Can use crypto.createHash()', async () => {20 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: {transform: createHash('sha1')}, encoding: 'hex'});21 const expectedStdout = createHash('sha1').update(foobarString).digest('hex');20 t.is(stdout, expectedStdout);22 assert.equal(stdout, expectedStdout);23});2423test('Can use zlib.createGzip()', async t => {25test('Can use zlib.createGzip()', async () => {26 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: {transform: createGzip()}, encoding: 'buffer'});27 const decompressedStdout = await promisify(gunzip)(stdout);26 t.is(decompressedStdout.toString(), foobarString);28 assert.equal(decompressedStdout.toString(), foobarString);29});3029test('Can use encoding "hex"', async t => {31test('Can use encoding "hex"', async () => {32 const {transform} = uppercaseEncodingDuplex('hex')();31 t.is(transform.readableEncoding, 'hex');33 assert.equal(transform.readableEncoding, 'hex');34 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: {transform}});33 t.is(stdout, foobarUppercaseHex);35 assert.equal(stdout, foobarUppercaseHex);36});3736test('Cannot use objectMode: true with duplex.readableObjectMode: false', t => {37 t.throws(() => {38test('Cannot use objectMode: true with duplex.readableObjectMode: false', () => {39 assertThrows(() => {40 execa('noop-fd.js', ['1', foobarString], {stdout: uppercaseEncodingDuplex(undefined, false)(true)});41 }, {message: /cannot be `false` if `new Duplex\({objectMode: true}\)`/});42});4342test('Cannot use objectMode: false with duplex.readableObjectMode: true', t => {43 t.throws(() => {44test('Cannot use objectMode: false with duplex.readableObjectMode: true', () => {45 assertThrows(() => {46 execa('noop-fd.js', ['1', foobarString], {stdout: uppercaseEncodingDuplex(undefined, true)(false)});47 }, {message: /can only be `true` if `new Duplex\({objectMode: true}\)`/});48});4948const testObjectModeFalse = async (t, objectMode) => {50const testObjectModeFalse = async objectMode => {51 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: uppercaseEncodingDuplex(undefined, objectMode)(false)});50 t.is(stdout, foobarUppercase);52 assert.equal(stdout, foobarUppercase);53};5453test('Can use objectMode: false with duplex.readableObjectMode: false', testObjectModeFalse, false);54test('Can use objectMode: undefined with duplex.readableObjectMode: false', testObjectModeFalse, undefined);55test('Can use objectMode: false with duplex.readableObjectMode: false', () => testObjectModeFalse(false));56test('Can use objectMode: undefined with duplex.readableObjectMode: false', () => testObjectModeFalse(undefined));5756const testObjectModeTrue = async (t, objectMode) => {58const testObjectModeTrue = async objectMode => {59 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: getOutputDuplex(foobarObject, objectMode)(true)});58 t.deepEqual(stdout, [foobarObject]);60 assert.deepEqual(stdout, [foobarObject]);61};6261test('Can use objectMode: true with duplex.readableObjectMode: true', testObjectModeTrue, true);62test('Can use objectMode: undefined with duplex.readableObjectMode: true', testObjectModeTrue, undefined);63test('Can use objectMode: true with duplex.readableObjectMode: true', () => testObjectModeTrue(true));64test('Can use objectMode: undefined with duplex.readableObjectMode: true', () => testObjectModeTrue(undefined));
modified:test/stdio/duplicate.js+147 added-139 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {createReadStream, createWriteStream} from 'node:fs';4import {5 mkdir,6 readFile,7 writeFile,8 rm,3import {mkdir, readFile, writeFile, rm} from 'node:fs/promises';4import {join} from 'node:path';9} from 'node:fs/promises';10import path from 'node:path';11import {Readable, Writable} from 'node:stream';12import {pathToFileURL} from 'node:url';7import test from 'ava';13import test from 'node:test';14import tempfile from 'tempfile';15import {assertThrows} from '../helpers/assert.js';16import {execa, execaSync} from '../../index.js';17import {setFixtureDirectory} from '../helpers/fixtures-directory.js';18import {19 uppercaseGenerator,
37 unmodified lines
57const differentInputsName = '`stdin` and `stdio[3]`';58const differentOutputsName = '`stdout` and `stderr`';59const differentInputsOutputsName = '`stdin` and `stdout`';6054test('Can use multiple "pipe" on same input file descriptor', async t => {61test('Can use multiple "pipe" on same input file descriptor', async () => {62 const subprocess = execa('stdin.js', {stdin: ['pipe', 'pipe']});63 subprocess.stdin.end(foobarString);64 const {stdout} = await subprocess;58 t.is(stdout, foobarString);65 assert.equal(stdout, foobarString);66});6761const testTwoPipeOutput = async (t, execaMethod) => {68const testTwoPipeOutput = async execaMethod => {69 const {stdout} = await execaMethod('noop.js', [foobarString], {stdout: ['pipe', 'pipe']});63 t.is(stdout, foobarString);70 assert.equal(stdout, foobarString);71};7266test('Can use multiple "pipe" on same output file descriptor', testTwoPipeOutput, execa);67test('Can use multiple "pipe" on same output file descriptor, sync', testTwoPipeOutput, execaSync);73test('Can use multiple "pipe" on same output file descriptor', () => testTwoPipeOutput(execa));74test('Can use multiple "pipe" on same output file descriptor, sync', () => testTwoPipeOutput(execaSync));7569test('Can repeat same stream on same input file descriptor', async t => {76test('Can repeat same stream on same input file descriptor', async () => {77 const stream = Readable.from([foobarString]);78 const {stdout} = await execa('stdin.js', {stdin: ['pipe', stream, stream]});72 t.is(stdout, foobarString);79 assert.equal(stdout, foobarString);80});8175test('Can repeat same stream on same output file descriptor', async t => {82test('Can repeat same stream on same output file descriptor', async () => {83 let stdout = '';84 const stream = new Writable({85 write(chunk, encoding, done) {86 stdout += chunk.toString();87 done();88 },89 });90 await execa('noop-fd.js', ['1', foobarString], {stdout: ['pipe', stream, stream]});84 t.is(stdout, foobarString);91 assert.equal(stdout, foobarString);92});9387// eslint-disable-next-line max-params88const testTwoGenerators = async (t, producesTwo, execaMethod, firstGenerator, secondGenerator = firstGenerator) => {94const testTwoGenerators = async (producesTwo, execaMethod, firstGenerator, secondGenerator = firstGenerator) => {95 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {stdout: [firstGenerator, secondGenerator]});96 const expectedSuffix = producesTwo ? `${casedSuffix}${casedSuffix}` : casedSuffix;91 t.is(stdout, `${foobarString}${expectedSuffix}`);97 assert.equal(stdout, `${foobarString}${expectedSuffix}`);98};9994test('Can use multiple identical generators', testTwoGenerators, true, execa, appendGenerator().transform);95test('Can use multiple identical generators, options object', testTwoGenerators, true, execa, appendGenerator());96test('Can use multiple identical generators, async', testTwoGenerators, true, execa, appendAsyncGenerator().transform);97test('Can use multiple identical generators, options object, async', testTwoGenerators, true, execa, appendAsyncGenerator());98test('Can use multiple identical generators, sync', testTwoGenerators, true, execaSync, appendGenerator().transform);99test('Can use multiple identical generators, options object, sync', testTwoGenerators, true, execaSync, appendGenerator());100test('Ignore duplicate identical duplexes', testTwoGenerators, false, execa, appendDuplex());101test('Ignore duplicate identical webTransforms', testTwoGenerators, false, execa, appendWebTransform());102test('Can use multiple generators with duplexes', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendDuplex());103test('Can use multiple generators with webTransforms', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendWebTransform());104test('Can use multiple duplexes with webTransforms', testTwoGenerators, true, execa, appendDuplex(), appendWebTransform());100test('Can use multiple identical generators', () => testTwoGenerators(true, execa, appendGenerator().transform));101test('Can use multiple identical generators, options object', () => testTwoGenerators(true, execa, appendGenerator()));102test('Can use multiple identical generators, async', () => testTwoGenerators(true, execa, appendAsyncGenerator().transform));103test('Can use multiple identical generators, options object, async', () => testTwoGenerators(true, execa, appendAsyncGenerator()));104test('Can use multiple identical generators, sync', () => testTwoGenerators(true, execaSync, appendGenerator().transform));105test('Can use multiple identical generators, options object, sync', () => testTwoGenerators(true, execaSync, appendGenerator()));106test('Ignore duplicate identical duplexes', () => testTwoGenerators(false, execa, appendDuplex()));107test('Ignore duplicate identical webTransforms', () => testTwoGenerators(false, execa, appendWebTransform()));108test('Can use multiple generators with duplexes', () => testTwoGenerators(true, execa, appendGenerator(false, false, true), appendDuplex()));109test('Can use multiple generators with webTransforms', () => testTwoGenerators(true, execa, appendGenerator(false, false, true), appendWebTransform()));110test('Can use multiple duplexes with webTransforms', () => testTwoGenerators(true, execa, appendDuplex(), appendWebTransform()));111106const testMultiplePipeOutput = async (t, execaMethod) => {112const testMultiplePipeOutput = async execaMethod => {113 const {stdout, stderr} = await execaMethod('noop-both.js', [foobarString], fullStdio);108 t.is(stdout, foobarString);109 t.is(stderr, foobarString);114 assert.equal(stdout, foobarString);115 assert.equal(stderr, foobarString);116};117112test('Can use multiple "pipe" on different output file descriptors', testMultiplePipeOutput, execa);113test('Can use multiple "pipe" on different output file descriptors, sync', testMultiplePipeOutput, execaSync);118test('Can use multiple "pipe" on different output file descriptors', () => testMultiplePipeOutput(execa));119test('Can use multiple "pipe" on different output file descriptors, sync', () => testMultiplePipeOutput(execaSync));120115test('Can re-use same generator on different input file descriptors', async t => {121test('Can re-use same generator on different input file descriptors', async () => {122 const {stdout} = await execa('stdin-fd-both.js', ['3'], getDifferentInputs([foobarUint8Array, uppercaseGenerator(false, false, true)]));117 t.is(stdout, `${foobarUppercase}${foobarUppercase}`);123 assert.equal(stdout, `${foobarUppercase}${foobarUppercase}`);124});125120test('Can re-use same generator on different output file descriptors', async t => {126test('Can re-use same generator on different output file descriptors', async () => {127 const {stdout, stderr} = await execa('noop-both.js', [foobarString], getDifferentOutputs(uppercaseGenerator(false, false, true)));122 t.is(stdout, foobarUppercase);123 t.is(stderr, foobarUppercase);128 assert.equal(stdout, foobarUppercase);129 assert.equal(stderr, foobarUppercase);130});131126test('Can re-use same non-native Readable stream on different input file descriptors', async t => {132test('Can re-use same non-native Readable stream on different input file descriptors', async () => {133 const filePath = tempfile();134 await writeFile(filePath, foobarString);135 const stream = createReadStream(filePath);136 await once(stream, 'open');137 const {stdout} = await execa('stdin-fd-both.js', ['3'], getDifferentInputs([new Uint8Array(0), stream]));132 t.is(stdout, `${foobarString}${foobarString}`);138 assert.equal(stdout, `${foobarString}${foobarString}`);139 await rm(filePath);140});141136const testMultipleStreamOutput = async (t, getStreamOption) => {142const testMultipleStreamOutput = async getStreamOption => {143 const filePath = tempfile();144 const stream = createWriteStream(filePath);145 await once(stream, 'open');146 await execa('noop-both.js', [foobarString], getDifferentOutputs(getStreamOption(stream)));141 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);147 assert.equal(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);148 await rm(filePath);149};150145test('Can re-use same native Writable stream on different output file descriptors', testMultipleStreamOutput, getNativeStream);146test('Can re-use same non-native Writable stream on different output file descriptors', testMultipleStreamOutput, getNonNativeStream);147test('Can re-use same web Writable stream on different output file descriptors', testMultipleStreamOutput, getWebWritableStream);151test('Can re-use same native Writable stream on different output file descriptors', () => testMultipleStreamOutput(getNativeStream));152test('Can re-use same non-native Writable stream on different output file descriptors', () => testMultipleStreamOutput(getNonNativeStream));153test('Can re-use same web Writable stream on different output file descriptors', () => testMultipleStreamOutput(getWebWritableStream));154149const testMultipleInheritOutput = async (t, isSync) => {155const testMultipleInheritOutput = async isSync => {156 const {stdout} = await nestedSubprocess('noop-both.js', [foobarString], {...getDifferentOutputs(1), isSync});151 t.is(stdout, `${foobarString}\n${foobarString}`);157 assert.equal(stdout, `${foobarString}\n${foobarString}`);158};159154test('Can re-use same parent file descriptor on different output file descriptors', testMultipleInheritOutput, false);155test('Can re-use same parent file descriptor on different output file descriptors, sync', testMultipleInheritOutput, true);160test('Can re-use same parent file descriptor on different output file descriptors', () => testMultipleInheritOutput(false));161test('Can re-use same parent file descriptor on different output file descriptors, sync', () => testMultipleInheritOutput(true));162157const testMultipleFileInput = async (t, mapFile) => {163const testMultipleFileInput = async mapFile => {164 const filePath = tempfile();165 await writeFile(filePath, foobarString);166 const {stdout} = await execa('stdin-fd-both.js', ['3'], getDifferentInputs([new Uint8Array(0), mapFile(filePath)]));161 t.is(stdout, `${foobarString}${foobarString}`);167 assert.equal(stdout, `${foobarString}${foobarString}`);168 await rm(filePath);169};170165test('Can re-use same file path on different input file descriptors', testMultipleFileInput, getAbsolutePath);166test('Can re-use same file URL on different input file descriptors', testMultipleFileInput, pathToFileURL);171test('Can re-use same file path on different input file descriptors', () => testMultipleFileInput(getAbsolutePath));172test('Can re-use same file URL on different input file descriptors', () => testMultipleFileInput(pathToFileURL));173168const testMultipleFileOutput = async (t, mapFile, execaMethod) => {174const testMultipleFileOutput = async (mapFile, execaMethod) => {175 const filePath = tempfile();176 await execaMethod('noop-both.js', [foobarString], getDifferentOutputs(mapFile(filePath)));171 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);177 assert.equal(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);178 await rm(filePath);179};180175test('Can re-use same file path on different output file descriptors', testMultipleFileOutput, getAbsolutePath, execa);176test('Can re-use same file path on different output file descriptors, sync', testMultipleFileOutput, getAbsolutePath, execaSync);177test('Can re-use same file URL on different output file descriptors', testMultipleFileOutput, pathToFileURL, execa);178test('Can re-use same file URL on different output file descriptors, sync', testMultipleFileOutput, pathToFileURL, execaSync);181test('Can re-use same file path on different output file descriptors', () => testMultipleFileOutput(getAbsolutePath, execa));182test('Can re-use same file path on different output file descriptors, sync', () => testMultipleFileOutput(getAbsolutePath, execaSync));183test('Can re-use same file URL on different output file descriptors', () => testMultipleFileOutput(pathToFileURL, execa));184test('Can re-use same file URL on different output file descriptors, sync', () => testMultipleFileOutput(pathToFileURL, execaSync));185180// One of the two `append` flags would be silently ignored otherwise181const testAppendConflict = (t, execaMethod, stdoutAppend, stderrAppend) => {186// When file descriptors target the same file with different `append` values, the first one decides187const testDifferentAppend = async (execaMethod, stdoutAppend, stderrAppend, expectedPrefix) => {188 const filePath = tempfile();183 t.throws(() => {184 execaMethod('empty.js', {185 stdout: {file: filePath, append: stdoutAppend},186 stderr: {file: filePath, append: stderrAppend},187 });188 }, {message: `The ${differentOutputsName} options must not target ${filePathName} that is the same with different \`append\` values.`});189 await writeFile(filePath, 'base\n');190 await execaMethod('noop-both.js', [foobarString], {191 stdout: {file: filePath, append: stdoutAppend},192 stderr: {file: filePath, append: stderrAppend},193 });194 assert.equal(await readFile(filePath, 'utf8'), `${expectedPrefix}${foobarString}\n${foobarString}\n`);195 await rm(filePath);196};197191test('Cannot use different `append` values on the same output file path', testAppendConflict, execa, undefined, true);192test('Cannot use different `append` values on the same output file path, reversed', testAppendConflict, execa, true, undefined);193test('Cannot use different `append` values on the same output file path, sync', testAppendConflict, execaSync, undefined, true);194test('Cannot use different `append` values on the same output file path, reversed, sync', testAppendConflict, execaSync, true, undefined);198test('The first file descriptor decides `append` on the same output file path', () => testDifferentAppend(execa, undefined, true, ''));199test('The first file descriptor decides `append` on the same output file path, reversed', () => testDifferentAppend(execa, true, undefined, 'base\n'));200test('The first file descriptor decides `append` on the same output file path, sync', () => testDifferentAppend(execaSync, undefined, true, ''));201test('The first file descriptor decides `append` on the same output file path, reversed, sync', () => testDifferentAppend(execaSync, true, undefined, 'base\n'));202196// Two items of a single file descriptor must be checked too, not only two different file descriptors203// Two items of a single file descriptor are written once, and the first one decides too204const sameFdName = '`stdout` and `stdout`';205199const testAppendConflictSameFd = (t, execaMethod, appendOne, appendTwo) => {206const testDifferentAppendSameFd = async (execaMethod, appendOne, appendTwo, expectedPrefix) => {207 const filePath = tempfile();201 t.throws(() => {202 execaMethod('empty.js', {stdout: [{file: filePath, append: appendOne}, {file: filePath, append: appendTwo}]});203 }, {message: `The ${sameFdName} options must not target ${filePathName} that is the same with different \`append\` values.`});208 await writeFile(filePath, 'base\n');209 await execaMethod('noop.js', [foobarString], {stdout: [{file: filePath, append: appendOne}, {file: filePath, append: appendTwo}]});210 assert.equal(await readFile(filePath, 'utf8'), `${expectedPrefix}${foobarString}\n`);211 await rm(filePath);212};213206test('Cannot use different `append` values on the same output file path in the same file descriptor', testAppendConflictSameFd, execa, undefined, true);207test('Cannot use different `append` values on the same output file path in the same file descriptor, reversed', testAppendConflictSameFd, execa, true, undefined);208test('Cannot use different `append` values on the same output file path in the same file descriptor, sync', testAppendConflictSameFd, execaSync, undefined, true);209test('Cannot use different `append` values on the same output file path in the same file descriptor, reversed, sync', testAppendConflictSameFd, execaSync, true, undefined);214test('The first item decides `append` on the same output file path in the same file descriptor', () => testDifferentAppendSameFd(execa, undefined, true, ''));215test('The first item decides `append` on the same output file path in the same file descriptor, reversed', () => testDifferentAppendSameFd(execa, true, undefined, 'base\n'));216test('The first item decides `append` on the same output file path in the same file descriptor, sync', () => testDifferentAppendSameFd(execaSync, undefined, true, ''));217test('The first item decides `append` on the same output file path in the same file descriptor, reversed, sync', () => testDifferentAppendSameFd(execaSync, true, undefined, 'base\n'));218211const testSameAppend = async (t, execaMethod) => {219const testSameAppend = async execaMethod => {220 const filePath = tempfile();221 await writeFile(filePath, 'base\n');222 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath, append: true}, stderr: {file: filePath, append: true}});215 t.is(await readFile(filePath, 'utf8'), `base\n${foobarString}\n${foobarString}\n`);223 assert.equal(await readFile(filePath, 'utf8'), `base\n${foobarString}\n${foobarString}\n`);224 await rm(filePath);225};226219test('Can use the same `append: true` value on the same output file path', testSameAppend, execa);220test('Can use the same `append: true` value on the same output file path, sync', testSameAppend, execaSync);227test('Can use the same `append: true` value on the same output file path', () => testSameAppend(execa));228test('Can use the same `append: true` value on the same output file path, sync', () => testSameAppend(execaSync));229222const testFalsyAppend = async (t, execaMethod) => {230const testFalsyAppend = async execaMethod => {231 const filePath = tempfile();232 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath}, stderr: {file: filePath, append: false}});225 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);233 assert.equal(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);234 await rm(filePath);235};236229test('Falsy `append` values are the same on the same output file path', testFalsyAppend, execa);230test('Falsy `append` values are the same on the same output file path, sync', testFalsyAppend, execaSync);237test('Falsy `append` values are the same on the same output file path', () => testFalsyAppend(execa));238test('Falsy `append` values are the same on the same output file path, sync', () => testFalsyAppend(execaSync));239232const testMultipleFileInputOutput = async (t, mapFile, execaMethod) => {240const testMultipleFileInputOutput = async (mapFile, execaMethod) => {241 const inputFilePath = tempfile();242 const outputFilePath = tempfile();243 await writeFile(inputFilePath, foobarString);244 await execaMethod('stdin.js', {stdin: mapFile(inputFilePath), stdout: mapFile(outputFilePath)});237 t.is(await readFile(outputFilePath, 'utf8'), foobarString);245 assert.equal(await readFile(outputFilePath, 'utf8'), foobarString);246 await Promise.all([rm(inputFilePath), rm(outputFilePath)]);247};248241test('Can use different file paths on different input/output file descriptors', testMultipleFileInputOutput, getAbsolutePath, execa);242test('Can use different file paths on different input/output file descriptors, sync', testMultipleFileInputOutput, getAbsolutePath, execaSync);243test('Can use different file URL on different input/output file descriptors', testMultipleFileInputOutput, pathToFileURL, execa);244test('Can use different file URL on different input/output file descriptors, sync', testMultipleFileInputOutput, pathToFileURL, execaSync);249test('Can use different file paths on different input/output file descriptors', () => testMultipleFileInputOutput(getAbsolutePath, execa));250test('Can use different file paths on different input/output file descriptors, sync', () => testMultipleFileInputOutput(getAbsolutePath, execaSync));251test('Can use different file URL on different input/output file descriptors', () => testMultipleFileInputOutput(pathToFileURL, execa));252test('Can use different file URL on different input/output file descriptors, sync', () => testMultipleFileInputOutput(pathToFileURL, execaSync));253254// eslint-disable-next-line max-params247const testMultipleInvalid = async (t, getDummyStream, typeName, getStdio, fdName, execaMethod) => {255const testMultipleInvalid = async (getDummyStream, typeName, getStdio, fdName, execaMethod) => {256 const stdioOption = await getDummyStream();249 t.throws(() => {257 assertThrows(() => {258 execaMethod('empty.js', getStdio(stdioOption));259 }, {message: `The ${fdName} options must not target ${typeName} that is the same.`});260 if (stdioOption.transform !== undefined) {253 t.true(stdioOption.transform.destroyed);261 assert.equal(stdioOption.transform.destroyed, true);262 }263};264257test('Cannot use same Duplex on different input file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentInputs, differentInputsName, execa);258test('Cannot use same Duplex on different output file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentOutputs, differentOutputsName, execa);259test('Cannot use same Duplex on both input and output file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentInputsOutputs, differentInputsOutputsName, execa);260test('Cannot use same TransformStream on different input file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentInputs, differentInputsName, execa);261test('Cannot use same TransformStream on different output file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentOutputs, differentOutputsName, execa);262test('Cannot use same TransformStream on both input and output file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentInputsOutputs, differentInputsOutputsName, execa);263test('Cannot use same file path on both input and output file descriptors', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execa);264test('Cannot use same file URL on both input and output file descriptors', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execa);265test('Cannot use same file path on both input and output file descriptors, sync', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);266test('Cannot use same file URL on both input and output file descriptors, sync', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);265test('Cannot use same Duplex on different input file descriptors', () => testMultipleInvalid(getDummyDuplex, duplexName, getDifferentInputs, differentInputsName, execa));266test('Cannot use same Duplex on different output file descriptors', () => testMultipleInvalid(getDummyDuplex, duplexName, getDifferentOutputs, differentOutputsName, execa));267test('Cannot use same Duplex on both input and output file descriptors', () => testMultipleInvalid(getDummyDuplex, duplexName, getDifferentInputsOutputs, differentInputsOutputsName, execa));268test('Cannot use same TransformStream on different input file descriptors', () => testMultipleInvalid(getDummyWebTransformStream, webTransformName, getDifferentInputs, differentInputsName, execa));269test('Cannot use same TransformStream on different output file descriptors', () => testMultipleInvalid(getDummyWebTransformStream, webTransformName, getDifferentOutputs, differentOutputsName, execa));270test('Cannot use same TransformStream on both input and output file descriptors', () => testMultipleInvalid(getDummyWebTransformStream, webTransformName, getDifferentInputsOutputs, differentInputsOutputsName, execa));271test('Cannot use same file path on both input and output file descriptors', () => testMultipleInvalid(getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execa));272test('Cannot use same file URL on both input and output file descriptors', () => testMultipleInvalid(getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execa));273test('Cannot use same file path on both input and output file descriptors, sync', () => testMultipleInvalid(getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync));274test('Cannot use same file URL on both input and output file descriptors, sync', () => testMultipleInvalid(getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync));275276// Piping a Duplex or a web TransformStream into itself would feed it its own output forever.277// Each item uses a distinct wrapper object, around the same stream, so that `filterDuplicates()` does not merge them.270const testSameStreamSameFd = (t, getStream, typeName) => {278const testSameStreamSameFd = (getStream, typeName) => {279 const stream = getStream();272 t.throws(() => {280 assertThrows(() => {281 execa('empty.js', {stdout: [{transform: stream}, {transform: stream}]});282 }, {message: `The ${sameFdName} options must not target ${typeName} that is the same.`});283};284277test('Cannot use same Duplex twice on the same output file descriptor', testSameStreamSameFd, noopDuplex, duplexName);278test('Cannot use same TransformStream twice on the same output file descriptor', testSameStreamSameFd, () => new TransformStream(), webTransformName);285test('Cannot use same Duplex twice on the same output file descriptor', () => testSameStreamSameFd(noopDuplex, duplexName));286test('Cannot use same TransformStream twice on the same output file descriptor', () => testSameStreamSameFd(() => new TransformStream(), webTransformName));287288// The streams created for the earlier items must be destroyed when a later one is rejected, otherwise they are leaked281test('Earlier streams are destroyed when a later item of the same file descriptor is rejected', t => {289test('Earlier streams are destroyed when a later item of the same file descriptor is rejected', () => {290 const stream = noopDuplex();283 t.throws(() => {291 assertThrows(() => {292 execa('empty.js', {stdout: [{transform: stream}, {transform: stream}]});293 }, {message: `The ${sameFdName} options must not target ${duplexName} that is the same.`});286 t.true(stream.destroyed);294 assert.equal(stream.destroyed, true);295});296297// `{file: './output.txt'}` and a `file:` URL are two ways to target the same file290const testFilePathAndUrl = async (t, execaMethod) => {298const testFilePathAndUrl = async execaMethod => {299 const filePath = tempfile();300 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath}, stderr: pathToFileURL(filePath)});293 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);301 assert.equal(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);302 await rm(filePath);303};304297const testFileUrlAndPath = async (t, execaMethod) => {305const testFileUrlAndPath = async execaMethod => {306 const filePath = tempfile();307 await execaMethod('noop-both.js', [foobarString], {stdout: pathToFileURL(filePath), stderr: {file: filePath}});300 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);308 assert.equal(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);309 await rm(filePath);310};311304test('Can use a file path and a file URL on different output file descriptors', testFilePathAndUrl, execa);305test('Can use a file URL and a file path on different output file descriptors', testFileUrlAndPath, execa);306test('Can use a file path and a file URL on different output file descriptors, sync', testFilePathAndUrl, execaSync);307test('Can use a file URL and a file path on different output file descriptors, sync', testFileUrlAndPath, execaSync);312test('Can use a file path and a file URL on different output file descriptors', () => testFilePathAndUrl(execa));313test('Can use a file URL and a file path on different output file descriptors', () => testFileUrlAndPath(execa));314test('Can use a file path and a file URL on different output file descriptors, sync', () => testFilePathAndUrl(execaSync));315test('Can use a file URL and a file path on different output file descriptors, sync', () => testFileUrlAndPath(execaSync));316317// A single file descriptor can target the same file twice. Its output is a single stream, so it must only be written once.310const testSameFileSameFd = async (t, execaMethod) => {318const testSameFileSameFd = async execaMethod => {319 const filePath = tempfile();320 await execaMethod('noop.js', [foobarString], {stdout: [{file: filePath}, {file: filePath}]});313 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n`);321 assert.equal(await readFile(filePath, 'utf8'), `${foobarString}\n`);322 await rm(filePath);323};324317test('Can use the same file path twice on the same output file descriptor', testSameFileSameFd, execa);318test('Can use the same file path twice on the same output file descriptor, sync', testSameFileSameFd, execaSync);325test('Can use the same file path twice on the same output file descriptor', () => testSameFileSameFd(execa));326test('Can use the same file path twice on the same output file descriptor, sync', () => testSameFileSameFd(execaSync));327328// A file path is resolved before being compared, so equivalent spellings of the same file are detected321const testFilePathNormalized = async (t, execaMethod) => {329const testFilePathNormalized = async execaMethod => {330 const directory = tempfile();331 await mkdir(directory);324 await mkdir(join(directory, 'subdirectory'));325 const filePath = join(directory, 'output.txt');326 // `join()` would normalize this away, but a raw string keeps the `..` segment332 await mkdir(path.join(directory, 'subdirectory'));333 const filePath = path.join(directory, 'output.txt');334 // `path.join()` would normalize this away, but a raw string keeps the `..` segment335 const equivalentFilePath = `${directory}/subdirectory/../output.txt`;336337 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath}, stderr: {file: equivalentFilePath}});330 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);338 assert.equal(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);339 await rm(directory, {recursive: true});340};341334test('Can use equivalent file paths on different output file descriptors', testFilePathNormalized, execa);335test('Can use equivalent file paths on different output file descriptors, sync', testFilePathNormalized, execaSync);342test('Can use equivalent file paths on different output file descriptors', () => testFilePathNormalized(execa));343test('Can use equivalent file paths on different output file descriptors, sync', () => testFilePathNormalized(execaSync));344337const testFilePathAndUrlNormalized = async (t, execaMethod) => {345const testFilePathAndUrlNormalized = async execaMethod => {346 const directory = tempfile();347 await mkdir(directory);340 await mkdir(join(directory, 'subdirectory'));341 const filePath = join(directory, 'output.txt');342 // `join()` would normalize this away, but a raw string keeps the `..` segment348 await mkdir(path.join(directory, 'subdirectory'));349 const filePath = path.join(directory, 'output.txt');350 // `path.join()` would normalize this away, but a raw string keeps the `..` segment351 const equivalentFilePath = `${directory}/subdirectory/../output.txt`;352353 await execaMethod('noop-both.js', [foobarString], {stdout: {file: filePath}, stderr: pathToFileURL(equivalentFilePath)});346 t.is(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);354 assert.equal(await readFile(filePath, 'utf8'), `${foobarString}\n${foobarString}\n`);355 await rm(directory, {recursive: true});356};357350test('Can use an equivalent file URL on different output file descriptors', testFilePathAndUrlNormalized, execa);351test('Can use an equivalent file URL on a different output file descriptor, sync', testFilePathAndUrlNormalized, execaSync);358test('Can use an equivalent file URL on different output file descriptors', () => testFilePathAndUrlNormalized(execa));359test('Can use an equivalent file URL on a different output file descriptor, sync', () => testFilePathAndUrlNormalized(execaSync));
modified:test/stdio/file-descriptor.js+14 added-13 removed
1import assert from 'node:assert/strict';2import {readFile, open, rm} from 'node:fs/promises';2import test from 'ava';3import test from 'node:test';4import tempfile from 'tempfile';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {getStdio} from '../helpers/stdio.js';89setFixtureDirectory();1010const testFileDescriptorOption = async (t, fdNumber, execaMethod) => {11const testFileDescriptorOption = async (fdNumber, execaMethod) => {12 const filePath = tempfile();13 const fileDescriptor = await open(filePath, 'w');14 await execaMethod('noop-fd.js', [`${fdNumber}`, 'foobar'], getStdio(fdNumber, fileDescriptor));14 t.is(await readFile(filePath, 'utf8'), 'foobar');15 assert.equal(await readFile(filePath, 'utf8'), 'foobar');16 await rm(filePath);17 await fileDescriptor.close();18};1919test('pass `stdout` to a file descriptor', testFileDescriptorOption, 1, execa);20test('pass `stderr` to a file descriptor', testFileDescriptorOption, 2, execa);21test('pass `stdio[*]` to a file descriptor', testFileDescriptorOption, 3, execa);22test('pass `stdout` to a file descriptor - sync', testFileDescriptorOption, 1, execaSync);23test('pass `stderr` to a file descriptor - sync', testFileDescriptorOption, 2, execaSync);24test('pass `stdio[*]` to a file descriptor - sync', testFileDescriptorOption, 3, execaSync);20test('pass `stdout` to a file descriptor', () => testFileDescriptorOption(1, execa));21test('pass `stderr` to a file descriptor', () => testFileDescriptorOption(2, execa));22test('pass `stdio[*]` to a file descriptor', () => testFileDescriptorOption(3, execa));23test('pass `stdout` to a file descriptor - sync', () => testFileDescriptorOption(1, execaSync));24test('pass `stderr` to a file descriptor - sync', () => testFileDescriptorOption(2, execaSync));25test('pass `stdio[*]` to a file descriptor - sync', () => testFileDescriptorOption(3, execaSync));2626const testStdinWrite = async (t, fdNumber) => {27const testStdinWrite = async fdNumber => {28 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, 'pipe'));29 subprocess.stdio[fdNumber].end('unicorns');30 const {stdout} = await subprocess;30 t.is(stdout, 'unicorns');31 assert.equal(stdout, 'unicorns');32};3333test('you can write to subprocess.stdin', testStdinWrite, 0);34test('you can write to subprocess.stdio[*]', testStdinWrite, 3);34test('you can write to subprocess.stdin', () => testStdinWrite(0));35test('you can write to subprocess.stdio[*]', () => testStdinWrite(3));
modified:test/stdio/file-path-error.js+88 added-86 removed
1import assert from 'node:assert/strict';2import {readFile, writeFile, rm} from 'node:fs/promises';3import {pathToFileURL} from 'node:url';3import test from 'ava';4import test from 'node:test';5import {pathExists} from 'path-exists';6import tempfile from 'tempfile';7import {assertThrows, assertRejects} from '../helpers/assert.js';8import {execa, execaSync} from '../../index.js';9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10import {identity, getStdio} from '../helpers/stdio.js';11import {foobarString, foobarUppercase} from '../helpers/input.js';
8 unmodified lines
20setFixtureDirectory();2122const nonFileUrl = new URL('https://example.com');2322const testStdioNonFileUrl = (t, fdNumber, execaMethod) => {23 t.throws(() => {24const testStdioNonFileUrl = (fdNumber, execaMethod) => {25 assertThrows(() => {26 execaMethod('empty.js', getStdio(fdNumber, nonFileUrl));27 }, {message: /pathToFileURL/});28};2928test('inputFile cannot be a non-file URL', testStdioNonFileUrl, 'inputFile', execa);29test('stdin cannot be a non-file URL', testStdioNonFileUrl, 0, execa);30test('stdout cannot be a non-file URL', testStdioNonFileUrl, 1, execa);31test('stderr cannot be a non-file URL', testStdioNonFileUrl, 2, execa);32test('stdio[*] cannot be a non-file URL', testStdioNonFileUrl, 3, execa);33test('inputFile cannot be a non-file URL - sync', testStdioNonFileUrl, 'inputFile', execaSync);34test('stdin cannot be a non-file URL - sync', testStdioNonFileUrl, 0, execaSync);35test('stdout cannot be a non-file URL - sync', testStdioNonFileUrl, 1, execaSync);36test('stderr cannot be a non-file URL - sync', testStdioNonFileUrl, 2, execaSync);37test('stdio[*] cannot be a non-file URL - sync', testStdioNonFileUrl, 3, execaSync);30test('inputFile cannot be a non-file URL', () => testStdioNonFileUrl('inputFile', execa));31test('stdin cannot be a non-file URL', () => testStdioNonFileUrl(0, execa));32test('stdout cannot be a non-file URL', () => testStdioNonFileUrl(1, execa));33test('stderr cannot be a non-file URL', () => testStdioNonFileUrl(2, execa));34test('stdio[*] cannot be a non-file URL', () => testStdioNonFileUrl(3, execa));35test('inputFile cannot be a non-file URL - sync', () => testStdioNonFileUrl('inputFile', execaSync));36test('stdin cannot be a non-file URL - sync', () => testStdioNonFileUrl(0, execaSync));37test('stdout cannot be a non-file URL - sync', () => testStdioNonFileUrl(1, execaSync));38test('stderr cannot be a non-file URL - sync', () => testStdioNonFileUrl(2, execaSync));39test('stdio[*] cannot be a non-file URL - sync', () => testStdioNonFileUrl(3, execaSync));4039const testInvalidInputFile = (t, execaMethod) => {40 t.throws(() => {41const testInvalidInputFile = execaMethod => {42 assertThrows(() => {43 execaMethod('empty.js', getStdio('inputFile', false));44 }, {message: /a file path string or a file URL/});45};4645test('inputFile must be a file URL or string', testInvalidInputFile, execa);46test('inputFile must be a file URL or string - sync', testInvalidInputFile, execaSync);47test('inputFile must be a file URL or string', () => testInvalidInputFile(execa));48test('inputFile must be a file URL or string - sync', () => testInvalidInputFile(execaSync));4948const testFilePathObject = (t, fdNumber, execaMethod) => {49 t.throws(() => {50const testFilePathObject = (fdNumber, execaMethod) => {51 assertThrows(() => {52 execaMethod('empty.js', getStdio(fdNumber, foobarString));53 }, {message: /must be used/});54};5554test('stdin must be an object when it is a file path string', testFilePathObject, 0, execa);55test('stdout must be an object when it is a file path string', testFilePathObject, 1, execa);56test('stderr must be an object when it is a file path string', testFilePathObject, 2, execa);57test('stdio[*] must be an object when it is a file path string', testFilePathObject, 3, execa);58test('stdin be an object when it is a file path string - sync', testFilePathObject, 0, execaSync);59test('stdout be an object when it is a file path string - sync', testFilePathObject, 1, execaSync);60test('stderr be an object when it is a file path string - sync', testFilePathObject, 2, execaSync);61test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, 3, execaSync);56test('stdin must be an object when it is a file path string', () => testFilePathObject(0, execa));57test('stdout must be an object when it is a file path string', () => testFilePathObject(1, execa));58test('stderr must be an object when it is a file path string', () => testFilePathObject(2, execa));59test('stdio[*] must be an object when it is a file path string', () => testFilePathObject(3, execa));60test('stdin be an object when it is a file path string - sync', () => testFilePathObject(0, execaSync));61test('stdout be an object when it is a file path string - sync', () => testFilePathObject(1, execaSync));62test('stderr be an object when it is a file path string - sync', () => testFilePathObject(2, execaSync));63test('stdio[*] must be an object when it is a file path string - sync', () => testFilePathObject(3, execaSync));6463const testFileError = async (t, fixtureName, mapFile, fdNumber) => {64 await t.throwsAsync(65const testFileError = async (fixtureName, mapFile, fdNumber) => {66 await assertRejects(67 execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, mapFile('./unknown/file'))),68 {code: 'ENOENT'},69 );70};7170test.serial('inputFile file URL errors should be handled', testFileError, 'stdin-fd.js', pathToFileURL, 'inputFile');71test.serial('stdin file URL errors should be handled', testFileError, 'stdin-fd.js', pathToFileURL, 0);72test.serial('stdout file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 1);73test.serial('stderr file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 2);74test.serial('stdio[*] file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 3);75test.serial('inputFile file path errors should be handled', testFileError, 'stdin-fd.js', identity, 'inputFile');76test.serial('stdin file path errors should be handled', testFileError, 'stdin-fd.js', getAbsolutePath, 0);77test.serial('stdout file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 1);78test.serial('stderr file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 2);79test.serial('stdio[*] file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 3);72test('inputFile file URL errors should be handled', () => testFileError('stdin-fd.js', pathToFileURL, 'inputFile'));73test('stdin file URL errors should be handled', () => testFileError('stdin-fd.js', pathToFileURL, 0));74test('stdout file URL errors should be handled', () => testFileError('noop-fd.js', pathToFileURL, 1));75test('stderr file URL errors should be handled', () => testFileError('noop-fd.js', pathToFileURL, 2));76test('stdio[*] file URL errors should be handled', () => testFileError('noop-fd.js', pathToFileURL, 3));77test('inputFile file path errors should be handled', () => testFileError('stdin-fd.js', identity, 'inputFile'));78test('stdin file path errors should be handled', () => testFileError('stdin-fd.js', getAbsolutePath, 0));79test('stdout file path errors should be handled', () => testFileError('noop-fd.js', getAbsolutePath, 1));80test('stderr file path errors should be handled', () => testFileError('noop-fd.js', getAbsolutePath, 2));81test('stdio[*] file path errors should be handled', () => testFileError('noop-fd.js', getAbsolutePath, 3));8281const testFileErrorSync = (t, mapFile, fdNumber) => {82 t.throws(() => {83const testFileErrorSync = (mapFile, fdNumber) => {84 assertThrows(() => {85 execaSync('empty.js', getStdio(fdNumber, mapFile('./unknown/file')));86 }, {code: 'ENOENT'});87};8887test('inputFile file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 'inputFile');88test('stdin file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 0);89test('stdout file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 1);90test('stderr file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 2);91test('stdio[*] file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 3);92test('inputFile file path errors should be handled - sync', testFileErrorSync, identity, 'inputFile');93test('stdin file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 0);94test('stdout file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 1);95test('stderr file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 2);96test('stdio[*] file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 3);89test('inputFile file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 'inputFile'));90test('stdin file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 0));91test('stdout file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 1));92test('stderr file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 2));93test('stdio[*] file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 3));94test('inputFile file path errors should be handled - sync', () => testFileErrorSync(identity, 'inputFile'));95test('stdin file path errors should be handled - sync', () => testFileErrorSync(getAbsolutePath, 0));96test('stdout file path errors should be handled - sync', () => testFileErrorSync(getAbsolutePath, 1));97test('stderr file path errors should be handled - sync', () => testFileErrorSync(getAbsolutePath, 2));98test('stdio[*] file path errors should be handled - sync', () => testFileErrorSync(getAbsolutePath, 3));9998const testInputFileObject = async (t, fdNumber, mapFile, execaMethod) => {100const testInputFileObject = async (fdNumber, mapFile, execaMethod) => {101 const filePath = tempfile();102 await writeFile(filePath, foobarString);101 t.throws(() => {103 assertThrows(() => {104 execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [105 new Uint8Array(),106 mapFile(filePath),107 serializeGenerator(true),
1 unmodified line
109 }, {message: /cannot use both files and transforms in objectMode/});110 await rm(filePath);111};112111test('stdin cannot use objectMode together with input file paths', testInputFileObject, 0, getAbsolutePath, execa);112test('stdin cannot use objectMode together with input file URLs', testInputFileObject, 0, pathToFileURL, execa);113test('stdio[*] cannot use objectMode together with input file paths', testInputFileObject, 3, getAbsolutePath, execa);114test('stdio[*] cannot use objectMode together with input file URLs', testInputFileObject, 3, pathToFileURL, execa);115test('stdin cannot use objectMode together with input file paths, sync', testInputFileObject, 0, getAbsolutePath, execaSync);116test('stdin cannot use objectMode together with input file URLs, sync', testInputFileObject, 0, pathToFileURL, execaSync);113test('stdin cannot use objectMode together with input file paths', () => testInputFileObject(0, getAbsolutePath, execa));114test('stdin cannot use objectMode together with input file URLs', () => testInputFileObject(0, pathToFileURL, execa));115test('stdio[*] cannot use objectMode together with input file paths', () => testInputFileObject(3, getAbsolutePath, execa));116test('stdio[*] cannot use objectMode together with input file URLs', () => testInputFileObject(3, pathToFileURL, execa));117test('stdin cannot use objectMode together with input file paths, sync', () => testInputFileObject(0, getAbsolutePath, execaSync));118test('stdin cannot use objectMode together with input file URLs, sync', () => testInputFileObject(0, pathToFileURL, execaSync));119118const testOutputFileObject = async (t, fdNumber, mapFile, execaMethod) => {120const testOutputFileObject = async (fdNumber, mapFile, execaMethod) => {121 const filePath = tempfile();120 t.throws(() => {122 assertThrows(() => {123 execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [124 outputObjectGenerator(),125 mapFile(filePath),126 ]));127 }, {message: /cannot use both files and transforms in objectMode/});126 t.false(await pathExists(filePath));128 assert.ok(!await pathExists(filePath));129};130129test('stdout cannot use objectMode together with output file paths', testOutputFileObject, 1, getAbsolutePath, execa);130test('stdout cannot use objectMode together with output file URLs', testOutputFileObject, 1, pathToFileURL, execa);131test('stderr cannot use objectMode together with output file paths', testOutputFileObject, 2, getAbsolutePath, execa);132test('stderr cannot use objectMode together with output file URLs', testOutputFileObject, 2, pathToFileURL, execa);133test('stdio[*] cannot use objectMode together with output file paths', testOutputFileObject, 3, getAbsolutePath, execa);134test('stdio[*] cannot use objectMode together with output file URLs', testOutputFileObject, 3, pathToFileURL, execa);135test('stdout cannot use objectMode together with output file paths, sync', testOutputFileObject, 1, getAbsolutePath, execaSync);136test('stdout cannot use objectMode together with output file URLs, sync', testOutputFileObject, 1, pathToFileURL, execaSync);137test('stderr cannot use objectMode together with output file paths, sync', testOutputFileObject, 2, getAbsolutePath, execaSync);138test('stderr cannot use objectMode together with output file URLs, sync', testOutputFileObject, 2, pathToFileURL, execaSync);139test('stdio[*] cannot use objectMode together with output file paths, sync', testOutputFileObject, 3, getAbsolutePath, execaSync);140test('stdio[*] cannot use objectMode together with output file URLs, sync', testOutputFileObject, 3, pathToFileURL, execaSync);131test('stdout cannot use objectMode together with output file paths', () => testOutputFileObject(1, getAbsolutePath, execa));132test('stdout cannot use objectMode together with output file URLs', () => testOutputFileObject(1, pathToFileURL, execa));133test('stderr cannot use objectMode together with output file paths', () => testOutputFileObject(2, getAbsolutePath, execa));134test('stderr cannot use objectMode together with output file URLs', () => testOutputFileObject(2, pathToFileURL, execa));135test('stdio[*] cannot use objectMode together with output file paths', () => testOutputFileObject(3, getAbsolutePath, execa));136test('stdio[*] cannot use objectMode together with output file URLs', () => testOutputFileObject(3, pathToFileURL, execa));137test('stdout cannot use objectMode together with output file paths, sync', () => testOutputFileObject(1, getAbsolutePath, execaSync));138test('stdout cannot use objectMode together with output file URLs, sync', () => testOutputFileObject(1, pathToFileURL, execaSync));139test('stderr cannot use objectMode together with output file paths, sync', () => testOutputFileObject(2, getAbsolutePath, execaSync));140test('stderr cannot use objectMode together with output file URLs, sync', () => testOutputFileObject(2, pathToFileURL, execaSync));141test('stdio[*] cannot use objectMode together with output file paths, sync', () => testOutputFileObject(3, getAbsolutePath, execaSync));142test('stdio[*] cannot use objectMode together with output file URLs, sync', () => testOutputFileObject(3, pathToFileURL, execaSync));143142test('Generator error stops writing to output file', async t => {144test('Generator error stops writing to output file', async () => {145 const filePath = tempfile();146 const cause = new Error(foobarString);145 const error = await t.throwsAsync(execa('noop.js', {147 const error = await assertRejects(execa('noop.js', {148 stdout: [throwingGenerator(cause)(), getAbsolutePath(filePath)],149 }));148 t.is(error.cause, cause);149 t.is(await readFile(filePath, 'utf8'), '');150 assert.equal(error.cause, cause);151 assert.equal(await readFile(filePath, 'utf8'), '');152});153152test('Generator error does not create output file, sync', async t => {154test('Generator error does not create output file, sync', async () => {155 const filePath = tempfile();156 const cause = new Error(foobarString);155 const error = t.throws(() => {157 const error = assertThrows(() => {158 execaSync('noop.js', {159 stdout: [throwingGenerator(cause)(), getAbsolutePath(filePath)],160 });161 });160 t.is(error.cause, cause);161 t.false(await pathExists(filePath));162 assert.equal(error.cause, cause);163 assert.ok(!await pathExists(filePath));164});165164test('Output file error still returns transformed output, sync', async t => {166test('Output file error still returns transformed output, sync', async () => {167 const filePath = tempfile();166 const {stdout} = t.throws(() => {168 const {stdout} = assertThrows(() => {169 execaSync('noop-fd.js', ['1', foobarString], {170 stdout: [uppercaseGenerator(), getAbsolutePath('./unknown/file')],171 });172 }, {code: 'ENOENT'});171 t.false(await pathExists(filePath));172 t.is(stdout, foobarUppercase);173 assert.ok(!await pathExists(filePath));174 assert.equal(stdout, foobarUppercase);175});
modified:test/stdio/file-path-main.js+105 added-107 removed
1import assert from 'node:assert/strict';2import {readFile, writeFile, rm} from 'node:fs/promises';3import path from 'node:path';4import process from 'node:process';5import {pathToFileURL} from 'node:url';5import test from 'ava';6import test from 'node:test';7import tempfile from 'tempfile';8import {assertRejects} from '../helpers/assert.js';9import {execa, execaSync} from '../../index.js';10import {setFixtureDirectory} from '../helpers/fixtures-directory.js';11import {identity, getStdio} from '../helpers/stdio.js';12import {
11 unmodified lines
24 if (fdNumberOrName === 'string') {25 return {input: foobarString};26 }2726 if (fdNumberOrName === 'binary') {27 return {input: foobarUint8Array};28 }2930 return getStdioInputFile(fdNumberOrName, file);28 return fdNumberOrName === 'binary' ? {input: foobarUint8Array} : getStdioInputFile(fdNumberOrName, file);29};3031const getStdioInputFile = (fdNumberOrName, file) => getStdio(fdNumberOrName, typeof fdNumberOrName === 'string' ? file : {file});3235const testStdinFile = async (t, mapFilePath, fdNumber, execaMethod) => {33const testStdinFile = async (mapFilePath, fdNumber, execaMethod) => {34 const filePath = tempfile();35 await writeFile(filePath, foobarString);36 const {stdout} = await execaMethod('stdin.js', getStdio(fdNumber, mapFilePath(filePath)));39 t.is(stdout, foobarString);37 assert.equal(stdout, foobarString);38 await rm(filePath);39};4043test('inputFile can be a file URL', testStdinFile, pathToFileURL, 'inputFile', execa);44test('stdin can be a file URL', testStdinFile, pathToFileURL, 0, execa);45test('inputFile can be an absolute file path', testStdinFile, identity, 'inputFile', execa);46test('stdin can be an absolute file path', testStdinFile, getAbsolutePath, 0, execa);47test('inputFile can be a relative file path', testStdinFile, identity, 'inputFile', execa);48test('stdin can be a relative file path', testStdinFile, getRelativePath, 0, execa);49test('inputFile can be a file URL - sync', testStdinFile, pathToFileURL, 'inputFile', execaSync);50test('stdin can be a file URL - sync', testStdinFile, pathToFileURL, 0, execaSync);51test('inputFile can be an absolute file path - sync', testStdinFile, identity, 'inputFile', execaSync);52test('stdin can be an absolute file path - sync', testStdinFile, getAbsolutePath, 0, execaSync);53test('inputFile can be a relative file path - sync', testStdinFile, identity, 'inputFile', execaSync);54test('stdin can be a relative file path - sync', testStdinFile, getRelativePath, 0, execaSync);41test('inputFile can be a file URL', () => testStdinFile(pathToFileURL, 'inputFile', execa));42test('stdin can be a file URL', () => testStdinFile(pathToFileURL, 0, execa));43test('inputFile can be an absolute file path', () => testStdinFile(identity, 'inputFile', execa));44test('stdin can be an absolute file path', () => testStdinFile(getAbsolutePath, 0, execa));45test('inputFile can be a relative file path', () => testStdinFile(identity, 'inputFile', execa));46test('stdin can be a relative file path', () => testStdinFile(getRelativePath, 0, execa));47test('inputFile can be a file URL - sync', () => testStdinFile(pathToFileURL, 'inputFile', execaSync));48test('stdin can be a file URL - sync', () => testStdinFile(pathToFileURL, 0, execaSync));49test('inputFile can be an absolute file path - sync', () => testStdinFile(identity, 'inputFile', execaSync));50test('stdin can be an absolute file path - sync', () => testStdinFile(getAbsolutePath, 0, execaSync));51test('inputFile can be a relative file path - sync', () => testStdinFile(identity, 'inputFile', execaSync));52test('stdin can be a relative file path - sync', () => testStdinFile(getRelativePath, 0, execaSync));5356const testOutputFile = async (t, mapFile, fdNumber, execaMethod) => {54const testOutputFile = async (mapFile, fdNumber, execaMethod) => {55 const filePath = tempfile();56 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, mapFile(filePath)));59 t.is(await readFile(filePath, 'utf8'), foobarString);57 assert.equal(await readFile(filePath, 'utf8'), foobarString);58 await rm(filePath);59};6063test('stdout can be a file URL', testOutputFile, pathToFileURL, 1, execa);64test('stderr can be a file URL', testOutputFile, pathToFileURL, 2, execa);65test('stdio[*] can be a file URL', testOutputFile, pathToFileURL, 3, execa);66test('stdout can be an absolute file path', testOutputFile, getAbsolutePath, 1, execa);67test('stderr can be an absolute file path', testOutputFile, getAbsolutePath, 2, execa);68test('stdio[*] can be an absolute file path', testOutputFile, getAbsolutePath, 3, execa);69test('stdout can be a relative file path', testOutputFile, getRelativePath, 1, execa);70test('stderr can be a relative file path', testOutputFile, getRelativePath, 2, execa);71test('stdio[*] can be a relative file path', testOutputFile, getRelativePath, 3, execa);72test('stdout can be a file URL - sync', testOutputFile, pathToFileURL, 1, execaSync);73test('stderr can be a file URL - sync', testOutputFile, pathToFileURL, 2, execaSync);74test('stdio[*] can be a file URL - sync', testOutputFile, pathToFileURL, 3, execaSync);75test('stdout can be an absolute file path - sync', testOutputFile, getAbsolutePath, 1, execaSync);76test('stderr can be an absolute file path - sync', testOutputFile, getAbsolutePath, 2, execaSync);77test('stdio[*] can be an absolute file path - sync', testOutputFile, getAbsolutePath, 3, execaSync);78test('stdout can be a relative file path - sync', testOutputFile, getRelativePath, 1, execaSync);79test('stderr can be a relative file path - sync', testOutputFile, getRelativePath, 2, execaSync);80test('stdio[*] can be a relative file path - sync', testOutputFile, getRelativePath, 3, execaSync);61test('stdout can be a file URL', () => testOutputFile(pathToFileURL, 1, execa));62test('stderr can be a file URL', () => testOutputFile(pathToFileURL, 2, execa));63test('stdio[*] can be a file URL', () => testOutputFile(pathToFileURL, 3, execa));64test('stdout can be an absolute file path', () => testOutputFile(getAbsolutePath, 1, execa));65test('stderr can be an absolute file path', () => testOutputFile(getAbsolutePath, 2, execa));66test('stdio[*] can be an absolute file path', () => testOutputFile(getAbsolutePath, 3, execa));67test('stdout can be a relative file path', () => testOutputFile(getRelativePath, 1, execa));68test('stderr can be a relative file path', () => testOutputFile(getRelativePath, 2, execa));69test('stdio[*] can be a relative file path', () => testOutputFile(getRelativePath, 3, execa));70test('stdout can be a file URL - sync', () => testOutputFile(pathToFileURL, 1, execaSync));71test('stderr can be a file URL - sync', () => testOutputFile(pathToFileURL, 2, execaSync));72test('stdio[*] can be a file URL - sync', () => testOutputFile(pathToFileURL, 3, execaSync));73test('stdout can be an absolute file path - sync', () => testOutputFile(getAbsolutePath, 1, execaSync));74test('stderr can be an absolute file path - sync', () => testOutputFile(getAbsolutePath, 2, execaSync));75test('stdio[*] can be an absolute file path - sync', () => testOutputFile(getAbsolutePath, 3, execaSync));76test('stdout can be a relative file path - sync', () => testOutputFile(getRelativePath, 1, execaSync));77test('stderr can be a relative file path - sync', () => testOutputFile(getRelativePath, 2, execaSync));78test('stdio[*] can be a relative file path - sync', () => testOutputFile(getRelativePath, 3, execaSync));7982const testInputFileValidUrl = async (t, fdNumber, execaMethod) => {80const testInputFileValidUrl = async (fdNumber, execaMethod) => {81 const filePath = tempfile();82 await writeFile(filePath, foobarString);83 const currentCwd = process.cwd();84 process.chdir(path.dirname(filePath));8586 try {87 const {stdout} = await execaMethod('stdin.js', getStdioInputFile(fdNumber, path.basename(filePath)));90 t.is(stdout, foobarString);88 assert.equal(stdout, foobarString);89 } finally {90 process.chdir(currentCwd);91 await rm(filePath);92 }93};9497test.serial('inputFile does not need to start with . when being a relative file path', testInputFileValidUrl, 'inputFile', execa);98test.serial('stdin does not need to start with . when being a relative file path', testInputFileValidUrl, 0, execa);99test.serial('inputFile does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 'inputFile', execaSync);100test.serial('stdin does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 0, execaSync);95test('inputFile does not need to start with . when being a relative file path', () => testInputFileValidUrl('inputFile', execa));96test('stdin does not need to start with . when being a relative file path', () => testInputFileValidUrl(0, execa));97test('inputFile does not need to start with . when being a relative file path - sync', () => testInputFileValidUrl('inputFile', execaSync));98test('stdin does not need to start with . when being a relative file path - sync', () => testInputFileValidUrl(0, execaSync));99102const testMultipleInputs = async (t, indices, execaMethod) => {100const testMultipleInputs = async (indices, execaMethod) => {101 const filePath = tempfile();102 await writeFile(filePath, foobarString);103 const options = Object.assign({}, ...indices.map(fdNumber => getStdioInput(fdNumber, filePath)));104 const {stdout} = await execaMethod('stdin.js', options);107 t.is(stdout, foobarString.repeat(indices.length));105 assert.equal(stdout, foobarString.repeat(indices.length));106 await rm(filePath);107};108111test('inputFile can be set', testMultipleInputs, ['inputFile'], runExeca);112test('inputFile can be set - sync', testMultipleInputs, ['inputFile'], runExecaSync);113test('inputFile can be set with $', testMultipleInputs, ['inputFile'], runScript);114test('inputFile can be set with $.sync', testMultipleInputs, ['inputFile'], runScriptSync);115test('input String and inputFile can be both set', testMultipleInputs, ['inputFile', 'string'], execa);116test('input String and stdin can be both set', testMultipleInputs, [0, 'string'], execa);117test('input Uint8Array and inputFile can be both set', testMultipleInputs, ['inputFile', 'binary'], execa);118test('input Uint8Array and stdin can be both set', testMultipleInputs, [0, 'binary'], execa);119test('stdin and inputFile can be both set', testMultipleInputs, [0, 'inputFile'], execa);120test('input String, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'string'], execa);121test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'binary'], execa);122test('input String and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'string'], execaSync);123test('input String and stdin can be both set - sync', testMultipleInputs, [0, 'string'], execaSync);124test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'binary'], execaSync);125test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [0, 'binary'], execaSync);126test('stdin and inputFile can be both set - sync', testMultipleInputs, [0, 'inputFile'], execaSync);127test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'string'], execaSync);128test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'binary'], execaSync);109test('inputFile can be set', () => testMultipleInputs(['inputFile'], runExeca));110test('inputFile can be set - sync', () => testMultipleInputs(['inputFile'], runExecaSync));111test('inputFile can be set with $', () => testMultipleInputs(['inputFile'], runScript));112test('inputFile can be set with $.sync', () => testMultipleInputs(['inputFile'], runScriptSync));113test('input String and inputFile can be both set', () => testMultipleInputs(['inputFile', 'string'], execa));114test('input String and stdin can be both set', () => testMultipleInputs([0, 'string'], execa));115test('input Uint8Array and inputFile can be both set', () => testMultipleInputs(['inputFile', 'binary'], execa));116test('input Uint8Array and stdin can be both set', () => testMultipleInputs([0, 'binary'], execa));117test('stdin and inputFile can be both set', () => testMultipleInputs([0, 'inputFile'], execa));118test('input String, stdin and inputFile can be all set', () => testMultipleInputs(['inputFile', 0, 'string'], execa));119test('input Uint8Array, stdin and inputFile can be all set', () => testMultipleInputs(['inputFile', 0, 'binary'], execa));120test('input String and inputFile can be both set - sync', () => testMultipleInputs(['inputFile', 'string'], execaSync));121test('input String and stdin can be both set - sync', () => testMultipleInputs([0, 'string'], execaSync));122test('input Uint8Array and inputFile can be both set - sync', () => testMultipleInputs(['inputFile', 'binary'], execaSync));123test('input Uint8Array and stdin can be both set - sync', () => testMultipleInputs([0, 'binary'], execaSync));124test('stdin and inputFile can be both set - sync', () => testMultipleInputs([0, 'inputFile'], execaSync));125test('input String, stdin and inputFile can be all set - sync', () => testMultipleInputs(['inputFile', 0, 'string'], execaSync));126test('input Uint8Array, stdin and inputFile can be all set - sync', () => testMultipleInputs(['inputFile', 0, 'binary'], execaSync));127130const testMultipleOutputs = async (t, mapFile, fdNumber, execaMethod) => {128const testMultipleOutputs = async (mapFile, fdNumber, execaMethod) => {129 const filePath = tempfile();130 const filePathTwo = tempfile();131 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [mapFile(filePath), mapFile(filePathTwo)]));134 t.is(await readFile(filePath, 'utf8'), foobarString);135 t.is(await readFile(filePathTwo, 'utf8'), foobarString);132 assert.equal(await readFile(filePath, 'utf8'), foobarString);133 assert.equal(await readFile(filePathTwo, 'utf8'), foobarString);134 await Promise.all([rm(filePath), rm(filePathTwo)]);135};136139test('stdout can be two file URLs', testMultipleOutputs, pathToFileURL, 1, execa);140test('stdout can be two file paths', testMultipleOutputs, getAbsolutePath, 1, execa);141test('stdout can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 1, execaSync);142test('stdout can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 1, execaSync);143test('stderr can be two file URLs', testMultipleOutputs, pathToFileURL, 2, execa);144test('stderr can be two file paths', testMultipleOutputs, getAbsolutePath, 2, execa);145test('stderr can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 2, execaSync);146test('stderr can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 2, execaSync);147test('stdio[*] can be two file URLs', testMultipleOutputs, pathToFileURL, 3, execa);148test('stdio[*] can be two file paths', testMultipleOutputs, getAbsolutePath, 3, execa);149test('stdio[*] can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 3, execaSync);150test('stdio[*] can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 3, execaSync);137test('stdout can be two file URLs', () => testMultipleOutputs(pathToFileURL, 1, execa));138test('stdout can be two file paths', () => testMultipleOutputs(getAbsolutePath, 1, execa));139test('stdout can be two file URLs - sync', () => testMultipleOutputs(pathToFileURL, 1, execaSync));140test('stdout can be two file paths - sync', () => testMultipleOutputs(getAbsolutePath, 1, execaSync));141test('stderr can be two file URLs', () => testMultipleOutputs(pathToFileURL, 2, execa));142test('stderr can be two file paths', () => testMultipleOutputs(getAbsolutePath, 2, execa));143test('stderr can be two file URLs - sync', () => testMultipleOutputs(pathToFileURL, 2, execaSync));144test('stderr can be two file paths - sync', () => testMultipleOutputs(getAbsolutePath, 2, execaSync));145test('stdio[*] can be two file URLs', () => testMultipleOutputs(pathToFileURL, 3, execa));146test('stdio[*] can be two file paths', () => testMultipleOutputs(getAbsolutePath, 3, execa));147test('stdio[*] can be two file URLs - sync', () => testMultipleOutputs(pathToFileURL, 3, execaSync));148test('stdio[*] can be two file paths - sync', () => testMultipleOutputs(getAbsolutePath, 3, execaSync));149152const testInputFileHanging = async (t, mapFilePath) => {150const testInputFileHanging = async mapFilePath => {151 const filePath = tempfile();152 await writeFile(filePath, foobarString);155 await t.throwsAsync(execa('stdin.js', {stdin: mapFilePath(filePath), timeout: 1}), {message: /timed out/});153 await assertRejects(execa('stdin.js', {stdin: mapFilePath(filePath), timeout: 1}), {message: /timed out/});154 await rm(filePath);155};156159test('Passing an input file path when subprocess exits does not make promise hang', testInputFileHanging, getAbsolutePath);160test('Passing an input file URL when subprocess exits does not make promise hang', testInputFileHanging, pathToFileURL);157test('Passing an input file path when subprocess exits does not make promise hang', () => testInputFileHanging(getAbsolutePath));158test('Passing an input file URL when subprocess exits does not make promise hang', () => testInputFileHanging(pathToFileURL));159162const testOverwriteFile = async (t, fdNumber, execaMethod, append) => {160const testOverwriteFile = async (fdNumber, execaMethod, append) => {161 const filePath = tempfile();162 await writeFile(filePath, '.');163 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, {file: filePath, append}));166 t.is(await readFile(filePath, 'utf8'), foobarString);164 assert.equal(await readFile(filePath, 'utf8'), foobarString);165 await rm(filePath);166};167170test('Overwrite by default to stdout', testOverwriteFile, 1, execa, undefined);171test('Overwrite by default to stderr', testOverwriteFile, 2, execa, undefined);172test('Overwrite by default to stdio[*]', testOverwriteFile, 3, execa, undefined);173test('Overwrite by default to stdout - sync', testOverwriteFile, 1, execaSync, undefined);174test('Overwrite by default to stderr - sync', testOverwriteFile, 2, execaSync, undefined);175test('Overwrite by default to stdio[*] - sync', testOverwriteFile, 3, execaSync, undefined);176test('Overwrite with append false to stdout', testOverwriteFile, 1, execa, false);177test('Overwrite with append false to stderr', testOverwriteFile, 2, execa, false);178test('Overwrite with append false to stdio[*]', testOverwriteFile, 3, execa, false);179test('Overwrite with append false to stdout - sync', testOverwriteFile, 1, execaSync, false);180test('Overwrite with append false to stderr - sync', testOverwriteFile, 2, execaSync, false);181test('Overwrite with append false to stdio[*] - sync', testOverwriteFile, 3, execaSync, false);168test('Overwrite by default to stdout', () => testOverwriteFile(1, execa, undefined));169test('Overwrite by default to stderr', () => testOverwriteFile(2, execa, undefined));170test('Overwrite by default to stdio[*]', () => testOverwriteFile(3, execa, undefined));171test('Overwrite by default to stdout - sync', () => testOverwriteFile(1, execaSync, undefined));172test('Overwrite by default to stderr - sync', () => testOverwriteFile(2, execaSync, undefined));173test('Overwrite by default to stdio[*] - sync', () => testOverwriteFile(3, execaSync, undefined));174test('Overwrite with append false to stdout', () => testOverwriteFile(1, execa, false));175test('Overwrite with append false to stderr', () => testOverwriteFile(2, execa, false));176test('Overwrite with append false to stdio[*]', () => testOverwriteFile(3, execa, false));177test('Overwrite with append false to stdout - sync', () => testOverwriteFile(1, execaSync, false));178test('Overwrite with append false to stderr - sync', () => testOverwriteFile(2, execaSync, false));179test('Overwrite with append false to stdio[*] - sync', () => testOverwriteFile(3, execaSync, false));180183const testAppendFile = async (t, fdNumber, execaMethod) => {181const testAppendFile = async (fdNumber, execaMethod) => {182 const filePath = tempfile();183 await writeFile(filePath, '.');184 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, {file: filePath, append: true}));187 t.is(await readFile(filePath, 'utf8'), `.${foobarString}`);185 assert.equal(await readFile(filePath, 'utf8'), `.${foobarString}`);186 await rm(filePath);187};188191test('Can append to stdout', testAppendFile, 1, execa);192test('Can append to stderr', testAppendFile, 2, execa);193test('Can append to stdio[*]', testAppendFile, 3, execa);194test('Can append to stdout - sync', testAppendFile, 1, execaSync);195test('Can append to stderr - sync', testAppendFile, 2, execaSync);196test('Can append to stdio[*] - sync', testAppendFile, 3, execaSync);189test('Can append to stdout', () => testAppendFile(1, execa));190test('Can append to stderr', () => testAppendFile(2, execa));191test('Can append to stdio[*]', () => testAppendFile(3, execa));192test('Can append to stdout - sync', () => testAppendFile(1, execaSync));193test('Can append to stderr - sync', () => testAppendFile(2, execaSync));194test('Can append to stdio[*] - sync', () => testAppendFile(3, execaSync));
modified:test/stdio/file-path-mixed.js+46 added-45 removed
1import assert from 'node:assert/strict';2import {readFile, writeFile, rm} from 'node:fs/promises';3import {pathToFileURL} from 'node:url';3import test from 'ava';4import test from 'node:test';5import tempfile from 'tempfile';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {getStdio} from '../helpers/stdio.js';
2 unmodified lines
11import {getAbsolutePath} from '../helpers/file-path.js';1213setFixtureDirectory();1414const testInputFileTransform = async (t, fdNumber, mapFile, execaMethod) => {15const testInputFileTransform = async (fdNumber, mapFile, execaMethod) => {16 const filePath = tempfile();17 await writeFile(filePath, foobarString);18 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [19 new Uint8Array(),20 mapFile(filePath),21 uppercaseGenerator(),22 ]));22 t.is(stdout, foobarUppercase);23 assert.equal(stdout, foobarUppercase);24 await rm(filePath);25};2626test('stdin can use generators together with input file paths', testInputFileTransform, 0, getAbsolutePath, execa);27test('stdin can use generators together with input file URLs', testInputFileTransform, 0, pathToFileURL, execa);28test('stdio[*] can use generators together with input file paths', testInputFileTransform, 3, getAbsolutePath, execa);29test('stdio[*] can use generators together with input file URLs', testInputFileTransform, 3, pathToFileURL, execa);30test('stdin can use generators together with input file paths, sync', testInputFileTransform, 0, getAbsolutePath, execaSync);31test('stdin can use generators together with input file URLs, sync', testInputFileTransform, 0, pathToFileURL, execaSync);27test('stdin can use generators together with input file paths', () => testInputFileTransform(0, getAbsolutePath, execa));28test('stdin can use generators together with input file URLs', () => testInputFileTransform(0, pathToFileURL, execa));29test('stdio[*] can use generators together with input file paths', () => testInputFileTransform(3, getAbsolutePath, execa));30test('stdio[*] can use generators together with input file URLs', () => testInputFileTransform(3, pathToFileURL, execa));31test('stdin can use generators together with input file paths, sync', () => testInputFileTransform(0, getAbsolutePath, execaSync));32test('stdin can use generators together with input file URLs, sync', () => testInputFileTransform(0, pathToFileURL, execaSync));3333const testOutputFileTransform = async (t, fdNumber, mapFile, execaMethod) => {34const testOutputFileTransform = async (fdNumber, mapFile, execaMethod) => {35 const filePath = tempfile();36 await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [37 uppercaseGenerator(),38 mapFile(filePath),39 ]));39 t.is(await readFile(filePath, 'utf8'), `${foobarUppercase}\n`);40 assert.equal(await readFile(filePath, 'utf8'), `${foobarUppercase}\n`);41 await rm(filePath);42};4343test('stdout can use generators together with output file paths', testOutputFileTransform, 1, getAbsolutePath, execa);44test('stdout can use generators together with output file URLs', testOutputFileTransform, 1, pathToFileURL, execa);45test('stderr can use generators together with output file paths', testOutputFileTransform, 2, getAbsolutePath, execa);46test('stderr can use generators together with output file URLs', testOutputFileTransform, 2, pathToFileURL, execa);47test('stdio[*] can use generators together with output file paths', testOutputFileTransform, 3, getAbsolutePath, execa);48test('stdio[*] can use generators together with output file URLs', testOutputFileTransform, 3, pathToFileURL, execa);49test('stdout can use generators together with output file paths, sync', testOutputFileTransform, 1, getAbsolutePath, execaSync);50test('stdout can use generators together with output file URLs, sync', testOutputFileTransform, 1, pathToFileURL, execaSync);51test('stderr can use generators together with output file paths, sync', testOutputFileTransform, 2, getAbsolutePath, execaSync);52test('stderr can use generators together with output file URLs, sync', testOutputFileTransform, 2, pathToFileURL, execaSync);53test('stdio[*] can use generators together with output file paths, sync', testOutputFileTransform, 3, getAbsolutePath, execaSync);54test('stdio[*] can use generators together with output file URLs, sync', testOutputFileTransform, 3, pathToFileURL, execaSync);44test('stdout can use generators together with output file paths', () => testOutputFileTransform(1, getAbsolutePath, execa));45test('stdout can use generators together with output file URLs', () => testOutputFileTransform(1, pathToFileURL, execa));46test('stderr can use generators together with output file paths', () => testOutputFileTransform(2, getAbsolutePath, execa));47test('stderr can use generators together with output file URLs', () => testOutputFileTransform(2, pathToFileURL, execa));48test('stdio[*] can use generators together with output file paths', () => testOutputFileTransform(3, getAbsolutePath, execa));49test('stdio[*] can use generators together with output file URLs', () => testOutputFileTransform(3, pathToFileURL, execa));50test('stdout can use generators together with output file paths, sync', () => testOutputFileTransform(1, getAbsolutePath, execaSync));51test('stdout can use generators together with output file URLs, sync', () => testOutputFileTransform(1, pathToFileURL, execaSync));52test('stderr can use generators together with output file paths, sync', () => testOutputFileTransform(2, getAbsolutePath, execaSync));53test('stderr can use generators together with output file URLs, sync', () => testOutputFileTransform(2, pathToFileURL, execaSync));54test('stdio[*] can use generators together with output file paths, sync', () => testOutputFileTransform(3, getAbsolutePath, execaSync));55test('stdio[*] can use generators together with output file URLs, sync', () => testOutputFileTransform(3, pathToFileURL, execaSync));5656const testOutputFileLines = async (t, fdNumber, mapFile, execaMethod) => {57const testOutputFileLines = async (fdNumber, mapFile, execaMethod) => {58 const filePath = tempfile();59 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, foobarString], {60 ...getStdio(fdNumber, mapFile(filePath)),61 lines: true,62 });62 t.deepEqual(stdio[fdNumber], [foobarString]);63 t.is(await readFile(filePath, 'utf8'), foobarString);63 assert.deepEqual(stdio[fdNumber], [foobarString]);64 assert.equal(await readFile(filePath, 'utf8'), foobarString);65 await rm(filePath);66};6767test('stdout can use "lines: true" together with output file paths', testOutputFileLines, 1, getAbsolutePath, execa);68test('stdout can use "lines: true" together with output file URLs', testOutputFileLines, 1, pathToFileURL, execa);69test('stderr can use "lines: true" together with output file paths', testOutputFileLines, 2, getAbsolutePath, execa);70test('stderr can use "lines: true" together with output file URLs', testOutputFileLines, 2, pathToFileURL, execa);71test('stdio[*] can use "lines: true" together with output file paths', testOutputFileLines, 3, getAbsolutePath, execa);72test('stdio[*] can use "lines: true" together with output file URLs', testOutputFileLines, 3, pathToFileURL, execa);73test('stdout can use "lines: true" together with output file paths, sync', testOutputFileLines, 1, getAbsolutePath, execaSync);74test('stdout can use "lines: true" together with output file URLs, sync', testOutputFileLines, 1, pathToFileURL, execaSync);75test('stderr can use "lines: true" together with output file paths, sync', testOutputFileLines, 2, getAbsolutePath, execaSync);76test('stderr can use "lines: true" together with output file URLs, sync', testOutputFileLines, 2, pathToFileURL, execaSync);77test('stdio[*] can use "lines: true" together with output file paths, sync', testOutputFileLines, 3, getAbsolutePath, execaSync);78test('stdio[*] can use "lines: true" together with output file URLs, sync', testOutputFileLines, 3, pathToFileURL, execaSync);68test('stdout can use "lines: true" together with output file paths', () => testOutputFileLines(1, getAbsolutePath, execa));69test('stdout can use "lines: true" together with output file URLs', () => testOutputFileLines(1, pathToFileURL, execa));70test('stderr can use "lines: true" together with output file paths', () => testOutputFileLines(2, getAbsolutePath, execa));71test('stderr can use "lines: true" together with output file URLs', () => testOutputFileLines(2, pathToFileURL, execa));72test('stdio[*] can use "lines: true" together with output file paths', () => testOutputFileLines(3, getAbsolutePath, execa));73test('stdio[*] can use "lines: true" together with output file URLs', () => testOutputFileLines(3, pathToFileURL, execa));74test('stdout can use "lines: true" together with output file paths, sync', () => testOutputFileLines(1, getAbsolutePath, execaSync));75test('stdout can use "lines: true" together with output file URLs, sync', () => testOutputFileLines(1, pathToFileURL, execaSync));76test('stderr can use "lines: true" together with output file paths, sync', () => testOutputFileLines(2, getAbsolutePath, execaSync));77test('stderr can use "lines: true" together with output file URLs, sync', () => testOutputFileLines(2, pathToFileURL, execaSync));78test('stdio[*] can use "lines: true" together with output file paths, sync', () => testOutputFileLines(3, getAbsolutePath, execaSync));79test('stdio[*] can use "lines: true" together with output file URLs, sync', () => testOutputFileLines(3, pathToFileURL, execaSync));8080const testOutputFileNoBuffer = async (t, buffer, execaMethod) => {81const testOutputFileNoBuffer = async (buffer, execaMethod) => {82 const filePath = tempfile();83 const {stdout} = await execaMethod('noop-fd.js', ['1', foobarString], {84 stdout: getAbsolutePath(filePath),85 buffer,86 });86 t.is(stdout, undefined);87 t.is(await readFile(filePath, 'utf8'), foobarString);87 assert.equal(stdout, undefined);88 assert.equal(await readFile(filePath, 'utf8'), foobarString);89 await rm(filePath);90};9191test('stdout can use "buffer: false" together with output file paths', testOutputFileNoBuffer, false, execa);92test('stdout can use "buffer: false" together with output file paths, fd-specific', testOutputFileNoBuffer, {stdout: false}, execa);93test('stdout can use "buffer: false" together with output file paths, sync', testOutputFileNoBuffer, false, execaSync);94test('stdout can use "buffer: false" together with output file paths, fd-specific, sync', testOutputFileNoBuffer, {stdout: false}, execaSync);92test('stdout can use "buffer: false" together with output file paths', () => testOutputFileNoBuffer(false, execa));93test('stdout can use "buffer: false" together with output file paths, fd-specific', () => testOutputFileNoBuffer({stdout: false}, execa));94test('stdout can use "buffer: false" together with output file paths, sync', () => testOutputFileNoBuffer(false, execaSync));95test('stdout can use "buffer: false" together with output file paths, fd-specific, sync', () => testOutputFileNoBuffer({stdout: false}, execaSync));
modified:test/stdio/handle-invalid.js+65 added-63 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {getStdio} from '../helpers/stdio.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';78setFixtureDirectory();98const testEmptyArray = (t, fdNumber, optionName, execaMethod) => {9 t.throws(() => {10const testEmptyArray = (fdNumber, optionName, execaMethod) => {11 assertThrows(() => {12 execaMethod('empty.js', getStdio(fdNumber, []));13 }, {message: `The \`${optionName}\` option must not be an empty array.`});14};1514test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);15test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);16test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);17test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);18test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);19test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);20test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);21test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);16test('Cannot pass an empty array to stdin', () => testEmptyArray(0, 'stdin', execa));17test('Cannot pass an empty array to stdout', () => testEmptyArray(1, 'stdout', execa));18test('Cannot pass an empty array to stderr', () => testEmptyArray(2, 'stderr', execa));19test('Cannot pass an empty array to stdio[*]', () => testEmptyArray(3, 'stdio[3]', execa));20test('Cannot pass an empty array to stdin - sync', () => testEmptyArray(0, 'stdin', execaSync));21test('Cannot pass an empty array to stdout - sync', () => testEmptyArray(1, 'stdout', execaSync));22test('Cannot pass an empty array to stderr - sync', () => testEmptyArray(2, 'stderr', execaSync));23test('Cannot pass an empty array to stdio[*] - sync', () => testEmptyArray(3, 'stdio[3]', execaSync));2423const testEmptyArrayBufferFalse = (t, fdNumber, optionName, execaMethod) => {24 t.throws(() => {25const testEmptyArrayBufferFalse = (fdNumber, optionName, execaMethod) => {26 assertThrows(() => {27 execaMethod('empty.js', {...getStdio(fdNumber, []), buffer: false});28 }, {message: `The \`${optionName}\` option must not be an empty array.`});29};3029test('Cannot pass an empty array to stdout with buffer: false', testEmptyArrayBufferFalse, 1, 'stdout', execa);30test('Cannot pass an empty array to stderr with buffer: false', testEmptyArrayBufferFalse, 2, 'stderr', execa);31test('Cannot pass an empty array to stdout with buffer: false - sync', testEmptyArrayBufferFalse, 1, 'stdout', execaSync);32test('Cannot pass an empty array to stderr with buffer: false - sync', testEmptyArrayBufferFalse, 2, 'stderr', execaSync);31test('Cannot pass an empty array to stdout with buffer: false', () => testEmptyArrayBufferFalse(1, 'stdout', execa));32test('Cannot pass an empty array to stderr with buffer: false', () => testEmptyArrayBufferFalse(2, 'stderr', execa));33test('Cannot pass an empty array to stdout with buffer: false - sync', () => testEmptyArrayBufferFalse(1, 'stdout', execaSync));34test('Cannot pass an empty array to stderr with buffer: false - sync', () => testEmptyArrayBufferFalse(2, 'stderr', execaSync));3534const testInvalidValueSync = (t, fdNumber, stdioOption) => {35 const {message} = t.throws(() => {36const testInvalidValueSync = (fdNumber, stdioOption) => {37 const {message} = assertThrows(() => {38 execaSync('empty.js', getStdio(fdNumber, stdioOption));39 });38 t.true(message.includes(`cannot be "${stdioOption}" with synchronous methods`));40 assert.ok(message.includes(`cannot be "${stdioOption}" with synchronous methods`));41};4241test('stdin cannot be "overlapped", sync', testInvalidValueSync, 0, 'overlapped');42test('stdout cannot be "overlapped", sync', testInvalidValueSync, 1, 'overlapped');43test('stderr cannot be "overlapped", sync', testInvalidValueSync, 2, 'overlapped');44test('stdio[*] cannot be "overlapped", sync', testInvalidValueSync, 3, 'overlapped');43test('stdin cannot be "overlapped", sync', () => testInvalidValueSync(0, 'overlapped'));44test('stdout cannot be "overlapped", sync', () => testInvalidValueSync(1, 'overlapped'));45test('stderr cannot be "overlapped", sync', () => testInvalidValueSync(2, 'overlapped'));46test('stdio[*] cannot be "overlapped", sync', () => testInvalidValueSync(3, 'overlapped'));4746const testInvalidArrayValue = (t, invalidStdio, fdNumber, execaMethod) => {47 t.throws(() => {48const testInvalidArrayValue = (invalidStdio, fdNumber, execaMethod) => {49 assertThrows(() => {50 execaMethod('empty.js', getStdio(fdNumber, ['pipe', invalidStdio]));51 }, {message: /must not include/});52};5352test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);53test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);54test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);55test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);56test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);57test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);58test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);59test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);54test('Cannot pass "ignore" and another value to stdin', () => testInvalidArrayValue('ignore', 0, execa));55test('Cannot pass "ignore" and another value to stdout', () => testInvalidArrayValue('ignore', 1, execa));56test('Cannot pass "ignore" and another value to stderr', () => testInvalidArrayValue('ignore', 2, execa));57test('Cannot pass "ignore" and another value to stdio[*]', () => testInvalidArrayValue('ignore', 3, execa));58test('Cannot pass "ignore" and another value to stdin - sync', () => testInvalidArrayValue('ignore', 0, execaSync));59test('Cannot pass "ignore" and another value to stdout - sync', () => testInvalidArrayValue('ignore', 1, execaSync));60test('Cannot pass "ignore" and another value to stderr - sync', () => testInvalidArrayValue('ignore', 2, execaSync));61test('Cannot pass "ignore" and another value to stdio[*] - sync', () => testInvalidArrayValue('ignore', 3, execaSync));6263// The `stdio: 'ipc'` value (raw `child_process` syntax) was replaced by the `ipc: true` option62const testIpcStdioOption = (t, fdNumber, stdioOption, execaMethod) => {63 t.throws(() => {64const testIpcStdioOption = (fdNumber, stdioOption, execaMethod) => {65 assertThrows(() => {66 execaMethod('empty.js', getStdio(fdNumber, stdioOption));67 }, {message: /The `ipc: true` option must be used instead/});68};6968test('stdin cannot be "ipc"', testIpcStdioOption, 0, 'ipc', execa);69test('stdout cannot be "ipc"', testIpcStdioOption, 1, 'ipc', execa);70test('stderr cannot be "ipc"', testIpcStdioOption, 2, 'ipc', execa);71test('stdio[*] cannot be "ipc"', testIpcStdioOption, 3, 'ipc', execa);72test('stdin cannot be "ipc" - sync', testIpcStdioOption, 0, 'ipc', execaSync);73test('stdout cannot be "ipc" - sync', testIpcStdioOption, 1, 'ipc', execaSync);74test('stderr cannot be "ipc" - sync', testIpcStdioOption, 2, 'ipc', execaSync);75test('stdio[*] cannot be "ipc" - sync', testIpcStdioOption, 3, 'ipc', execaSync);76test('stdio cannot be "ipc"', testIpcStdioOption, 'stdio', 'ipc', execa);77test('stdio cannot be "ipc" - sync', testIpcStdioOption, 'stdio', 'ipc', execaSync);78test('stdio[*] cannot be ["ipc"]', testIpcStdioOption, 3, ['ipc'], execa);79test('stdio[*] cannot be ["ipc"] - sync', testIpcStdioOption, 3, ['ipc'], execaSync);80test('stdio[*] cannot be {value: "ipc"}', testIpcStdioOption, 3, {value: 'ipc'}, execa);81test('stdio[*] cannot be {value: "ipc"} - sync', testIpcStdioOption, 3, {value: 'ipc'}, execaSync);82test('Cannot pass "ipc" and another value to stdio[*]', testIpcStdioOption, 3, ['pipe', 'ipc'], execa);83test('Cannot pass "ipc" and another value to stdio[*] - sync', testIpcStdioOption, 3, ['pipe', 'ipc'], execaSync);84test('Cannot pass {value: "ipc"} and another value to stdio[*]', testIpcStdioOption, 3, ['pipe', {value: 'ipc'}], execa);85test('Cannot pass {value: "ipc"} and another value to stdio[*] - sync', testIpcStdioOption, 3, ['pipe', {value: 'ipc'}], execaSync);70test('stdin cannot be "ipc"', () => testIpcStdioOption(0, 'ipc', execa));71test('stdout cannot be "ipc"', () => testIpcStdioOption(1, 'ipc', execa));72test('stderr cannot be "ipc"', () => testIpcStdioOption(2, 'ipc', execa));73test('stdio[*] cannot be "ipc"', () => testIpcStdioOption(3, 'ipc', execa));74test('stdin cannot be "ipc" - sync', () => testIpcStdioOption(0, 'ipc', execaSync));75test('stdout cannot be "ipc" - sync', () => testIpcStdioOption(1, 'ipc', execaSync));76test('stderr cannot be "ipc" - sync', () => testIpcStdioOption(2, 'ipc', execaSync));77test('stdio[*] cannot be "ipc" - sync', () => testIpcStdioOption(3, 'ipc', execaSync));78test('stdio cannot be "ipc"', () => testIpcStdioOption('stdio', 'ipc', execa));79test('stdio cannot be "ipc" - sync', () => testIpcStdioOption('stdio', 'ipc', execaSync));80test('stdio[*] cannot be ["ipc"]', () => testIpcStdioOption(3, ['ipc'], execa));81test('stdio[*] cannot be ["ipc"] - sync', () => testIpcStdioOption(3, ['ipc'], execaSync));82test('stdio[*] cannot be {value: "ipc"}', () => testIpcStdioOption(3, {value: 'ipc'}, execa));83test('stdio[*] cannot be {value: "ipc"} - sync', () => testIpcStdioOption(3, {value: 'ipc'}, execaSync));84test('Cannot pass "ipc" and another value to stdio[*]', () => testIpcStdioOption(3, ['pipe', 'ipc'], execa));85test('Cannot pass "ipc" and another value to stdio[*] - sync', () => testIpcStdioOption(3, ['pipe', 'ipc'], execaSync));86test('Cannot pass {value: "ipc"} and another value to stdio[*]', () => testIpcStdioOption(3, ['pipe', {value: 'ipc'}], execa));87test('Cannot pass {value: "ipc"} and another value to stdio[*] - sync', () => testIpcStdioOption(3, ['pipe', {value: 'ipc'}], execaSync));8889// A file descriptor must be a non-negative integer. Without this, `node:child_process` aborts the current process with a fatal assertion when spawning.88const testInvalidFileDescriptor = (t, fdNumber, optionName, stdioOption, execaMethod) => {89 t.throws(() => {90const testInvalidFileDescriptor = (fdNumber, optionName, stdioOption, execaMethod) => {91 assertThrows(() => {92 execaMethod('empty.js', getStdio(fdNumber, stdioOption));93 }, {message: `The \`${optionName}\` option must be a non-negative 32-bit integer: got ${stdioOption}.`});94};9594test('Cannot pass a fractional file descriptor to stdin', testInvalidFileDescriptor, 0, 'stdin', 1.5, execa);95test('Cannot pass NaN as a file descriptor to stdin', testInvalidFileDescriptor, 0, 'stdin', Number.NaN, execa);96test('Cannot pass Infinity as a file descriptor to stdout', testInvalidFileDescriptor, 1, 'stdout', Number.POSITIVE_INFINITY, execa);97test('Cannot pass a too large file descriptor to stderr', testInvalidFileDescriptor, 2, 'stderr', 2 ** 32, execa);98test('Cannot pass a negative file descriptor to stdio[*]', testInvalidFileDescriptor, 3, 'stdio[3]', -1, execa);99test('Cannot pass a fractional file descriptor to stdout', testInvalidFileDescriptor, 1, 'stdout', 1.5, execaSync);100test('Cannot pass a negative file descriptor to stdin', testInvalidFileDescriptor, 0, 'stdin', -1, execaSync);96test('Cannot pass a fractional file descriptor to stdin', () => testInvalidFileDescriptor(0, 'stdin', 1.5, execa));97test('Cannot pass NaN as a file descriptor to stdin', () => testInvalidFileDescriptor(0, 'stdin', NaN, execa));98test('Cannot pass Infinity as a file descriptor to stdout', () => testInvalidFileDescriptor(1, 'stdout', Infinity, execa));99test('Cannot pass a too large file descriptor to stderr', () => testInvalidFileDescriptor(2, 'stderr', 2 ** 32, execa));100test('Cannot pass a negative file descriptor to stdio[*]', () => testInvalidFileDescriptor(3, 'stdio[3]', -1, execa));101test('Cannot pass a fractional file descriptor to stdout', () => testInvalidFileDescriptor(1, 'stdout', 1.5, execaSync));102test('Cannot pass a negative file descriptor to stdin', () => testInvalidFileDescriptor(0, 'stdin', -1, execaSync));
modified:test/stdio/handle-normal.js+28 added-27 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa} from '../../index.js';4import {getStdio} from '../helpers/stdio.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {foobarString, foobarUint8Array} from '../helpers/input.js';78setFixtureDirectory();99const testInputOverlapped = async (t, fdNumber) => {10const testInputOverlapped = async fdNumber => {11 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, [foobarUint8Array, 'overlapped', 'pipe']));11 t.is(stdout, foobarString);12 assert.equal(stdout, foobarString);13};1414test('stdin can be ["overlapped", "pipe"]', testInputOverlapped, 0);15test('stdio[*] input can be ["overlapped", "pipe"]', testInputOverlapped, 3);15test('stdin can be ["overlapped", "pipe"]', () => testInputOverlapped(0));16test('stdio[*] input can be ["overlapped", "pipe"]', () => testInputOverlapped(3));1717const testOutputOverlapped = async (t, fdNumber) => {18const testOutputOverlapped = async fdNumber => {19 const {stdio} = await execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, ['overlapped', 'pipe']));19 t.is(stdio[fdNumber], foobarString);20 assert.equal(stdio[fdNumber], foobarString);21};2222test('stdout can be ["overlapped", "pipe"]', testOutputOverlapped, 1);23test('stderr can be ["overlapped", "pipe"]', testOutputOverlapped, 2);24test('stdio[*] output can be ["overlapped", "pipe"]', testOutputOverlapped, 3);23test('stdout can be ["overlapped", "pipe"]', () => testOutputOverlapped(1));24test('stderr can be ["overlapped", "pipe"]', () => testOutputOverlapped(2));25test('stdio[*] output can be ["overlapped", "pipe"]', () => testOutputOverlapped(3));2626const testFd3Undefined = async (t, stdioOption, options) => {27const testFd3Undefined = async (stdioOption, options) => {28 const subprocess = execa('empty.js', {...getStdio(3, stdioOption), ...options});28 t.is(subprocess.stdio.length, 4);29 t.is(subprocess.stdio[3], null);29 assert.equal(subprocess.stdio.length, 4);30 assert.equal(subprocess.stdio[3], null);3132 const {stdio} = await subprocess;32 t.is(stdio.length, 4);33 t.is(stdio[3], undefined);33 assert.equal(stdio.length, 4);34 assert.equal(stdio[3], undefined);35};3636test('stdio[*] undefined means "ignore"', testFd3Undefined, undefined, {});37test('stdio[*] null means "ignore"', testFd3Undefined, null, {});38test('stdio[*] [undefined] means "ignore"', testFd3Undefined, [undefined], {});39test('stdio[*] [null] means "ignore"', testFd3Undefined, [null], {});40test('stdio[*] undefined means "ignore", "lines: true"', testFd3Undefined, undefined, {lines: true});41test('stdio[*] null means "ignore", "lines: true"', testFd3Undefined, null, {lines: true});42test('stdio[*] [undefined] means "ignore", "lines: true"', testFd3Undefined, [undefined], {lines: true});43test('stdio[*] [null] means "ignore", "lines: true"', testFd3Undefined, [null], {lines: true});44test('stdio[*] undefined means "ignore", "encoding: hex"', testFd3Undefined, undefined, {encoding: 'hex'});45test('stdio[*] null means "ignore", "encoding: hex"', testFd3Undefined, null, {encoding: 'hex'});46test('stdio[*] [undefined] means "ignore", "encoding: hex"', testFd3Undefined, [undefined], {encoding: 'hex'});47test('stdio[*] [null] means "ignore", "encoding: hex"', testFd3Undefined, [null], {encoding: 'hex'});37test('stdio[*] undefined means "ignore"', () => testFd3Undefined(undefined, {}));38test('stdio[*] null means "ignore"', () => testFd3Undefined(null, {}));39test('stdio[*] [undefined] means "ignore"', () => testFd3Undefined([undefined], {}));40test('stdio[*] [null] means "ignore"', () => testFd3Undefined([null], {}));41test('stdio[*] undefined means "ignore", "lines: true"', () => testFd3Undefined(undefined, {lines: true}));42test('stdio[*] null means "ignore", "lines: true"', () => testFd3Undefined(null, {lines: true}));43test('stdio[*] [undefined] means "ignore", "lines: true"', () => testFd3Undefined([undefined], {lines: true}));44test('stdio[*] [null] means "ignore", "lines: true"', () => testFd3Undefined([null], {lines: true}));45test('stdio[*] undefined means "ignore", "encoding: hex"', () => testFd3Undefined(undefined, {encoding: 'hex'}));46test('stdio[*] null means "ignore", "encoding: hex"', () => testFd3Undefined(null, {encoding: 'hex'}));47test('stdio[*] [undefined] means "ignore", "encoding: hex"', () => testFd3Undefined([undefined], {encoding: 'hex'}));48test('stdio[*] [null] means "ignore", "encoding: hex"', () => testFd3Undefined([null], {encoding: 'hex'}));
modified:test/stdio/handle-options.js+42 added-32 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa} from '../../index.js';3import {getStdio} from '../helpers/stdio.js';4import {getStdio, fullStdio} from '../helpers/stdio.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {nestedSubprocess} from '../helpers/nested.js';78setFixtureDirectory();98const testNoPipeOption = async (t, stdioOption, fdNumber) => {10const testNoPipeOption = async (stdioOption, fdNumber) => {11 const subprocess = execa('empty.js', getStdio(fdNumber, stdioOption));10 t.is(subprocess.stdio[fdNumber], null);12 assert.equal(subprocess.stdio[fdNumber], null);13 await subprocess;14};1514test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);15test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);16test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);17test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);18test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);19test('stdin can be 0', testNoPipeOption, 0, 0);20test('stdin can be [0]', testNoPipeOption, [0], 0);21test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);22test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);23test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);24test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);25test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);26test('stdout can be 1', testNoPipeOption, 1, 1);27test('stdout can be [1]', testNoPipeOption, [1], 1);28test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);29test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);30test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);31test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);32test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);33test('stderr can be 2', testNoPipeOption, 2, 2);34test('stderr can be [2]', testNoPipeOption, [2], 2);35test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);36test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);37test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);38test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);39test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);40test('stdio[*] can be 3', testNoPipeOption, 3, 3);41test('stdio[*] can be [3]', testNoPipeOption, [3], 3);16test('stdin can be "ignore"', () => testNoPipeOption('ignore', 0));17test('stdin can be ["ignore"]', () => testNoPipeOption(['ignore'], 0));18test('stdin can be ["ignore", "ignore"]', () => testNoPipeOption(['ignore', 'ignore'], 0));19test('stdin can be "inherit"', () => testNoPipeOption('inherit', 0));20test('stdin can be ["inherit"]', () => testNoPipeOption(['inherit'], 0));21test('stdin can be 0', () => testNoPipeOption(0, 0));22test('stdin can be [0]', () => testNoPipeOption([0], 0));23test('stdout can be "ignore"', () => testNoPipeOption('ignore', 1));24test('stdout can be ["ignore"]', () => testNoPipeOption(['ignore'], 1));25test('stdout can be ["ignore", "ignore"]', () => testNoPipeOption(['ignore', 'ignore'], 1));26test('stdout can be "inherit"', () => testNoPipeOption('inherit', 1));27test('stdout can be ["inherit"]', () => testNoPipeOption(['inherit'], 1));28test('stdout can be 1', () => testNoPipeOption(1, 1));29test('stdout can be [1]', () => testNoPipeOption([1], 1));30test('stderr can be "ignore"', () => testNoPipeOption('ignore', 2));31test('stderr can be ["ignore"]', () => testNoPipeOption(['ignore'], 2));32test('stderr can be ["ignore", "ignore"]', () => testNoPipeOption(['ignore', 'ignore'], 2));33test('stderr can be "inherit"', () => testNoPipeOption('inherit', 2));34test('stderr can be ["inherit"]', () => testNoPipeOption(['inherit'], 2));35test('stderr can be 2', () => testNoPipeOption(2, 2));36test('stderr can be [2]', () => testNoPipeOption([2], 2));37test('stdio[*] can be "ignore"', () => testNoPipeOption('ignore', 3));38test('stdio[*] can be ["ignore"]', () => testNoPipeOption(['ignore'], 3));39test('stdio[*] can be ["ignore", "ignore"]', () => testNoPipeOption(['ignore', 'ignore'], 3));4041// Inheriting fd 3 requires the current process to have one that can be inherited. The test runner does not provide one, so this runs inside a parent process which does.42const testNoPipeOptionFd3 = async stdioOption => {43 const {nestedResult} = await nestedSubprocess('empty.js', getStdio(3, stdioOption), fullStdio);44 assert.equal(nestedResult.failed, false);45 assert.equal(nestedResult.stdio[3], undefined);46};4748test('stdio[*] can be "inherit"', () => testNoPipeOptionFd3('inherit'));49test('stdio[*] can be ["inherit"]', () => testNoPipeOptionFd3(['inherit']));50test('stdio[*] can be 3', () => testNoPipeOptionFd3(3));51test('stdio[*] can be [3]', () => testNoPipeOptionFd3([3]));
modified:test/stdio/iterable.js+96 added-94 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import test from 'node:test';5import {assertThrows, assertRejects} from '../helpers/assert.js';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {getStdio} from '../helpers/stdio.js';9import {
34 unmodified lines
44};4546setFixtureDirectory();4746const testIterable = async (t, stdioOption, fdNumber, execaMethod) => {48const testIterable = async (stdioOption, fdNumber, execaMethod) => {49 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, stdioOption));48 t.is(stdout, 'foobar');50 assert.equal(stdout, 'foobar');51};5251const testIpcDataIterable = async (t, fdNumber, execaMethod) => {53const testIpcDataIterable = async (fdNumber, execaMethod) => {54 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [['ipc']]));53 t.is(stdout, 'ipc');55 assert.equal(stdout, 'ipc');56};5756test.serial('stdin option can be an array of strings', testIterable, [foobarArray], 0, execa);57test.serial('stdin option can be an array of strings - sync', testIterable, [foobarArray], 0, execaSync);58test.serial('stdio[*] option can be an array of strings', testIterable, [foobarArray], 3, execa);59test.serial('stdin option can be an array with "ipc" as input data', testIpcDataIterable, 0, execa);60test.serial('stdin option can be an array with "ipc" as input data - sync', testIpcDataIterable, 0, execaSync);61test.serial('stdio[*] option can be an array with "ipc" as input data', testIpcDataIterable, 3, execa);62test.serial('stdin option can be an array of Uint8Arrays', testIterable, [binaryArray], 0, execa);63test.serial('stdin option can be an array of Uint8Arrays - sync', testIterable, [binaryArray], 0, execaSync);64test.serial('stdio[*] option can be an array of Uint8Arrays', testIterable, [binaryArray], 3, execa);65test.serial('stdin option can be an iterable of strings', testIterable, stringGenerator(), 0, execa);66test.serial('stdin option can be an iterable of strings - sync', testIterable, stringGenerator(), 0, execaSync);67test.serial('stdio[*] option can be an iterable of strings', testIterable, stringGenerator(), 3, execa);68test.serial('stdin option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 0, execa);69test.serial('stdin option can be an iterable of Uint8Arrays - sync', testIterable, binaryGenerator(), 0, execaSync);70test.serial('stdio[*] option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 3, execa);71test.serial('stdin option can be an iterable of strings + Uint8Arrays', testIterable, mixedGenerator(), 0, execa);72test.serial('stdin option can be an iterable of strings + Uint8Arrays - sync', testIterable, mixedGenerator(), 0, execaSync);73test.serial('stdio[*] option can be an iterable of strings + Uint8Arrays', testIterable, mixedGenerator(), 3, execa);74test.serial('stdin option can be an async iterable', testIterable, asyncGenerator(), 0, execa);75test.serial('stdio[*] option can be an async iterable', testIterable, asyncGenerator(), 3, execa);58test('stdin option can be an array of strings', () => testIterable([foobarArray], 0, execa));59test('stdin option can be an array of strings - sync', () => testIterable([foobarArray], 0, execaSync));60test('stdio[*] option can be an array of strings', () => testIterable([foobarArray], 3, execa));61test('stdin option can be an array with "ipc" as input data', () => testIpcDataIterable(0, execa));62test('stdin option can be an array with "ipc" as input data - sync', () => testIpcDataIterable(0, execaSync));63test('stdio[*] option can be an array with "ipc" as input data', () => testIpcDataIterable(3, execa));64test('stdin option can be an array of Uint8Arrays', () => testIterable([binaryArray], 0, execa));65test('stdin option can be an array of Uint8Arrays - sync', () => testIterable([binaryArray], 0, execaSync));66test('stdio[*] option can be an array of Uint8Arrays', () => testIterable([binaryArray], 3, execa));67test('stdin option can be an iterable of strings', () => testIterable(stringGenerator(), 0, execa));68test('stdin option can be an iterable of strings - sync', () => testIterable(stringGenerator(), 0, execaSync));69test('stdio[*] option can be an iterable of strings', () => testIterable(stringGenerator(), 3, execa));70test('stdin option can be an iterable of Uint8Arrays', () => testIterable(binaryGenerator(), 0, execa));71test('stdin option can be an iterable of Uint8Arrays - sync', () => testIterable(binaryGenerator(), 0, execaSync));72test('stdio[*] option can be an iterable of Uint8Arrays', () => testIterable(binaryGenerator(), 3, execa));73test('stdin option can be an iterable of strings + Uint8Arrays', () => testIterable(mixedGenerator(), 0, execa));74test('stdin option can be an iterable of strings + Uint8Arrays - sync', () => testIterable(mixedGenerator(), 0, execaSync));75test('stdio[*] option can be an iterable of strings + Uint8Arrays', () => testIterable(mixedGenerator(), 3, execa));76test('stdin option can be an async iterable', () => testIterable(asyncGenerator(), 0, execa));77test('stdio[*] option can be an async iterable', () => testIterable(asyncGenerator(), 3, execa));7879const foobarObjectGenerator = function * () {80 yield foobarObject;81};
1 unmodified line
83const foobarAsyncObjectGenerator = async function * () {84 yield foobarObject;85};8685const testObjectIterable = async (t, stdioOption, fdNumber, execaMethod) => {87const testObjectIterable = async (stdioOption, fdNumber, execaMethod) => {88 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stdioOption, serializeGenerator(true)]));87 t.is(stdout, foobarObjectString);89 assert.equal(stdout, foobarObjectString);90};9190test('stdin option can be an array of objects', testObjectIterable, [foobarObject], 0, execa);91test('stdio[*] option can be an array of objects', testObjectIterable, [foobarObject], 3, execa);92test('stdin option can be an iterable of objects', testObjectIterable, foobarObjectGenerator(), 0, execa);93test('stdio[*] option can be an iterable of objects', testObjectIterable, foobarObjectGenerator(), 3, execa);94test('stdin option can be an async iterable of objects', testObjectIterable, foobarAsyncObjectGenerator(), 0, execa);95test('stdio[*] option can be an async iterable of objects', testObjectIterable, foobarAsyncObjectGenerator(), 3, execa);96test('stdin option can be an array of objects - sync', testObjectIterable, [foobarObject], 0, execaSync);97test('stdin option can be an iterable of objects - sync', testObjectIterable, foobarObjectGenerator(), 0, execaSync);92test('stdin option can be an array of objects', () => testObjectIterable([foobarObject], 0, execa));93test('stdio[*] option can be an array of objects', () => testObjectIterable([foobarObject], 3, execa));94test('stdin option can be an iterable of objects', () => testObjectIterable(foobarObjectGenerator(), 0, execa));95test('stdio[*] option can be an iterable of objects', () => testObjectIterable(foobarObjectGenerator(), 3, execa));96test('stdin option can be an async iterable of objects', () => testObjectIterable(foobarAsyncObjectGenerator(), 0, execa));97test('stdio[*] option can be an async iterable of objects', () => testObjectIterable(foobarAsyncObjectGenerator(), 3, execa));98test('stdin option can be an array of objects - sync', () => testObjectIterable([foobarObject], 0, execaSync));99test('stdin option can be an iterable of objects - sync', () => testObjectIterable(foobarObjectGenerator(), 0, execaSync));10099const testIterableNoGeneratorsSync = (t, stdioOption, fdNumber) => {100 t.throws(() => {101const testIterableNoGeneratorsSync = (stdioOption, fdNumber) => {102 assertThrows(() => {103 execaSync('empty.js', getStdio(fdNumber, stdioOption));104 }, {message: /must be used to serialize/});105};106105test('stdin option cannot be an array of objects without generators - sync', testIterableNoGeneratorsSync, [[foobarObject]], 0);106test('stdin option cannot be an iterable of objects without generators - sync', testIterableNoGeneratorsSync, foobarObjectGenerator(), 0);107test('stdin option cannot be an array of objects without generators - sync', () => testIterableNoGeneratorsSync([[foobarObject]], 0));108test('stdin option cannot be an iterable of objects without generators - sync', () => testIterableNoGeneratorsSync(foobarObjectGenerator(), 0));109108const testIterableNoSerializeSync = (t, stdioOption, fdNumber) => {109 t.throws(() => {110const testIterableNoSerializeSync = (stdioOption, fdNumber) => {111 assertThrows(() => {112 execaSync('empty.js', getStdio(fdNumber, [stdioOption, noopGenerator()]));113 }, {message: /The `stdin` option's transform must use "objectMode: true" to receive as input: object/});114};115114test('stdin option cannot be an array of objects without serializing - sync', testIterableNoSerializeSync, [foobarObject], 0);115test('stdin option cannot be an iterable of objects without serializing - sync', testIterableNoSerializeSync, foobarObjectGenerator(), 0);116test('stdin option cannot be an array of objects without serializing - sync', () => testIterableNoSerializeSync([foobarObject], 0));117test('stdin option cannot be an iterable of objects without serializing - sync', () => testIterableNoSerializeSync(foobarObjectGenerator(), 0));118117const testIterableSync = (t, stdioOption, fdNumber) => {118 t.throws(() => {119const testIterableSync = (stdioOption, fdNumber) => {120 assertThrows(() => {121 execaSync('empty.js', getStdio(fdNumber, stdioOption));122 }, {message: /an iterable with synchronous methods/});123};124123test('stdio[*] option cannot be an array of strings - sync', testIterableSync, [foobarArray], 3);124test('stdio[*] option cannot be an array of Uint8Arrays - sync', testIterableSync, [binaryArray], 3);125test('stdio[*] option cannot be an array of objects - sync', testIterableSync, [[foobarObject]], 3);126test('stdio[*] option cannot be an iterable of strings - sync', testIterableSync, stringGenerator(), 3);127test('stdio[*] option cannot be an iterable of Uint8Arrays - sync', testIterableSync, binaryGenerator(), 3);128test('stdio[*] option cannot be an iterable of objects - sync', testIterableSync, foobarObjectGenerator(), 3);129test('stdio[*] option cannot be multiple iterables - sync', testIterableSync, [stringGenerator(), stringGenerator()], 3);125test('stdio[*] option cannot be an array of strings - sync', () => testIterableSync([foobarArray], 3));126test('stdio[*] option cannot be an array of Uint8Arrays - sync', () => testIterableSync([binaryArray], 3));127test('stdio[*] option cannot be an array of objects - sync', () => testIterableSync([[foobarObject]], 3));128test('stdio[*] option cannot be an iterable of strings - sync', () => testIterableSync(stringGenerator(), 3));129test('stdio[*] option cannot be an iterable of Uint8Arrays - sync', () => testIterableSync(binaryGenerator(), 3));130test('stdio[*] option cannot be an iterable of objects - sync', () => testIterableSync(foobarObjectGenerator(), 3));131test('stdio[*] option cannot be multiple iterables - sync', () => testIterableSync([stringGenerator(), stringGenerator()], 3));132131const testAsyncIterableSync = (t, stdioOption, fdNumber) => {132 t.throws(() => {133const testAsyncIterableSync = (stdioOption, fdNumber) => {134 assertThrows(() => {135 execaSync('empty.js', getStdio(fdNumber, stdioOption));136 }, {message: /an async iterable with synchronous method/});137};138137test('stdin option cannot be an async iterable - sync', testAsyncIterableSync, asyncGenerator(), 0);138test('stdio[*] option cannot be an async iterable - sync', testAsyncIterableSync, asyncGenerator(), 3);139test('stdin option cannot be an async iterable of objects - sync', testAsyncIterableSync, foobarAsyncObjectGenerator(), 0);140test('stdio[*] option cannot be an async iterable of objects - sync', testAsyncIterableSync, foobarAsyncObjectGenerator(), 3);139test('stdin option cannot be an async iterable - sync', () => testAsyncIterableSync(asyncGenerator(), 0));140test('stdio[*] option cannot be an async iterable - sync', () => testAsyncIterableSync(asyncGenerator(), 3));141test('stdin option cannot be an async iterable of objects - sync', () => testAsyncIterableSync(foobarAsyncObjectGenerator(), 0));142test('stdio[*] option cannot be an async iterable of objects - sync', () => testAsyncIterableSync(foobarAsyncObjectGenerator(), 3));143142const testIterableError = async (t, fdNumber) => {144const testIterableError = async fdNumber => {145 const cause = new Error(foobarString);144 const error = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator(cause)().transform())));145 t.is(error.cause, cause);146 const error = await assertRejects(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator(cause)().transform())));147 assert.equal(error.cause, cause);148};149148test('stdin option handles errors in iterables', testIterableError, 0);149test('stdio[*] option handles errors in iterables', testIterableError, 3);150test('stdin option handles errors in iterables', () => testIterableError(0));151test('stdio[*] option handles errors in iterables', () => testIterableError(3));152151const testIterableErrorSync = (t, fdNumber) => {153const testIterableErrorSync = fdNumber => {154 const cause = new Error(foobarString);153 const error = t.throws(() => {155 const error = assertThrows(() => {156 execaSync('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, throwingGenerator(cause)().transform()));157 });156 t.is(error, cause);158 assert.equal(error, cause);159};160159test('stdin option handles errors in iterables - sync', testIterableErrorSync, 0);160test('stdio[*] option handles errors in iterables - sync', testIterableErrorSync, 3);161test('stdin option handles errors in iterables - sync', () => testIterableErrorSync(0));162test('stdio[*] option handles errors in iterables - sync', () => testIterableErrorSync(3));163162const testNoIterableOutput = (t, stdioOption, fdNumber, execaMethod) => {163 t.throws(() => {164const testNoIterableOutput = (stdioOption, fdNumber, execaMethod) => {165 assertThrows(() => {166 execaMethod('empty.js', getStdio(fdNumber, stdioOption));167 }, {message: /cannot be an iterable/});168};169168test('stdout option cannot be an array of strings', testNoIterableOutput, [foobarArray], 1, execa);169test('stderr option cannot be an array of strings', testNoIterableOutput, [foobarArray], 2, execa);170test('stdout option cannot be an array of strings - sync', testNoIterableOutput, [foobarArray], 1, execaSync);171test('stderr option cannot be an array of strings - sync', testNoIterableOutput, [foobarArray], 2, execaSync);172test('stdout option cannot be an iterable', testNoIterableOutput, stringGenerator(), 1, execa);173test('stderr option cannot be an iterable', testNoIterableOutput, stringGenerator(), 2, execa);174test('stdout option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 1, execaSync);175test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);170test('stdout option cannot be an array of strings', () => testNoIterableOutput([foobarArray], 1, execa));171test('stderr option cannot be an array of strings', () => testNoIterableOutput([foobarArray], 2, execa));172test('stdout option cannot be an array of strings - sync', () => testNoIterableOutput([foobarArray], 1, execaSync));173test('stderr option cannot be an array of strings - sync', () => testNoIterableOutput([foobarArray], 2, execaSync));174test('stdout option cannot be an iterable', () => testNoIterableOutput(stringGenerator(), 1, execa));175test('stderr option cannot be an iterable', () => testNoIterableOutput(stringGenerator(), 2, execa));176test('stdout option cannot be an iterable - sync', () => testNoIterableOutput(stringGenerator(), 1, execaSync));177test('stderr option cannot be an iterable - sync', () => testNoIterableOutput(stringGenerator(), 2, execaSync));178177test('stdin option can be an infinite iterable', async t => {179test('stdin option can be an infinite iterable', async () => {180 const iterable = infiniteGenerator().transform();181 const subprocess = execa('stdin.js', getStdio(0, iterable));182 await once(subprocess.stdout, 'data');183 subprocess.kill();182 const {stdout} = await t.throwsAsync(subprocess);183 t.true(stdout.startsWith('foo'));184 t.deepEqual(await iterable.next(), {value: undefined, done: true});184 const {stdout} = await assertRejects(subprocess);185 assert.ok(stdout.startsWith('foo'));186 assert.deepEqual(await iterable.next(), {value: undefined, done: true});187});188187const testMultipleIterable = async (t, stdioOption, fdNumber, execaMethod) => {189const testMultipleIterable = async (stdioOption, fdNumber, execaMethod) => {190 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, stdioOption));191 const expectedOutputs = [192 `${foobarArray[0]}${foobarArray[1]}${foobarArray[0]}${foobarArray[1]}`,193 `${foobarArray[0]}${foobarArray[0]}${foobarArray[1]}${foobarArray[1]}`,194 ];193 t.true(expectedOutputs.includes(stdout));195 assert.ok(expectedOutputs.includes(stdout));196};197196test('stdin option can be multiple iterables', testMultipleIterable, [stringGenerator(), stringGenerator()], 0, execa);197test('stdio[*] option can be multiple iterables', testMultipleIterable, [stringGenerator(), stringGenerator()], 3, execa);198test('stdin option can be multiple iterables - sync', testMultipleIterable, [stringGenerator(), stringGenerator()], 0, execaSync);199test('stdin option can be multiple mixed iterables', testMultipleIterable, [stringGenerator(), binaryGenerator()], 0, execa);200test('stdio[*] option can be multiple mixed iterables', testMultipleIterable, [stringGenerator(), binaryGenerator()], 3, execa);201test('stdin option can be multiple mixed iterables - sync', testMultipleIterable, [stringGenerator(), binaryGenerator()], 0, execaSync);202test('stdin option can be sync/async mixed iterables', testMultipleIterable, [stringGenerator(), asyncGenerator()], 0, execa);203test('stdio[*] option can be sync/async mixed iterables', testMultipleIterable, [stringGenerator(), asyncGenerator()], 3, execa);198test('stdin option can be multiple iterables', () => testMultipleIterable([stringGenerator(), stringGenerator()], 0, execa));199test('stdio[*] option can be multiple iterables', () => testMultipleIterable([stringGenerator(), stringGenerator()], 3, execa));200test('stdin option can be multiple iterables - sync', () => testMultipleIterable([stringGenerator(), stringGenerator()], 0, execaSync));201test('stdin option can be multiple mixed iterables', () => testMultipleIterable([stringGenerator(), binaryGenerator()], 0, execa));202test('stdio[*] option can be multiple mixed iterables', () => testMultipleIterable([stringGenerator(), binaryGenerator()], 3, execa));203test('stdin option can be multiple mixed iterables - sync', () => testMultipleIterable([stringGenerator(), binaryGenerator()], 0, execaSync));204test('stdin option can be sync/async mixed iterables', () => testMultipleIterable([stringGenerator(), asyncGenerator()], 0, execa));205test('stdio[*] option can be sync/async mixed iterables', () => testMultipleIterable([stringGenerator(), asyncGenerator()], 3, execa));206205test('stdin option iterable is canceled on subprocess error', async t => {207test('stdin option iterable is canceled on subprocess error', async () => {208 const iterable = infiniteGenerator().transform();207 await t.throwsAsync(execa('stdin.js', {stdin: iterable, timeout: 1}), {message: /timed out/});209 await assertRejects(execa('stdin.js', {stdin: iterable, timeout: 1}), {message: /timed out/});210 // eslint-disable-next-line no-empty211 for await (const _ of iterable) {}212});
modified:test/stdio/lines-main.js+59 added-57 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertRejects} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {fullStdio} from '../helpers/stdio.js';7import {getOutputsGenerator} from '../helpers/generator.js';
10 unmodified lines
1819setFixtureDirectory();2021// eslint-disable-next-line max-params20const testStreamLines = async (t, fdNumber, input, expectedOutput, lines, stripFinalNewline, execaMethod) => {22const testStreamLines = async (fdNumber, input, expectedOutput, lines, stripFinalNewline, execaMethod) => {23 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, input], {...fullStdio, lines, stripFinalNewline});22 t.deepEqual(stdio[fdNumber], expectedOutput);24 assert.deepEqual(stdio[fdNumber], expectedOutput);25};2625test('"lines: true" splits lines, stdout', testStreamLines, 1, simpleFull, simpleLines, true, false, execa);26test('"lines: true" splits lines, stdout, fd-specific', testStreamLines, 1, simpleFull, simpleLines, {stdout: true}, false, execa);27test('"lines: true" splits lines, stderr', testStreamLines, 2, simpleFull, simpleLines, true, false, execa);28test('"lines: true" splits lines, stderr, fd-specific', testStreamLines, 2, simpleFull, simpleLines, {stderr: true}, false, execa);29test('"lines: true" splits lines, stdio[*]', testStreamLines, 3, simpleFull, simpleLines, true, false, execa);30test('"lines: true" splits lines, stdio[*], fd-specific', testStreamLines, 3, simpleFull, simpleLines, {fd3: true}, false, execa);31test('"lines: true" splits lines, stdout, stripFinalNewline', testStreamLines, 1, simpleFull, noNewlinesChunks, true, true, execa);32test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific', testStreamLines, 1, simpleFull, noNewlinesChunks, true, {stdout: true}, execa);33test('"lines: true" splits lines, stderr, stripFinalNewline', testStreamLines, 2, simpleFull, noNewlinesChunks, true, true, execa);34test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific', testStreamLines, 2, simpleFull, noNewlinesChunks, true, {stderr: true}, execa);35test('"lines: true" splits lines, stdio[*], stripFinalNewline', testStreamLines, 3, simpleFull, noNewlinesChunks, true, true, execa);36test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific', testStreamLines, 3, simpleFull, noNewlinesChunks, true, {fd3: true}, execa);37test('"lines: true" splits lines, stdout, sync', testStreamLines, 1, simpleFull, simpleLines, true, false, execaSync);38test('"lines: true" splits lines, stdout, fd-specific, sync', testStreamLines, 1, simpleFull, simpleLines, {stdout: true}, false, execaSync);39test('"lines: true" splits lines, stderr, sync', testStreamLines, 2, simpleFull, simpleLines, true, false, execaSync);40test('"lines: true" splits lines, stderr, fd-specific, sync', testStreamLines, 2, simpleFull, simpleLines, {stderr: true}, false, execaSync);41test('"lines: true" splits lines, stdio[*], sync', testStreamLines, 3, simpleFull, simpleLines, true, false, execaSync);42test('"lines: true" splits lines, stdio[*], fd-specific, sync', testStreamLines, 3, simpleFull, simpleLines, {fd3: true}, false, execaSync);43test('"lines: true" splits lines, stdout, stripFinalNewline, sync', testStreamLines, 1, simpleFull, noNewlinesChunks, true, true, execaSync);44test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific, sync', testStreamLines, 1, simpleFull, noNewlinesChunks, true, {stdout: true}, execaSync);45test('"lines: true" splits lines, stderr, stripFinalNewline, sync', testStreamLines, 2, simpleFull, noNewlinesChunks, true, true, execaSync);46test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific, sync', testStreamLines, 2, simpleFull, noNewlinesChunks, true, {stderr: true}, execaSync);47test('"lines: true" splits lines, stdio[*], stripFinalNewline, sync', testStreamLines, 3, simpleFull, noNewlinesChunks, true, true, execaSync);48test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific, sync', testStreamLines, 3, simpleFull, noNewlinesChunks, true, {fd3: true}, execaSync);27test('"lines: true" splits lines, stdout', () => testStreamLines(1, simpleFull, simpleLines, true, false, execa));28test('"lines: true" splits lines, stdout, fd-specific', () => testStreamLines(1, simpleFull, simpleLines, {stdout: true}, false, execa));29test('"lines: true" splits lines, stderr', () => testStreamLines(2, simpleFull, simpleLines, true, false, execa));30test('"lines: true" splits lines, stderr, fd-specific', () => testStreamLines(2, simpleFull, simpleLines, {stderr: true}, false, execa));31test('"lines: true" splits lines, stdio[*]', () => testStreamLines(3, simpleFull, simpleLines, true, false, execa));32test('"lines: true" splits lines, stdio[*], fd-specific', () => testStreamLines(3, simpleFull, simpleLines, {fd3: true}, false, execa));33test('"lines: true" splits lines, stdout, stripFinalNewline', () => testStreamLines(1, simpleFull, noNewlinesChunks, true, true, execa));34test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific', () => testStreamLines(1, simpleFull, noNewlinesChunks, true, {stdout: true}, execa));35test('"lines: true" splits lines, stderr, stripFinalNewline', () => testStreamLines(2, simpleFull, noNewlinesChunks, true, true, execa));36test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific', () => testStreamLines(2, simpleFull, noNewlinesChunks, true, {stderr: true}, execa));37test('"lines: true" splits lines, stdio[*], stripFinalNewline', () => testStreamLines(3, simpleFull, noNewlinesChunks, true, true, execa));38test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific', () => testStreamLines(3, simpleFull, noNewlinesChunks, true, {fd3: true}, execa));39test('"lines: true" splits lines, stdout, sync', () => testStreamLines(1, simpleFull, simpleLines, true, false, execaSync));40test('"lines: true" splits lines, stdout, fd-specific, sync', () => testStreamLines(1, simpleFull, simpleLines, {stdout: true}, false, execaSync));41test('"lines: true" splits lines, stderr, sync', () => testStreamLines(2, simpleFull, simpleLines, true, false, execaSync));42test('"lines: true" splits lines, stderr, fd-specific, sync', () => testStreamLines(2, simpleFull, simpleLines, {stderr: true}, false, execaSync));43test('"lines: true" splits lines, stdio[*], sync', () => testStreamLines(3, simpleFull, simpleLines, true, false, execaSync));44test('"lines: true" splits lines, stdio[*], fd-specific, sync', () => testStreamLines(3, simpleFull, simpleLines, {fd3: true}, false, execaSync));45test('"lines: true" splits lines, stdout, stripFinalNewline, sync', () => testStreamLines(1, simpleFull, noNewlinesChunks, true, true, execaSync));46test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific, sync', () => testStreamLines(1, simpleFull, noNewlinesChunks, true, {stdout: true}, execaSync));47test('"lines: true" splits lines, stderr, stripFinalNewline, sync', () => testStreamLines(2, simpleFull, noNewlinesChunks, true, true, execaSync));48test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific, sync', () => testStreamLines(2, simpleFull, noNewlinesChunks, true, {stderr: true}, execaSync));49test('"lines: true" splits lines, stdio[*], stripFinalNewline, sync', () => testStreamLines(3, simpleFull, noNewlinesChunks, true, true, execaSync));50test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific, sync', () => testStreamLines(3, simpleFull, noNewlinesChunks, true, {fd3: true}, execaSync));5152const bigArray = Array.from({length: 1e5}).fill('.\n');53const bigString = bigArray.join('');54const bigStringNoNewlines = '.'.repeat(1e6);55const bigStringNoNewlinesEnd = `${bigStringNoNewlines}\n`;5657// eslint-disable-next-line max-params56const testStreamLinesGenerator = async (t, input, expectedLines, objectMode, binary, stripFinalNewline, execaMethod) => {58const testStreamLinesGenerator = async (input, expectedLines, objectMode, binary, stripFinalNewline, execaMethod) => {59 const {stdout} = await execaMethod('noop.js', {60 stdout: getOutputsGenerator(input)(objectMode, binary),61 lines: true,62 stripFinalNewline,63 });62 t.deepEqual(stdout, expectedLines);64 assert.deepEqual(stdout, expectedLines);65};6665test('"lines: true" works with strings generators', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false, false, execa);66test('"lines: true" works with strings generators, binary', testStreamLinesGenerator, simpleChunks, simpleLines, false, true, false, execa);67test('"lines: true" works with big strings generators', testStreamLinesGenerator, [bigString], bigArray, false, false, false, execa);68test('"lines: true" works with big strings generators without newlines', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execa);69test('"lines: true" is a noop with strings generators, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, false, execa);70test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, true, execa);71test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execa);72test('"lines: true" is a noop with strings generators, binary, objectMode', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true, false, execa);73test('"lines: true" is a noop big strings generators, objectMode', testStreamLinesGenerator, [bigString], [bigString], true, false, false, execa);74test('"lines: true" is a noop big strings generators without newlines, objectMode', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execa);75test('"lines: true" works with strings generators, sync', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false, false, execaSync);76test('"lines: true" works with strings generators, binary, sync', testStreamLinesGenerator, simpleChunks, simpleLines, false, true, false, execaSync);77test('"lines: true" works with big strings generators, sync', testStreamLinesGenerator, [bigString], bigArray, false, false, false, execaSync);78test('"lines: true" works with big strings generators without newlines, sync', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execaSync);79test('"lines: true" is a noop with strings generators, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, false, execaSync);80test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, true, execaSync);81test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execaSync);82test('"lines: true" is a noop with strings generators, binary, objectMode, sync', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true, false, execaSync);83test('"lines: true" is a noop big strings generators, objectMode, sync', testStreamLinesGenerator, [bigString], [bigString], true, false, false, execaSync);84test('"lines: true" is a noop big strings generators without newlines, objectMode, sync', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execaSync);67test('"lines: true" works with strings generators', () => testStreamLinesGenerator(simpleChunks, simpleFullEndLines, false, false, false, execa));68test('"lines: true" works with strings generators, binary', () => testStreamLinesGenerator(simpleChunks, simpleLines, false, true, false, execa));69test('"lines: true" works with big strings generators', () => testStreamLinesGenerator([bigString], bigArray, false, false, false, execa));70test('"lines: true" works with big strings generators without newlines', () => testStreamLinesGenerator([bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execa));71test('"lines: true" is a noop with strings generators, objectMode', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, false, execa));72test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, true, execa));73test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execa));74test('"lines: true" is a noop with strings generators, binary, objectMode', () => testStreamLinesGenerator(simpleChunks, simpleChunks, true, true, false, execa));75test('"lines: true" is a noop big strings generators, objectMode', () => testStreamLinesGenerator([bigString], [bigString], true, false, false, execa));76test('"lines: true" is a noop big strings generators without newlines, objectMode', () => testStreamLinesGenerator([bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execa));77test('"lines: true" works with strings generators, sync', () => testStreamLinesGenerator(simpleChunks, simpleFullEndLines, false, false, false, execaSync));78test('"lines: true" works with strings generators, binary, sync', () => testStreamLinesGenerator(simpleChunks, simpleLines, false, true, false, execaSync));79test('"lines: true" works with big strings generators, sync', () => testStreamLinesGenerator([bigString], bigArray, false, false, false, execaSync));80test('"lines: true" works with big strings generators without newlines, sync', () => testStreamLinesGenerator([bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execaSync));81test('"lines: true" is a noop with strings generators, objectMode, sync', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, false, execaSync));82test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode, sync', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, true, execaSync));83test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode, sync', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execaSync));84test('"lines: true" is a noop with strings generators, binary, objectMode, sync', () => testStreamLinesGenerator(simpleChunks, simpleChunks, true, true, false, execaSync));85test('"lines: true" is a noop big strings generators, objectMode, sync', () => testStreamLinesGenerator([bigString], [bigString], true, false, false, execaSync));86test('"lines: true" is a noop big strings generators without newlines, objectMode, sync', () => testStreamLinesGenerator([bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execaSync));8786test('"lines: true" stops on stream error', async t => {88test('"lines: true" stops on stream error', async () => {89 const cause = new Error(foobarString);88 const error = await t.throwsAsync(getSimpleChunkSubprocessAsync({90 const error = await assertRejects(getSimpleChunkSubprocessAsync({91 * stdout(line) {92 if (line === noNewlinesChunks[2]) {93 throw cause;94 }9596 yield line;97 },98 }));97 t.is(error.cause, cause);98 t.deepEqual(error.stdout, noNewlinesChunks.slice(0, 2));99 assert.equal(error.cause, cause);100 assert.deepEqual(error.stdout, noNewlinesChunks.slice(0, 2));101});102101test('"lines: true" stops on stream error event', async t => {103test('"lines: true" stops on stream error event', async () => {104 const cause = new Error(foobarString);105 const subprocess = getSimpleChunkSubprocessAsync();106 subprocess.stdout.emit('error', cause);105 const error = await t.throwsAsync(subprocess);106 t.is(error.cause, cause);107 t.deepEqual(error.stdout, []);107 const error = await assertRejects(subprocess);108 assert.equal(error.cause, cause);109 assert.deepEqual(error.stdout, []);110});
modified:test/stdio/lines-max-buffer.js+29 added-27 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows, assertRejects} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {simpleLines, noNewlinesChunks, getSimpleChunkSubprocessAsync} from '../helpers/lines.js';7import {assertErrorMessage} from '../helpers/max-buffer.js';
1 unmodified line
9setFixtureDirectory();1011const maxBuffer = simpleLines.length - 1;1211const testBelowMaxBuffer = async (t, lines) => {13const testBelowMaxBuffer = async lines => {14 const {isMaxBuffer, stdout} = await getSimpleChunkSubprocessAsync({lines, maxBuffer: maxBuffer + 1});13 t.false(isMaxBuffer);14 t.deepEqual(stdout, noNewlinesChunks);15 assert.equal(isMaxBuffer, false);16 assert.deepEqual(stdout, noNewlinesChunks);17};1817test('"lines: true" can be below "maxBuffer"', testBelowMaxBuffer, true);18test('"lines: true" can be below "maxBuffer", fd-specific', testBelowMaxBuffer, {stdout: true});19test('"lines: true" can be below "maxBuffer"', () => testBelowMaxBuffer(true));20test('"lines: true" can be below "maxBuffer", fd-specific', () => testBelowMaxBuffer({stdout: true}));2120const testAboveMaxBuffer = async (t, lines) => {21 const {isMaxBuffer, shortMessage, stdout} = await t.throwsAsync(getSimpleChunkSubprocessAsync({lines, maxBuffer}));22 t.true(isMaxBuffer);23 assertErrorMessage(t, shortMessage, {length: maxBuffer, unit: 'lines'});24 t.deepEqual(stdout, noNewlinesChunks.slice(0, maxBuffer));22const testAboveMaxBuffer = async lines => {23 const {isMaxBuffer, shortMessage, stdout} = await assertRejects(getSimpleChunkSubprocessAsync({lines, maxBuffer}));24 assert.equal(isMaxBuffer, true);25 assertErrorMessage(shortMessage, {length: maxBuffer, unit: 'lines'});26 assert.deepEqual(stdout, noNewlinesChunks.slice(0, maxBuffer));27};2827test('"lines: true" can be above "maxBuffer"', testAboveMaxBuffer, true);28test('"lines: true" can be above "maxBuffer", fd-specific', testAboveMaxBuffer, {stdout: true});29test('"lines: true" can be above "maxBuffer"', () => testAboveMaxBuffer(true));30test('"lines: true" can be above "maxBuffer", fd-specific', () => testAboveMaxBuffer({stdout: true}));3130const testMaxBufferUnit = async (t, lines) => {31 const {isMaxBuffer, shortMessage, stdout} = await t.throwsAsync(execa('noop-repeat.js', ['1', '...\n'], {lines, maxBuffer}));32 t.true(isMaxBuffer);33 assertErrorMessage(t, shortMessage, {length: maxBuffer, unit: 'lines'});34 t.deepEqual(stdout, ['...', '...']);32const testMaxBufferUnit = async lines => {33 const {isMaxBuffer, shortMessage, stdout} = await assertRejects(execa('noop-repeat.js', ['1', '...\n'], {lines, maxBuffer}));34 assert.equal(isMaxBuffer, true);35 assertErrorMessage(shortMessage, {length: maxBuffer, unit: 'lines'});36 assert.deepEqual(stdout, ['...', '...']);37};3837test('"maxBuffer" is measured in lines with "lines: true"', testMaxBufferUnit, true);38test('"maxBuffer" is measured in lines with "lines: true", fd-specific', testMaxBufferUnit, {stdout: true});39test('"maxBuffer" is measured in lines with "lines: true"', () => testMaxBufferUnit(true));40test('"maxBuffer" is measured in lines with "lines: true", fd-specific', () => testMaxBufferUnit({stdout: true}));4140const testMaxBufferUnitSync = (t, lines) => {41 const {isMaxBuffer, shortMessage, stdout} = t.throws(() => {42const testMaxBufferUnitSync = lines => {43 const {isMaxBuffer, shortMessage, stdout} = assertThrows(() => {44 execaSync('noop-repeat.js', ['1', '...\n'], {lines, maxBuffer});45 }, {code: 'ENOBUFS'});44 t.true(isMaxBuffer);45 assertErrorMessage(t, shortMessage, {execaMethod: execaSync, length: maxBuffer});46 t.deepEqual(stdout, ['..']);46 assert.equal(isMaxBuffer, true);47 assertErrorMessage(shortMessage, {execaMethod: execaSync, length: maxBuffer});48 assert.deepEqual(stdout, ['..']);49};5049test('"maxBuffer" is measured in bytes with "lines: true", sync', testMaxBufferUnitSync, true);50test('"maxBuffer" is measured in bytes with "lines: true", fd-specific, sync', testMaxBufferUnitSync, {stdout: true});51test('"maxBuffer" is measured in bytes with "lines: true", sync', () => testMaxBufferUnitSync(true));52test('"maxBuffer" is measured in bytes with "lines: true", fd-specific, sync', () => testMaxBufferUnitSync({stdout: true}));
modified:test/stdio/lines-mixed.js+23 added-22 removed
1import assert from 'node:assert/strict';2import {Writable} from 'node:stream';2import test from 'ava';3import test from 'node:test';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {assertStreamOutput, assertStreamDataEvents, assertIterableChunks} from '../helpers/convert.js';6import {7 simpleFull,
3 unmodified lines
11} from '../helpers/lines.js';1213setFixtureDirectory();1414const testAsyncIteration = async (t, expectedLines, stripFinalNewline) => {15const testAsyncIteration = async (expectedLines, stripFinalNewline) => {16 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});16 t.false(subprocess.stdout.readableObjectMode);17 await assertStreamOutput(t, subprocess.stdout, simpleFull);17 assert.equal(subprocess.stdout.readableObjectMode, false);18 await assertStreamOutput(subprocess.stdout, simpleFull);19 const {stdout} = await subprocess;19 t.deepEqual(stdout, expectedLines);20 assert.deepEqual(stdout, expectedLines);21};2222test('"lines: true" works with stream async iteration', testAsyncIteration, simpleLines, false);23test('"lines: true" works with stream async iteration, stripFinalNewline', testAsyncIteration, noNewlinesChunks, true);23test('"lines: true" works with stream async iteration', () => testAsyncIteration(simpleLines, false));24test('"lines: true" works with stream async iteration, stripFinalNewline', () => testAsyncIteration(noNewlinesChunks, true));2525const testDataEvents = async (t, expectedLines, stripFinalNewline) => {26const testDataEvents = async (expectedLines, stripFinalNewline) => {27 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});27 await assertStreamDataEvents(t, subprocess.stdout, simpleFull);28 await assertStreamDataEvents(subprocess.stdout, simpleFull);29 const {stdout} = await subprocess;29 t.deepEqual(stdout, expectedLines);30 assert.deepEqual(stdout, expectedLines);31};3232test('"lines: true" works with stream "data" events', testDataEvents, simpleLines, false);33test('"lines: true" works with stream "data" events, stripFinalNewline', testDataEvents, noNewlinesChunks, true);33test('"lines: true" works with stream "data" events', () => testDataEvents(simpleLines, false));34test('"lines: true" works with stream "data" events, stripFinalNewline', () => testDataEvents(noNewlinesChunks, true));3535const testWritableStream = async (t, expectedLines, stripFinalNewline) => {36const testWritableStream = async (expectedLines, stripFinalNewline) => {37 let output = '';38 const writable = new Writable({39 write(line, encoding, done) {40 output += line.toString();
1 unmodified line
42 },43 decodeStrings: false,44 });45 const {stdout} = await getSimpleChunkSubprocessAsync({stripFinalNewline, stdout: ['pipe', writable]});45 t.deepEqual(output, simpleFull);46 t.deepEqual(stdout, expectedLines);46 assert.deepEqual(output, simpleFull);47 assert.deepEqual(stdout, expectedLines);48};4949test('"lines: true" works with writable streams targets', testWritableStream, simpleLines, false);50test('"lines: true" works with writable streams targets, stripFinalNewline', testWritableStream, noNewlinesChunks, true);50test('"lines: true" works with writable streams targets', () => testWritableStream(simpleLines, false));51test('"lines: true" works with writable streams targets, stripFinalNewline', () => testWritableStream(noNewlinesChunks, true));5252const testIterable = async (t, expectedLines, stripFinalNewline) => {53const testIterable = async (expectedLines, stripFinalNewline) => {54 const subprocess = getSimpleChunkSubprocessAsync({stripFinalNewline});54 await assertIterableChunks(t, subprocess, noNewlinesChunks);55 await assertIterableChunks(subprocess, noNewlinesChunks);56 const {stdout} = await subprocess;56 t.deepEqual(stdout, expectedLines);57 assert.deepEqual(stdout, expectedLines);58};5959test('"lines: true" works with subprocess.iterable()', testIterable, simpleLines, false);60test('"lines: true" works with subprocess.iterable(), stripFinalNewline', testIterable, noNewlinesChunks, true);60test('"lines: true" works with subprocess.iterable()', () => testIterable(simpleLines, false));61test('"lines: true" works with subprocess.iterable(), stripFinalNewline', () => testIterable(noNewlinesChunks, true));
modified:test/stdio/lines-noop.js+50 added-49 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa, execaSync} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {getOutputsGenerator} from '../helpers/generator.js';6import {foobarObject} from '../helpers/input.js';
8 unmodified lines
15} from '../helpers/lines.js';1617setFixtureDirectory();1818const testStreamLinesNoop = async (t, lines, execaMethod) => {19const testStreamLinesNoop = async (lines, execaMethod) => {20 const {stdout} = await execaMethod('noop-fd.js', ['1', simpleFull], {lines});20 t.is(stdout, simpleFull);21 assert.equal(stdout, simpleFull);22};2323test('"lines: false" is a noop', testStreamLinesNoop, false, execa);24test('"lines: false" is a noop, fd-specific', testStreamLinesNoop, {stderr: true}, execa);25test('"lines: false" is a noop, fd-specific none', testStreamLinesNoop, {}, execa);26test('"lines: false" is a noop, sync', testStreamLinesNoop, false, execaSync);27test('"lines: false" is a noop, fd-specific, sync', testStreamLinesNoop, {stderr: true}, execaSync);28test('"lines: false" is a noop, fd-specific none, sync', testStreamLinesNoop, {}, execaSync);24test('"lines: false" is a noop', () => testStreamLinesNoop(false, execa));25test('"lines: false" is a noop, fd-specific', () => testStreamLinesNoop({stderr: true}, execa));26test('"lines: false" is a noop, fd-specific none', () => testStreamLinesNoop({}, execa));27test('"lines: false" is a noop, sync', () => testStreamLinesNoop(false, execaSync));28test('"lines: false" is a noop, fd-specific, sync', () => testStreamLinesNoop({stderr: true}, execaSync));29test('"lines: false" is a noop, fd-specific none, sync', () => testStreamLinesNoop({}, execaSync));3030const testLinesObjectMode = async (t, lines, execaMethod) => {31const testLinesObjectMode = async (lines, execaMethod) => {32 const {stdout} = await execaMethod('noop.js', {33 stdout: getOutputsGenerator([foobarObject])(true),34 lines,35 });35 t.deepEqual(stdout, [foobarObject]);36 assert.deepEqual(stdout, [foobarObject]);37};3838test('"lines: true" is a noop with objects generators, objectMode', testLinesObjectMode, true, execa);39test('"lines: true" is a noop with objects generators, fd-specific, objectMode', testLinesObjectMode, {stdout: true}, execa);40test('"lines: true" is a noop with objects generators, objectMode, sync', testLinesObjectMode, true, execaSync);41test('"lines: true" is a noop with objects generators, fd-specific, objectMode, sync', testLinesObjectMode, {stdout: true}, execaSync);39test('"lines: true" is a noop with objects generators, objectMode', () => testLinesObjectMode(true, execa));40test('"lines: true" is a noop with objects generators, fd-specific, objectMode', () => testLinesObjectMode({stdout: true}, execa));41test('"lines: true" is a noop with objects generators, objectMode, sync', () => testLinesObjectMode(true, execaSync));42test('"lines: true" is a noop with objects generators, fd-specific, objectMode, sync', () => testLinesObjectMode({stdout: true}, execaSync));4344// eslint-disable-next-line max-params44const testEncoding = async (t, input, expectedOutput, encoding, lines, stripFinalNewline, execaMethod) => {45const testEncoding = async (input, expectedOutput, encoding, lines, stripFinalNewline, execaMethod) => {46 const {stdout} = await execaMethod('stdin.js', {47 lines,48 stripFinalNewline,49 encoding,50 input,51 });51 t.deepEqual(stdout, expectedOutput);52 assert.deepEqual(stdout, expectedOutput);53};5454test('"lines: true" is a noop with "encoding: utf16"', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execa);55test('"lines: true" is a noop with "encoding: utf16", fd-specific', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execa);56test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execa);57test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execa);58test('"lines: true" is a noop with "encoding: buffer"', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execa);59test('"lines: true" is a noop with "encoding: buffer", fd-specific', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execa);60test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execa);61test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execa);62test('"lines: true" is a noop with "encoding: hex"', testEncoding, simpleFull, simpleFullHex, 'hex', true, false, execa);63test('"lines: true" is a noop with "encoding: hex", fd-specific', testEncoding, simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execa);64test('"lines: true" is a noop with "encoding: hex", stripFinalNewline', testEncoding, simpleFull, simpleFullHex, 'hex', true, true, execa);65test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific', testEncoding, simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execa);66test('"lines: true" is a noop with "encoding: utf16", sync', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execaSync);67test('"lines: true" is a noop with "encoding: utf16", fd-specific, sync', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execaSync);68test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, sync', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execaSync);69test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific, sync', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execaSync);70test('"lines: true" is a noop with "encoding: buffer", sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync);71test('"lines: true" is a noop with "encoding: buffer", fd-specific, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execaSync);72test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync);73test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execaSync);74test('"lines: true" is a noop with "encoding: hex", sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, false, execaSync);75test('"lines: true" is a noop with "encoding: hex", fd-specific, sync', testEncoding, simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execaSync);76test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, true, execaSync);77test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific, sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execaSync);55test('"lines: true" is a noop with "encoding: utf16"', () => testEncoding(simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execa));56test('"lines: true" is a noop with "encoding: utf16", fd-specific', () => testEncoding(simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execa));57test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline', () => testEncoding(simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execa));58test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific', () => testEncoding(simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execa));59test('"lines: true" is a noop with "encoding: buffer"', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, false, execa));60test('"lines: true" is a noop with "encoding: buffer", fd-specific', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execa));61test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, false, execa));62test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execa));63test('"lines: true" is a noop with "encoding: hex"', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, false, execa));64test('"lines: true" is a noop with "encoding: hex", fd-specific', () => testEncoding(simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execa));65test('"lines: true" is a noop with "encoding: hex", stripFinalNewline', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, true, execa));66test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execa));67test('"lines: true" is a noop with "encoding: utf16", sync', () => testEncoding(simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execaSync));68test('"lines: true" is a noop with "encoding: utf16", fd-specific, sync', () => testEncoding(simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execaSync));69test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, sync', () => testEncoding(simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execaSync));70test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific, sync', () => testEncoding(simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execaSync));71test('"lines: true" is a noop with "encoding: buffer", sync', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync));72test('"lines: true" is a noop with "encoding: buffer", fd-specific, sync', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execaSync));73test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, sync', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync));74test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific, sync', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execaSync));75test('"lines: true" is a noop with "encoding: hex", sync', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, false, execaSync));76test('"lines: true" is a noop with "encoding: hex", fd-specific, sync', () => testEncoding(simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execaSync));77test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, sync', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, true, execaSync));78test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific, sync', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execaSync));7979const testLinesNoBuffer = async (t, lines, buffer, execaMethod) => {80const testLinesNoBuffer = async (lines, buffer, execaMethod) => {81 const {stdout} = await getSimpleChunkSubprocess(execaMethod, {lines, buffer});81 t.is(stdout, undefined);82 assert.equal(stdout, undefined);83};8484test('"lines: true" is a noop with "buffer: false"', testLinesNoBuffer, true, false, execa);85test('"lines: true" is a noop with "buffer: false", fd-specific buffer', testLinesNoBuffer, true, {stdout: false}, execa);86test('"lines: true" is a noop with "buffer: false", fd-specific lines', testLinesNoBuffer, {stdout: true}, false, execa);87test('"lines: true" is a noop with "buffer: false", sync', testLinesNoBuffer, true, false, execaSync);88test('"lines: true" is a noop with "buffer: false", fd-specific buffer, sync', testLinesNoBuffer, true, {stdout: false}, execaSync);89test('"lines: true" is a noop with "buffer: false", fd-specific lines, sync', testLinesNoBuffer, {stdout: true}, false, execaSync);85test('"lines: true" is a noop with "buffer: false"', () => testLinesNoBuffer(true, false, execa));86test('"lines: true" is a noop with "buffer: false", fd-specific buffer', () => testLinesNoBuffer(true, {stdout: false}, execa));87test('"lines: true" is a noop with "buffer: false", fd-specific lines', () => testLinesNoBuffer({stdout: true}, false, execa));88test('"lines: true" is a noop with "buffer: false", sync', () => testLinesNoBuffer(true, false, execaSync));89test('"lines: true" is a noop with "buffer: false", fd-specific buffer, sync', () => testLinesNoBuffer(true, {stdout: false}, execaSync));90test('"lines: true" is a noop with "buffer: false", fd-specific lines, sync', () => testLinesNoBuffer({stdout: true}, false, execaSync));
modified:test/stdio/native-fd.js+50 added-53 removed
1import assert from 'node:assert/strict';2import {platform} from 'node:process';2import test from 'ava';3import test from 'node:test';4import {assertThrows} from '../helpers/assert.js';5import {execa, execaSync} from '../../index.js';6import {getStdio, fullStdio} from '../helpers/stdio.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {foobarString} from '../helpers/input.js';
1 unmodified line
1011setFixtureDirectory();1213const isLinux = platform === 'linux';12const isWindows = platform === 'win32';1414const testFd3InheritOutput = async (t, stdioOption, isSync) => {15const testFd3InheritOutput = async (stdioOption, isSync) => {16 const {stdio} = await nestedSubprocess('noop-fd.js', ['3', foobarString], {...getStdio(3, stdioOption), isSync}, fullStdio);16 t.is(stdio[3], foobarString);17 assert.equal(stdio[3], foobarString);18};1919test('stdio[*] output can use "inherit"', testFd3InheritOutput, 'inherit', false);20test('stdio[*] output can use ["inherit"]', testFd3InheritOutput, ['inherit'], false);21test('stdio[*] output can use "inherit", sync', testFd3InheritOutput, 'inherit', true);22test('stdio[*] output can use ["inherit"], sync', testFd3InheritOutput, ['inherit'], true);20test('stdio[*] output can use "inherit"', () => testFd3InheritOutput('inherit', false));21test('stdio[*] output can use ["inherit"]', () => testFd3InheritOutput(['inherit'], false));22test('stdio[*] output can use "inherit", sync', () => testFd3InheritOutput('inherit', true));23test('stdio[*] output can use ["inherit"], sync', () => testFd3InheritOutput(['inherit'], true));2425if (isLinux) {25 const testOverflowStream = async (t, fdNumber, stdioOption, isSync) => {26 const testOverflowStream = async (fdNumber, stdioOption, isSync) => {27 const {stdout} = await nestedSubprocess('empty.js', {...getStdio(fdNumber, stdioOption), isSync}, fullStdio);27 t.is(stdout, '');28 assert.equal(stdout, '');29 };3030 test('stdin can use 4+', testOverflowStream, 0, 4, false);31 test('stdin can use [4+]', testOverflowStream, 0, [4], false);32 test('stdout can use 4+', testOverflowStream, 1, 4, false);33 test('stdout can use [4+]', testOverflowStream, 1, [4], false);34 test('stderr can use 4+', testOverflowStream, 2, 4, false);35 test('stderr can use [4+]', testOverflowStream, 2, [4], false);36 test('stdio[*] can use 4+', testOverflowStream, 3, 4, false);37 test('stdio[*] can use [4+]', testOverflowStream, 3, [4], false);38 test('stdin can use 4+, sync', testOverflowStream, 0, 4, true);39 test('stdin can use [4+], sync', testOverflowStream, 0, [4], true);40 test('stdout can use 4+, sync', testOverflowStream, 1, 4, true);41 test('stdout can use [4+], sync', testOverflowStream, 1, [4], true);42 test('stderr can use 4+, sync', testOverflowStream, 2, 4, true);43 test('stderr can use [4+], sync', testOverflowStream, 2, [4], true);44 test('stdio[*] can use 4+, sync', testOverflowStream, 3, 4, true);45 test('stdio[*] can use [4+], sync', testOverflowStream, 3, [4], true);31 test('stdin can use 4+', () => testOverflowStream(0, 4, false));32 test('stdin can use [4+]', () => testOverflowStream(0, [4], false));33 test('stdout can use 4+', () => testOverflowStream(1, 4, false));34 test('stdout can use [4+]', () => testOverflowStream(1, [4], false));35 test('stderr can use 4+', () => testOverflowStream(2, 4, false));36 test('stderr can use [4+]', () => testOverflowStream(2, [4], false));37 test('stdio[*] can use 4+', () => testOverflowStream(3, 4, false));38 test('stdio[*] can use [4+]', () => testOverflowStream(3, [4], false));39 test('stdin can use 4+, sync', () => testOverflowStream(0, 4, true));40 test('stdin can use [4+], sync', () => testOverflowStream(0, [4], true));41 test('stdout can use 4+, sync', () => testOverflowStream(1, 4, true));42 test('stdout can use [4+], sync', () => testOverflowStream(1, [4], true));43 test('stderr can use 4+, sync', () => testOverflowStream(2, 4, true));44 test('stderr can use [4+], sync', () => testOverflowStream(2, [4], true));45 test('stdio[*] can use 4+, sync', () => testOverflowStream(3, 4, true));46 test('stdio[*] can use [4+], sync', () => testOverflowStream(3, [4], true));47}4848const testOverflowStreamArray = (t, fdNumber, stdioOption) => {49 t.throws(() => {49const testOverflowStreamArray = (fdNumber, stdioOption) => {50 assertThrows(() => {51 execa('empty.js', getStdio(fdNumber, stdioOption));52 }, {message: /no such standard stream/});53};5454test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);55test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);56test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);57test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);58test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);55test('stdin cannot use 4+ and another value', () => testOverflowStreamArray(0, [4, 'pipe']));56test('stdout cannot use 4+ and another value', () => testOverflowStreamArray(1, [4, 'pipe']));57test('stderr cannot use 4+ and another value', () => testOverflowStreamArray(2, [4, 'pipe']));58test('stdio[*] cannot use 4+ and another value', () => testOverflowStreamArray(3, [4, 'pipe']));59test('stdio[*] cannot use "inherit" and another value', () => testOverflowStreamArray(3, ['inherit', 'pipe']));6060const getInvalidFdCode = () => {61 if (isLinux) {62 return 'EINVAL';63 }61// A file descriptor number which is not open in the current process.62// Lower ones might be used internally by Node.js, and the error then depends on what they are.63const closedFdNumber = 1000;6465 return isWindows ? 'EBADF' : 'ENXIO';65const testOverflowStreamArraySync = fdNumber => {66 assertThrows(() => {67 execaSync('noop-fd.js', [fdNumber, foobarString], getStdio(fdNumber, [closedFdNumber, 'pipe']));68 }, {code: 'EBADF'});69};7068const testOverflowStreamArraySync = (t, fdNumber) => {69 t.throws(() => {70 execaSync('noop-fd.js', [fdNumber, foobarString], getStdio(fdNumber, [4, 'pipe']));71 }, {code: getInvalidFdCode()});72};71test('stdout cannot use 4+ and another value, sync', () => testOverflowStreamArraySync(1));72test('stderr cannot use 4+ and another value, sync', () => testOverflowStreamArraySync(2));73test('stdio[*] cannot use 4+ and another value, sync', () => testOverflowStreamArraySync(3));7474test('stdout cannot use 4+ and another value, sync', testOverflowStreamArraySync, 1);75test('stderr cannot use 4+ and another value, sync', testOverflowStreamArraySync, 2);76test('stdio[*] cannot use 4+ and another value, sync', testOverflowStreamArraySync, 3);7775// `1` and 'inherit' are two spellings of the same target, which only becomes apparent once native values are normalized.76// The output must be written to the inherited file descriptor only once, which the nested parent captures.77// The nested parent's `stdout` has its final newline stripped by the outer `execa()` call.81const testSameTargetOutput = async (t, stdioOption, isSync) => {78const testSameTargetOutput = async (stdioOption, isSync) => {79 const {stdout} = await nestedSubprocess('noop.js', [foobarString], {stdout: stdioOption, isSync});83 t.is(stdout, foobarString);80 assert.equal(stdout, foobarString);81};8286test('stdout output is not duplicated with [1, "inherit"]', testSameTargetOutput, [1, 'inherit'], false);87test('stdout output is not duplicated with ["inherit", 1]', testSameTargetOutput, ['inherit', 1], false);88test('stdout output is not duplicated with [1, "inherit"], sync', testSameTargetOutput, [1, 'inherit'], true);89test('stdout output is not duplicated with ["inherit", 1], sync', testSameTargetOutput, ['inherit', 1], true);83test('stdout output is not duplicated with [1, "inherit"]', () => testSameTargetOutput([1, 'inherit'], false));84test('stdout output is not duplicated with ["inherit", 1]', () => testSameTargetOutput(['inherit', 1], false));85test('stdout output is not duplicated with [1, "inherit"], sync', () => testSameTargetOutput([1, 'inherit'], true));86test('stdout output is not duplicated with ["inherit", 1], sync', () => testSameTargetOutput(['inherit', 1], true));
modified:test/stdio/native-inherit-pipe.js+62 added-60 removed
1import assert from 'node:assert/strict';2import {readFile, rm} from 'node:fs/promises';2import test from 'ava';3import test from 'node:test';4import tempfile from 'tempfile';5import {assertRejects} from '../helpers/assert.js';6import {execa} from '../../index.js';7import {getStdio, fullStdio} from '../helpers/stdio.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9import {foobarString} from '../helpers/input.js';10import {nestedSubprocess} from '../helpers/nested.js';1112setFixtureDirectory();1312const testInheritStdin = async (t, stdioOption, isSync) => {14const testInheritStdin = async (stdioOption, isSync) => {15 const {stdout} = await execa('nested-multiple-stdin.js', [JSON.stringify(stdioOption), `${isSync}`], {input: foobarString});14 t.is(stdout, `${foobarString}${foobarString}`);16 assert.equal(stdout, `${foobarString}${foobarString}`);17};1817test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe'], false);18test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe'], false);19test('stdin can be [process.stdin, "pipe"]', testInheritStdin, ['stdin', 'pipe'], false);20test.serial('stdin can be ["inherit", "pipe"], sync', testInheritStdin, ['inherit', 'pipe'], true);21test.serial('stdin can be [0, "pipe"], sync', testInheritStdin, [0, 'pipe'], true);22test.serial('stdin can be [process.stdin, "pipe"], sync', testInheritStdin, ['stdin', 'pipe'], true);19test('stdin can be ["inherit", "pipe"]', () => testInheritStdin(['inherit', 'pipe'], false));20test('stdin can be [0, "pipe"]', () => testInheritStdin([0, 'pipe'], false));21test('stdin can be [process.stdin, "pipe"]', () => testInheritStdin(['stdin', 'pipe'], false));22test('stdin can be ["inherit", "pipe"], sync', () => testInheritStdin(['inherit', 'pipe'], true));23test('stdin can be [0, "pipe"], sync', () => testInheritStdin([0, 'pipe'], true));24test('stdin can be [process.stdin, "pipe"], sync', () => testInheritStdin(['stdin', 'pipe'], true));2526// eslint-disable-next-line max-params25const testInheritStdioOutput = async (t, fdNumber, outerFdNumber, stdioOption, isSync, encoding) => {27const testInheritStdioOutput = async (fdNumber, outerFdNumber, stdioOption, isSync, encoding) => {28 const {stdio} = await execa('nested-multiple-stdio-output.js', [JSON.stringify(stdioOption), `${fdNumber}`, `${outerFdNumber}`, `${isSync}`, encoding], fullStdio);27 t.is(stdio[fdNumber], foobarString);28 t.is(stdio[outerFdNumber], `nested ${foobarString}`);29 assert.equal(stdio[fdNumber], foobarString);30 assert.equal(stdio[outerFdNumber], `nested ${foobarString}`);31};3231test('stdout can be ["inherit", "pipe"]', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], false, 'utf8');32test('stdout can be [1, "pipe"]', testInheritStdioOutput, 1, 2, [1, 'pipe'], false, 'utf8');33test('stdout can be [process.stdout, "pipe"]', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], false, 'utf8');34test('stderr can be ["inherit", "pipe"]', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], false, 'utf8');35test('stderr can be [2, "pipe"]', testInheritStdioOutput, 2, 1, [2, 'pipe'], false, 'utf8');36test('stderr can be [process.stderr, "pipe"]', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], false, 'utf8');37test('stdout can be ["inherit", "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], false, 'buffer');38test('stdout can be [1, "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, [1, 'pipe'], false, 'buffer');39test('stdout can be [process.stdout, "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], false, 'buffer');40test('stderr can be ["inherit", "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], false, 'buffer');41test('stderr can be [2, "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, [2, 'pipe'], false, 'buffer');42test('stderr can be [process.stderr, "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], false, 'buffer');43test('stdout can be ["inherit", "pipe"], sync', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], true, 'utf8');44test('stdout can be [1, "pipe"], sync', testInheritStdioOutput, 1, 2, [1, 'pipe'], true, 'utf8');45test('stdout can be [process.stdout, "pipe"], sync', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], true, 'utf8');46test('stderr can be ["inherit", "pipe"], sync', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], true, 'utf8');47test('stderr can be [2, "pipe"], sync', testInheritStdioOutput, 2, 1, [2, 'pipe'], true, 'utf8');48test('stderr can be [process.stderr, "pipe"], sync', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], true, 'utf8');49test('stdio[*] output can be ["inherit", "pipe"], sync', testInheritStdioOutput, 3, 1, ['inherit', 'pipe'], true, 'utf8');50test('stdio[*] output can be [3, "pipe"], sync', testInheritStdioOutput, 3, 1, [3, 'pipe'], true, 'utf8');51test('stdout can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], true, 'buffer');52test('stdout can be [1, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, [1, 'pipe'], true, 'buffer');53test('stdout can be [process.stdout, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], true, 'buffer');54test('stderr can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], true, 'buffer');55test('stderr can be [2, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, [2, 'pipe'], true, 'buffer');56test('stderr can be [process.stderr, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], true, 'buffer');57test('stdio[*] output can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 3, 1, ['inherit', 'pipe'], true, 'buffer');58test('stdio[*] output can be [3, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 3, 1, [3, 'pipe'], true, 'buffer');33test('stdout can be ["inherit", "pipe"]', () => testInheritStdioOutput(1, 2, ['inherit', 'pipe'], false, 'utf8'));34test('stdout can be [1, "pipe"]', () => testInheritStdioOutput(1, 2, [1, 'pipe'], false, 'utf8'));35test('stdout can be [process.stdout, "pipe"]', () => testInheritStdioOutput(1, 2, ['stdout', 'pipe'], false, 'utf8'));36test('stderr can be ["inherit", "pipe"]', () => testInheritStdioOutput(2, 1, ['inherit', 'pipe'], false, 'utf8'));37test('stderr can be [2, "pipe"]', () => testInheritStdioOutput(2, 1, [2, 'pipe'], false, 'utf8'));38test('stderr can be [process.stderr, "pipe"]', () => testInheritStdioOutput(2, 1, ['stderr', 'pipe'], false, 'utf8'));39test('stdout can be ["inherit", "pipe"], encoding "buffer"', () => testInheritStdioOutput(1, 2, ['inherit', 'pipe'], false, 'buffer'));40test('stdout can be [1, "pipe"], encoding "buffer"', () => testInheritStdioOutput(1, 2, [1, 'pipe'], false, 'buffer'));41test('stdout can be [process.stdout, "pipe"], encoding "buffer"', () => testInheritStdioOutput(1, 2, ['stdout', 'pipe'], false, 'buffer'));42test('stderr can be ["inherit", "pipe"], encoding "buffer"', () => testInheritStdioOutput(2, 1, ['inherit', 'pipe'], false, 'buffer'));43test('stderr can be [2, "pipe"], encoding "buffer"', () => testInheritStdioOutput(2, 1, [2, 'pipe'], false, 'buffer'));44test('stderr can be [process.stderr, "pipe"], encoding "buffer"', () => testInheritStdioOutput(2, 1, ['stderr', 'pipe'], false, 'buffer'));45test('stdout can be ["inherit", "pipe"], sync', () => testInheritStdioOutput(1, 2, ['inherit', 'pipe'], true, 'utf8'));46test('stdout can be [1, "pipe"], sync', () => testInheritStdioOutput(1, 2, [1, 'pipe'], true, 'utf8'));47test('stdout can be [process.stdout, "pipe"], sync', () => testInheritStdioOutput(1, 2, ['stdout', 'pipe'], true, 'utf8'));48test('stderr can be ["inherit", "pipe"], sync', () => testInheritStdioOutput(2, 1, ['inherit', 'pipe'], true, 'utf8'));49test('stderr can be [2, "pipe"], sync', () => testInheritStdioOutput(2, 1, [2, 'pipe'], true, 'utf8'));50test('stderr can be [process.stderr, "pipe"], sync', () => testInheritStdioOutput(2, 1, ['stderr', 'pipe'], true, 'utf8'));51test('stdio[*] output can be ["inherit", "pipe"], sync', () => testInheritStdioOutput(3, 1, ['inherit', 'pipe'], true, 'utf8'));52test('stdio[*] output can be [3, "pipe"], sync', () => testInheritStdioOutput(3, 1, [3, 'pipe'], true, 'utf8'));53test('stdout can be ["inherit", "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(1, 2, ['inherit', 'pipe'], true, 'buffer'));54test('stdout can be [1, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(1, 2, [1, 'pipe'], true, 'buffer'));55test('stdout can be [process.stdout, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(1, 2, ['stdout', 'pipe'], true, 'buffer'));56test('stderr can be ["inherit", "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(2, 1, ['inherit', 'pipe'], true, 'buffer'));57test('stderr can be [2, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(2, 1, [2, 'pipe'], true, 'buffer'));58test('stderr can be [process.stderr, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(2, 1, ['stderr', 'pipe'], true, 'buffer'));59test('stdio[*] output can be ["inherit", "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(3, 1, ['inherit', 'pipe'], true, 'buffer'));60test('stdio[*] output can be [3, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(3, 1, [3, 'pipe'], true, 'buffer'));6160const testInheritNoBuffer = async (t, stdioOption, isSync) => {62const testInheritNoBuffer = async (stdioOption, isSync) => {63 const filePath = tempfile();64 await nestedSubprocess('nested-write.js', [filePath, foobarString], {stdin: stdioOption, buffer: false, isSync}, {input: foobarString});63 t.is(await readFile(filePath, 'utf8'), `${foobarString} ${foobarString}`);65 assert.equal(await readFile(filePath, 'utf8'), `${foobarString} ${foobarString}`);66 await rm(filePath);67};6867test('stdin can be ["inherit", "pipe"], buffer: false', testInheritNoBuffer, ['inherit', 'pipe'], false);68test('stdin can be [0, "pipe"], buffer: false', testInheritNoBuffer, [0, 'pipe'], false);69test.serial('stdin can be ["inherit", "pipe"], buffer: false, sync', testInheritNoBuffer, ['inherit', 'pipe'], true);70test.serial('stdin can be [0, "pipe"], buffer: false, sync', testInheritNoBuffer, [0, 'pipe'], true);69test('stdin can be ["inherit", "pipe"], buffer: false', () => testInheritNoBuffer(['inherit', 'pipe'], false));70test('stdin can be [0, "pipe"], buffer: false', () => testInheritNoBuffer([0, 'pipe'], false));71test('stdin can be ["inherit", "pipe"], buffer: false, sync', () => testInheritNoBuffer(['inherit', 'pipe'], true));72test('stdin can be [0, "pipe"], buffer: false, sync', () => testInheritNoBuffer([0, 'pipe'], true));7372test('stdin can use ["inherit", "pipe"] in a TTY', async t => {74test('stdin can use ["inherit", "pipe"] in a TTY', async () => {75 const stdioOption = [['inherit', 'pipe'], 'inherit', 'pipe'];76 const {stdout} = await execa('nested-sync-tty.js', [JSON.stringify({stdio: stdioOption}), 'false', 'stdin-fd.js', '0'], {input: foobarString});75 t.is(stdout, foobarString);77 assert.equal(stdout, foobarString);78});7978const testNoTtyInput = async (t, fdNumber, optionName) => {80const testNoTtyInput = async (fdNumber, optionName) => {81 const stdioOption = ['pipe', 'inherit', 'pipe'];82 stdioOption[fdNumber] = [[''], 'inherit', 'pipe'];81 const {message} = await t.throwsAsync(execa('nested-sync-tty.js', [JSON.stringify({stdio: stdioOption}), 'true', 'stdin-fd.js', `${fdNumber}`], fullStdio));82 t.true(message.includes(`The \`${optionName}: 'inherit'\` option is invalid: it cannot be a TTY`));83 const {message} = await assertRejects(execa('nested-sync-tty.js', [JSON.stringify({stdio: stdioOption}), 'true', 'stdin-fd.js', `${fdNumber}`], fullStdio));84 assert.ok(message.includes(`The \`${optionName}: 'inherit'\` option is invalid: it cannot be a TTY`));85};8685test('stdin cannot use ["inherit", "pipe"] in a TTY, sync', testNoTtyInput, 0, 'stdin');86test('stdio[*] input cannot use ["inherit", "pipe"] in a TTY, sync', testNoTtyInput, 3, 'stdio[3]');87test('stdin cannot use ["inherit", "pipe"] in a TTY, sync', () => testNoTtyInput(0, 'stdin'));88test('stdio[*] input cannot use ["inherit", "pipe"] in a TTY, sync', () => testNoTtyInput(3, 'stdio[3]'));8988const testTtyOutput = async (t, fdNumber, isSync) => {90const testTtyOutput = async (fdNumber, isSync) => {91 const {stdio} = await execa('nested-sync-tty.js', [JSON.stringify(getStdio(fdNumber, ['inherit', 'pipe'])), `${isSync}`, 'noop-fd.js', `${fdNumber}`, foobarString], fullStdio);90 t.is(stdio[fdNumber], foobarString);92 assert.equal(stdio[fdNumber], foobarString);93};9493test('stdout can use ["inherit", "pipe"] in a TTY', testTtyOutput, 1, false);94test('stderr can use ["inherit", "pipe"] in a TTY', testTtyOutput, 2, false);95test('stdout can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 1, true);96test('stderr can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 2, true);97test('stdio[*] output can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 3, true);95test('stdout can use ["inherit", "pipe"] in a TTY', () => testTtyOutput(1, false));96test('stderr can use ["inherit", "pipe"] in a TTY', () => testTtyOutput(2, false));97test('stdout can use ["inherit", "pipe"] in a TTY, sync', () => testTtyOutput(1, true));98test('stderr can use ["inherit", "pipe"] in a TTY, sync', () => testTtyOutput(2, true));99test('stdio[*] output can use ["inherit", "pipe"] in a TTY, sync', () => testTtyOutput(3, true));
modified:test/stdio/native-redirect.js+58 added-58 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {foobarString} from '../helpers/input.js';67setFixtureDirectory();88// eslint-disable-next-line max-params9const testRedirect = async (t, stdioOption, fdNumber, isInput, isSync) => {9const testRedirect = async (stdioOption, fdNumber, isInput, isSync) => {10 const {fixtureName, ...options} = isInput11 ? {fixtureName: 'stdin-fd.js', input: foobarString}12 : {fixtureName: 'noop-fd.js'};13 const {stdio} = await execa('nested-stdio.js', [JSON.stringify(stdioOption), `${fdNumber}`, `${isSync}`, fixtureName, foobarString], options);14 const resultFdNumber = isStderrDescriptor(stdioOption) ? 2 : 1;15 t.is(stdio[resultFdNumber], foobarString);15 assert.equal(stdio[resultFdNumber], foobarString);16};1718const isStderrDescriptor = stdioOption => stdioOption === 219 || stdioOption === 'stderr'20 || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));2122test.serial('stdio[*] can be 0', testRedirect, 0, 3, true, false);23test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true, false);24test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true, false);25test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true, false);26test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true, false);27test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true, false);28test('stdout can be 2', testRedirect, 2, 1, false, false);29test('stdout can be [2]', testRedirect, [2], 1, false, false);30test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false, false);31test('stdout can be process.stderr', testRedirect, 'stderr', 1, false, false);32test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false, false);33test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false, false);34test('stderr can be 1', testRedirect, 1, 2, false, false);35test('stderr can be [1]', testRedirect, [1], 2, false, false);36test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false, false);37test('stderr can be process.stdout', testRedirect, 'stdout', 2, false, false);38test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false, false);39test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false, false);40test('stdio[*] can be 1', testRedirect, 1, 3, false, false);41test('stdio[*] can be [1]', testRedirect, [1], 3, false, false);42test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false, false);43test('stdio[*] can be 2', testRedirect, 2, 3, false, false);44test('stdio[*] can be [2]', testRedirect, [2], 3, false, false);45test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false, false);46test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false, false);47test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false, false);48test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false, false);49test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false, false);50test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false, false);51test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false, false);52test('stdout can be 2, sync', testRedirect, 2, 1, false, true);53test('stdout can be [2], sync', testRedirect, [2], 1, false, true);54test('stdout can be [2, "pipe"], sync', testRedirect, [2, 'pipe'], 1, false, true);55test('stdout can be process.stderr, sync', testRedirect, 'stderr', 1, false, true);56test('stdout can be [process.stderr], sync', testRedirect, ['stderr'], 1, false, true);57test('stdout can be [process.stderr, "pipe"], sync', testRedirect, ['stderr', 'pipe'], 1, false, true);58test('stderr can be 1, sync', testRedirect, 1, 2, false, true);59test('stderr can be [1], sync', testRedirect, [1], 2, false, true);60test('stderr can be [1, "pipe"], sync', testRedirect, [1, 'pipe'], 2, false, true);61test('stderr can be process.stdout, sync', testRedirect, 'stdout', 2, false, true);62test('stderr can be [process.stdout], sync', testRedirect, ['stdout'], 2, false, true);63test('stderr can be [process.stdout, "pipe"], sync', testRedirect, ['stdout', 'pipe'], 2, false, true);64test('stdio[*] can be 1, sync', testRedirect, 1, 3, false, true);65test('stdio[*] can be [1], sync', testRedirect, [1], 3, false, true);66test('stdio[*] can be [1, "pipe"], sync', testRedirect, [1, 'pipe'], 3, false, true);67test('stdio[*] can be 2, sync', testRedirect, 2, 3, false, true);68test('stdio[*] can be [2], sync', testRedirect, [2], 3, false, true);69test('stdio[*] can be [2, "pipe"], sync', testRedirect, [2, 'pipe'], 3, false, true);70test('stdio[*] can be process.stdout, sync', testRedirect, 'stdout', 3, false, true);71test('stdio[*] can be [process.stdout], sync', testRedirect, ['stdout'], 3, false, true);72test('stdio[*] can be [process.stdout, "pipe"], sync', testRedirect, ['stdout', 'pipe'], 3, false, true);73test('stdio[*] can be process.stderr, sync', testRedirect, 'stderr', 3, false, true);74test('stdio[*] can be [process.stderr], sync', testRedirect, ['stderr'], 3, false, true);75test('stdio[*] can be [process.stderr, "pipe"], sync', testRedirect, ['stderr', 'pipe'], 3, false, true);22test('stdio[*] can be 0', () => testRedirect(0, 3, true, false));23test('stdio[*] can be [0]', () => testRedirect([0], 3, true, false));24test('stdio[*] can be [0, "pipe"]', () => testRedirect([0, 'pipe'], 3, true, false));25test('stdio[*] can be process.stdin', () => testRedirect('stdin', 3, true, false));26test('stdio[*] can be [process.stdin]', () => testRedirect(['stdin'], 3, true, false));27test('stdio[*] can be [process.stdin, "pipe"]', () => testRedirect(['stdin', 'pipe'], 3, true, false));28test('stdout can be 2', () => testRedirect(2, 1, false, false));29test('stdout can be [2]', () => testRedirect([2], 1, false, false));30test('stdout can be [2, "pipe"]', () => testRedirect([2, 'pipe'], 1, false, false));31test('stdout can be process.stderr', () => testRedirect('stderr', 1, false, false));32test('stdout can be [process.stderr]', () => testRedirect(['stderr'], 1, false, false));33test('stdout can be [process.stderr, "pipe"]', () => testRedirect(['stderr', 'pipe'], 1, false, false));34test('stderr can be 1', () => testRedirect(1, 2, false, false));35test('stderr can be [1]', () => testRedirect([1], 2, false, false));36test('stderr can be [1, "pipe"]', () => testRedirect([1, 'pipe'], 2, false, false));37test('stderr can be process.stdout', () => testRedirect('stdout', 2, false, false));38test('stderr can be [process.stdout]', () => testRedirect(['stdout'], 2, false, false));39test('stderr can be [process.stdout, "pipe"]', () => testRedirect(['stdout', 'pipe'], 2, false, false));40test('stdio[*] can be 1', () => testRedirect(1, 3, false, false));41test('stdio[*] can be [1]', () => testRedirect([1], 3, false, false));42test('stdio[*] can be [1, "pipe"]', () => testRedirect([1, 'pipe'], 3, false, false));43test('stdio[*] can be 2', () => testRedirect(2, 3, false, false));44test('stdio[*] can be [2]', () => testRedirect([2], 3, false, false));45test('stdio[*] can be [2, "pipe"]', () => testRedirect([2, 'pipe'], 3, false, false));46test('stdio[*] can be process.stdout', () => testRedirect('stdout', 3, false, false));47test('stdio[*] can be [process.stdout]', () => testRedirect(['stdout'], 3, false, false));48test('stdio[*] can be [process.stdout, "pipe"]', () => testRedirect(['stdout', 'pipe'], 3, false, false));49test('stdio[*] can be process.stderr', () => testRedirect('stderr', 3, false, false));50test('stdio[*] can be [process.stderr]', () => testRedirect(['stderr'], 3, false, false));51test('stdio[*] can be [process.stderr, "pipe"]', () => testRedirect(['stderr', 'pipe'], 3, false, false));52test('stdout can be 2, sync', () => testRedirect(2, 1, false, true));53test('stdout can be [2], sync', () => testRedirect([2], 1, false, true));54test('stdout can be [2, "pipe"], sync', () => testRedirect([2, 'pipe'], 1, false, true));55test('stdout can be process.stderr, sync', () => testRedirect('stderr', 1, false, true));56test('stdout can be [process.stderr], sync', () => testRedirect(['stderr'], 1, false, true));57test('stdout can be [process.stderr, "pipe"], sync', () => testRedirect(['stderr', 'pipe'], 1, false, true));58test('stderr can be 1, sync', () => testRedirect(1, 2, false, true));59test('stderr can be [1], sync', () => testRedirect([1], 2, false, true));60test('stderr can be [1, "pipe"], sync', () => testRedirect([1, 'pipe'], 2, false, true));61test('stderr can be process.stdout, sync', () => testRedirect('stdout', 2, false, true));62test('stderr can be [process.stdout], sync', () => testRedirect(['stdout'], 2, false, true));63test('stderr can be [process.stdout, "pipe"], sync', () => testRedirect(['stdout', 'pipe'], 2, false, true));64test('stdio[*] can be 1, sync', () => testRedirect(1, 3, false, true));65test('stdio[*] can be [1], sync', () => testRedirect([1], 3, false, true));66test('stdio[*] can be [1, "pipe"], sync', () => testRedirect([1, 'pipe'], 3, false, true));67test('stdio[*] can be 2, sync', () => testRedirect(2, 3, false, true));68test('stdio[*] can be [2], sync', () => testRedirect([2], 3, false, true));69test('stdio[*] can be [2, "pipe"], sync', () => testRedirect([2, 'pipe'], 3, false, true));70test('stdio[*] can be process.stdout, sync', () => testRedirect('stdout', 3, false, true));71test('stdio[*] can be [process.stdout], sync', () => testRedirect(['stdout'], 3, false, true));72test('stdio[*] can be [process.stdout, "pipe"], sync', () => testRedirect(['stdout', 'pipe'], 3, false, true));73test('stdio[*] can be process.stderr, sync', () => testRedirect('stderr', 3, false, true));74test('stdio[*] can be [process.stderr], sync', () => testRedirect(['stderr'], 3, false, true));75test('stdio[*] can be [process.stderr, "pipe"], sync', () => testRedirect(['stderr', 'pipe'], 3, false, true));
modified:test/stdio/node-stream-custom.js+70 added-68 removed
1import assert from 'node:assert/strict';2import {createReadStream, createWriteStream} from 'node:fs';3import {readFile, writeFile, rm} from 'node:fs/promises';4import {Writable, PassThrough} from 'node:stream';5import {text} from 'node:stream/consumers';6import {setImmediate} from 'node:timers/promises';7import {callbackify} from 'node:util';7import test from 'ava';8import test from 'node:test';9import tempfile from 'tempfile';10import {assertThrows, assertRejects, assertLike} from '../helpers/assert.js';11import {execa, execaSync} from '../../index.js';12import {setFixtureDirectory} from '../helpers/fixtures-directory.js';13import {getStdio} from '../helpers/stdio.js';14import {foobarString} from '../helpers/input.js';
1 unmodified line
16import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';1718setFixtureDirectory();1918const testLazyFileReadable = async (t, fdNumber) => {20const testLazyFileReadable = async fdNumber => {21 const filePath = tempfile();22 await writeFile(filePath, 'foobar');23 const stream = createReadStream(filePath);2425 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));24 t.is(stdout, 'foobar');26 assert.equal(stdout, 'foobar');2728 await rm(filePath);29};3029test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 0);30test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 3);31test('stdin can be [Readable, "pipe"] without a file descriptor', () => testLazyFileReadable(0));32test('stdio[*] can be [Readable, "pipe"] without a file descriptor', () => testLazyFileReadable(3));3332const testLazyFileReadableSync = (t, fdNumber) => {33 t.throws(() => {34const testLazyFileReadableSync = fdNumber => {35 assertThrows(() => {36 execaSync('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [noopReadable(), 'pipe']));37 }, {message: /cannot both be an array and include a stream/});38};3938test('stdin cannot be [Readable, "pipe"] without a file descriptor, sync', testLazyFileReadableSync, 0);39test('stdio[*] cannot be [Readable, "pipe"] without a file descriptor, sync', testLazyFileReadableSync, 3);40test('stdin cannot be [Readable, "pipe"] without a file descriptor, sync', () => testLazyFileReadableSync(0));41test('stdio[*] cannot be [Readable, "pipe"] without a file descriptor, sync', () => testLazyFileReadableSync(3));4241const testLazyFileWritable = async (t, fdNumber) => {43const testLazyFileWritable = async fdNumber => {44 const filePath = tempfile();45 const stream = createWriteStream(filePath);4647 await execa('noop-fd.js', [`${fdNumber}`, 'foobar'], getStdio(fdNumber, [stream, 'pipe']));46 t.is(await readFile(filePath, 'utf8'), 'foobar');48 assert.equal(await readFile(filePath, 'utf8'), 'foobar');4950 await rm(filePath);51};5251test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);52test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);53test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);53test('stdout can be [Writable, "pipe"] without a file descriptor', () => testLazyFileWritable(1));54test('stderr can be [Writable, "pipe"] without a file descriptor', () => testLazyFileWritable(2));55test('stdio[*] can be [Writable, "pipe"] without a file descriptor', () => testLazyFileWritable(3));5655const testLazyFileWritableSync = (t, fdNumber) => {56 t.throws(() => {57const testLazyFileWritableSync = fdNumber => {58 assertThrows(() => {59 execaSync('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [noopWritable(), 'pipe']));60 }, {message: /cannot both be an array and include a stream/});61};6261test('stdout cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 1);62test('stderr cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 2);63test('stdio[*] cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 3);63test('stdout cannot be [Writable, "pipe"] without a file descriptor, sync', () => testLazyFileWritableSync(1));64test('stderr cannot be [Writable, "pipe"] without a file descriptor, sync', () => testLazyFileWritableSync(2));65test('stdio[*] cannot be [Writable, "pipe"] without a file descriptor, sync', () => testLazyFileWritableSync(3));6667/*68An output stream is written to, then handed back to the user.69We must only wait for our writes to be flushed, not for the user to consume its readable side,70otherwise the subprocess promise hangs until they do.71*/70const testUnconsumedOutputStream = async (t, fdNumber) => {72const testUnconsumedOutputStream = async fdNumber => {73 const stream = new PassThrough();74 const {exitCode} = await execa('empty.js', {...getStdio(fdNumber, [stream, 'pipe']), timeout: 1e3});73 t.is(exitCode, 0);75 assert.equal(exitCode, 0);76};7776test('stdout does not wait for the user to consume the output stream', testUnconsumedOutputStream, 1);77test('stderr does not wait for the user to consume the output stream', testUnconsumedOutputStream, 2);78test('stdio[*] does not wait for the user to consume the output stream', testUnconsumedOutputStream, 3);78test('stdout does not wait for the user to consume the output stream', () => testUnconsumedOutputStream(1));79test('stderr does not wait for the user to consume the output stream', () => testUnconsumedOutputStream(2));80test('stdio[*] does not wait for the user to consume the output stream', () => testUnconsumedOutputStream(3));8180test('stdout does not wait for the user to consume the output stream on subprocess errors', async t => {82test('stdout does not wait for the user to consume the output stream on subprocess errors', async () => {83 const stream = new PassThrough();82 const error = await t.throwsAsync(execa('fail.js', {...getStdio(1, [stream, 'pipe']), timeout: 1e3}));83 t.false(error.timedOut);84 t.is(error.exitCode, 2);84 const error = await assertRejects(execa('fail.js', {...getStdio(1, [stream, 'pipe']), timeout: 1e3}));85 assert.equal(error.timedOut, false);86 assert.equal(error.exitCode, 2);87});8889// The stream is handed back to the user with its data still readable88test('output stream data is readable once the subprocess is done', async t => {90test('output stream data is readable once the subprocess is done', async () => {91 const stream = new PassThrough();92 await execa('noop.js', [foobarString], {...getStdio(1, [stream, 'pipe'])});91 t.is(await text(stream), `${foobarString}\n`);93 assert.equal(await text(stream), `${foobarString}\n`);94});9594test('Waits for custom streams destroy on subprocess errors', async t => {96test('Waits for custom streams destroy on subprocess errors', async () => {97 let isWaitedForDestroy = false;98 const stream = new Writable({99 destroy: callbackify(async error => {100 await setImmediate();101 isWaitedForDestroy = true;102 return error;103 }),104 });103 const {timedOut} = await t.throwsAsync(execa('forever.js', {stdout: [stream, 'pipe'], timeout: 1}));104 t.true(timedOut);105 t.true(isWaitedForDestroy);105 const {timedOut} = await assertRejects(execa('forever.js', {stdout: [stream, 'pipe'], timeout: 1}));106 assert.equal(timedOut, true);107 assert.equal(isWaitedForDestroy, true);108});109108test('Handles custom streams destroy errors on subprocess success', async t => {110test('Handles custom streams destroy errors on subprocess success', async () => {111 const cause = new Error('test');112 const stream = new Writable({113 destroy(destroyError, done) {114 done(destroyError ?? cause);115 },116 });115 const error = await t.throwsAsync(execa('empty.js', {stdout: [stream, 'pipe']}));116 t.is(error.cause, cause);117 const error = await assertRejects(execa('empty.js', {stdout: [stream, 'pipe']}));118 assert.equal(error.cause, cause);119});120119const testStreamEarlyExit = async (t, stream, streamName) => {120 const error = await t.throwsAsync(getEarlyErrorSubprocess({[streamName]: [stream, 'pipe']}));121 t.like(error, expectedEarlyError);122 t.true(stream.destroyed);121const testStreamEarlyExit = async (stream, streamName) => {122 const error = await assertRejects(getEarlyErrorSubprocess({[streamName]: [stream, 'pipe']}));123 assertLike(error, expectedEarlyError);124 assert.equal(stream.destroyed, true);125};126125test('Input streams are canceled on early subprocess exit', testStreamEarlyExit, noopReadable(), 'stdin');126test('Output streams are canceled on early subprocess exit', testStreamEarlyExit, noopWritable(), 'stdout');127test('Input streams are canceled on early subprocess exit', () => testStreamEarlyExit(noopReadable(), 'stdin'));128test('Output streams are canceled on early subprocess exit', () => testStreamEarlyExit(noopWritable(), 'stdout'));129128const testInputDuplexStream = async (t, fdNumber) => {130const testInputDuplexStream = async fdNumber => {131 const stream = new PassThrough();132 stream.end(foobarString);133 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));132 t.is(stdout, foobarString);134 assert.equal(stdout, foobarString);135};136135test('Can pass Duplex streams to stdin', testInputDuplexStream, 0);136test('Can pass Duplex streams to input stdio[*]', testInputDuplexStream, 3);137test('Can pass Duplex streams to stdin', () => testInputDuplexStream(0));138test('Can pass Duplex streams to input stdio[*]', () => testInputDuplexStream(3));139138const testOutputDuplexStream = async (t, fdNumber) => {140const testOutputDuplexStream = async fdNumber => {141 const stream = new PassThrough();142 const [output] = await Promise.all([143 text(stream),144 execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe'])),145 ]);144 t.is(output, foobarString);146 assert.equal(output, foobarString);147};148147test('Can pass Duplex streams to stdout', testOutputDuplexStream, 1);148test('Can pass Duplex streams to stderr', testOutputDuplexStream, 2);149test('Can pass Duplex streams to output stdio[*]', testOutputDuplexStream, 3);149test('Can pass Duplex streams to stdout', () => testOutputDuplexStream(1));150test('Can pass Duplex streams to stderr', () => testOutputDuplexStream(2));151test('Can pass Duplex streams to output stdio[*]', () => testOutputDuplexStream(3));152151const testInputStreamAbort = async (t, fdNumber) => {153const testInputStreamAbort = async fdNumber => {154 const stream = new PassThrough();155 stream.destroy();156157 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));158 await subprocess;157 t.true(subprocess.stdio[fdNumber].writableEnded);159 assert.ok(subprocess.stdio[fdNumber].writableEnded);160};161160test('subprocess.stdin is ended when an input stream aborts', testInputStreamAbort, 0);161test('subprocess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);162test('subprocess.stdin is ended when an input stream aborts', () => testInputStreamAbort(0));163test('subprocess.stdio[*] is ended when an input stream aborts', () => testInputStreamAbort(3));164163const testInputStreamError = async (t, fdNumber) => {165const testInputStreamError = async fdNumber => {166 const stream = new PassThrough();167 const cause = new Error(foobarString);168 stream.destroy(cause);169170 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, new Uint8Array()]));169 t.like(await t.throwsAsync(subprocess), {cause});170 t.true(subprocess.stdio[fdNumber].writableEnded);171 assertLike(await assertRejects(subprocess), {cause});172 assert.ok(subprocess.stdio[fdNumber].writableEnded);173};174173test('subprocess.stdin is ended when an input stream errors', testInputStreamError, 0);174test('subprocess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);175test('subprocess.stdin is ended when an input stream errors', () => testInputStreamError(0));176test('subprocess.stdio[*] is ended when an input stream errors', () => testInputStreamError(3));177176const testOutputStreamError = async (t, fdNumber) => {178const testOutputStreamError = async fdNumber => {179 const stream = new PassThrough();180 const cause = new Error(foobarString);181 stream.destroy(cause);182183 const subprocess = execa('noop-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));182 t.like(await t.throwsAsync(subprocess), {cause});183 t.true(subprocess.stdio[fdNumber].readableAborted);184 t.is(subprocess.stdio[fdNumber].errored, null);184 assertLike(await assertRejects(subprocess), {cause});185 assert.ok(subprocess.stdio[fdNumber].readableAborted);186 assert.equal(subprocess.stdio[fdNumber].errored, null);187};188187test('subprocess.stdout is aborted when an output stream errors', testOutputStreamError, 1);188test('subprocess.stderr is aborted when an output stream errors', testOutputStreamError, 2);189test('subprocess.stdio[*] is aborted when an output stream errors', testOutputStreamError, 3);189test('subprocess.stdout is aborted when an output stream errors', () => testOutputStreamError(1));190test('subprocess.stderr is aborted when an output stream errors', () => testOutputStreamError(2));191test('subprocess.stdio[*] is aborted when an output stream errors', () => testOutputStreamError(3));
modified:test/stdio/node-stream-native.js+82 added-80 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {createReadStream, createWriteStream} from 'node:fs';4import {readFile, writeFile, rm} from 'node:fs/promises';4import test from 'ava';5import test from 'node:test';6import tempfile from 'tempfile';7import {assertThrows, assertRejects} from '../helpers/assert.js';8import {execa, execaSync} from '../../index.js';9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10import {getStdio} from '../helpers/stdio.js';11import {foobarString} from '../helpers/input.js';
5 unmodified lines
17} from '../helpers/stream.js';1819setFixtureDirectory();2019const testNoFileStreamSync = async (t, fdNumber, stream) => {20 t.throws(() => {21const testNoFileStreamSync = async (fdNumber, stream) => {22 assertThrows(() => {23 execaSync('empty.js', getStdio(fdNumber, stream));24 }, {code: 'ERR_INVALID_ARG_VALUE'});25};2625test('stdin cannot be a Node.js Readable without a file descriptor - sync', testNoFileStreamSync, 0, noopReadable());26test('stdin cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 0, noopDuplex());27test('stdout cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 1, noopWritable());28test('stdout cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 1, noopDuplex());29test('stderr cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 2, noopWritable());30test('stderr cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 2, noopDuplex());31test('stdio[*] cannot be a Node.js Readable without a file descriptor - sync', testNoFileStreamSync, 3, noopReadable());32test('stdio[*] cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 3, noopWritable());33test('stdio[*] cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 3, noopDuplex());27test('stdin cannot be a Node.js Readable without a file descriptor - sync', () => testNoFileStreamSync(0, noopReadable()));28test('stdin cannot be a Node.js Duplex without a file descriptor - sync', () => testNoFileStreamSync(0, noopDuplex()));29test('stdout cannot be a Node.js Writable without a file descriptor - sync', () => testNoFileStreamSync(1, noopWritable()));30test('stdout cannot be a Node.js Duplex without a file descriptor - sync', () => testNoFileStreamSync(1, noopDuplex()));31test('stderr cannot be a Node.js Writable without a file descriptor - sync', () => testNoFileStreamSync(2, noopWritable()));32test('stderr cannot be a Node.js Duplex without a file descriptor - sync', () => testNoFileStreamSync(2, noopDuplex()));33test('stdio[*] cannot be a Node.js Readable without a file descriptor - sync', () => testNoFileStreamSync(3, noopReadable()));34test('stdio[*] cannot be a Node.js Writable without a file descriptor - sync', () => testNoFileStreamSync(3, noopWritable()));35test('stdio[*] cannot be a Node.js Duplex without a file descriptor - sync', () => testNoFileStreamSync(3, noopDuplex()));3635test('input can be a Node.js Readable without a file descriptor', async t => {37test('input can be a Node.js Readable without a file descriptor', async () => {38 const {stdout} = await execa('stdin.js', {input: simpleReadable()});37 t.is(stdout, foobarString);39 assert.equal(stdout, foobarString);40});4140test('input cannot be a Node.js Readable without a file descriptor - sync', t => {41 t.throws(() => {42test('input cannot be a Node.js Readable without a file descriptor - sync', () => {43 assertThrows(() => {44 execaSync('empty.js', {input: simpleReadable()});45 }, {message: 'The `input` option cannot be a Node.js stream with synchronous methods.'});46});4746const testNoFileStream = async (t, fdNumber, stream) => {47 await t.throwsAsync(execa('empty.js', getStdio(fdNumber, stream)), {code: 'ERR_INVALID_ARG_VALUE'});48const testNoFileStream = async (fdNumber, stream) => {49 await assertRejects(execa('empty.js', getStdio(fdNumber, stream)), {code: 'ERR_INVALID_ARG_VALUE'});50};5150test('stdin cannot be a Node.js Readable without a file descriptor', testNoFileStream, 0, noopReadable());51test('stdin cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 0, noopDuplex());52test('stdout cannot be a Node.js Writable without a file descriptor', testNoFileStream, 1, noopWritable());53test('stdout cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 1, noopDuplex());54test('stderr cannot be a Node.js Writable without a file descriptor', testNoFileStream, 2, noopWritable());55test('stderr cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 2, noopDuplex());56test('stdio[*] cannot be a Node.js Readable without a file descriptor', testNoFileStream, 3, noopReadable());57test('stdio[*] cannot be a Node.js Writable without a file descriptor', testNoFileStream, 3, noopWritable());58test('stdio[*] cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 3, noopDuplex());52test('stdin cannot be a Node.js Readable without a file descriptor', () => testNoFileStream(0, noopReadable()));53test('stdin cannot be a Node.js Duplex without a file descriptor', () => testNoFileStream(0, noopDuplex()));54test('stdout cannot be a Node.js Writable without a file descriptor', () => testNoFileStream(1, noopWritable()));55test('stdout cannot be a Node.js Duplex without a file descriptor', () => testNoFileStream(1, noopDuplex()));56test('stderr cannot be a Node.js Writable without a file descriptor', () => testNoFileStream(2, noopWritable()));57test('stderr cannot be a Node.js Duplex without a file descriptor', () => testNoFileStream(2, noopDuplex()));58test('stdio[*] cannot be a Node.js Readable without a file descriptor', () => testNoFileStream(3, noopReadable()));59test('stdio[*] cannot be a Node.js Writable without a file descriptor', () => testNoFileStream(3, noopWritable()));60test('stdio[*] cannot be a Node.js Duplex without a file descriptor', () => testNoFileStream(3, noopDuplex()));6162const createFileReadStream = async () => {63 const filePath = tempfile();64 await writeFile(filePath, 'foobar');
8 unmodified lines
73 await once(stream, 'open');74 return {stream, filePath};75};7675const assertFileStreamError = async (t, subprocess, stream, filePath) => {77const assertFileStreamError = async (subprocess, stream, filePath) => {78 const cause = new Error('test');79 stream.destroy(cause);8079 const error = await t.throwsAsync(subprocess);80 t.is(error.cause, cause);81 t.is(error.exitCode, 0);82 t.is(error.signal, undefined);81 const error = await assertRejects(subprocess);82 assert.equal(error.cause, cause);83 assert.equal(error.exitCode, 0);84 assert.equal(error.signal, undefined);8586 await rm(filePath);87};8887const testFileReadable = async (t, fdNumber, execaMethod) => {89const testFileReadable = async (fdNumber, execaMethod) => {90 const {stream, filePath} = await createFileReadStream();9192 const fdNumberString = fdNumber === 'input' ? '0' : `${fdNumber}`;93 const {stdout} = await execaMethod('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));92 t.is(stdout, 'foobar');94 assert.equal(stdout, 'foobar');9596 await rm(filePath);97};9897test('input can be a Node.js Readable with a file descriptor', testFileReadable, 'input', execa);98test('stdin can be a Node.js Readable with a file descriptor', testFileReadable, 0, execa);99test('stdio[*] can be a Node.js Readable with a file descriptor', testFileReadable, 3, execa);100test('stdin can be a Node.js Readable with a file descriptor - sync', testFileReadable, 0, execaSync);101test('stdio[*] can be a Node.js Readable with a file descriptor - sync', testFileReadable, 3, execaSync);99test('input can be a Node.js Readable with a file descriptor', () => testFileReadable('input', execa));100test('stdin can be a Node.js Readable with a file descriptor', () => testFileReadable(0, execa));101test('stdio[*] can be a Node.js Readable with a file descriptor', () => testFileReadable(3, execa));102test('stdin can be a Node.js Readable with a file descriptor - sync', () => testFileReadable(0, execaSync));103test('stdio[*] can be a Node.js Readable with a file descriptor - sync', () => testFileReadable(3, execaSync));104103const testFileReadableError = async (t, fdNumber) => {105const testFileReadableError = async fdNumber => {106 const {stream, filePath} = await createFileReadStream();107108 const fdNumberString = fdNumber === 'input' ? '0' : `${fdNumber}`;109 const subprocess = execa('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));110109 await assertFileStreamError(t, subprocess, stream, filePath);111 await assertFileStreamError(subprocess, stream, filePath);112};113112test.serial('input handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 'input');113test.serial('stdin handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 0);114test.serial('stdio[*] handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 3);114test('input handles errors from a Node.js Readable with a file descriptor', () => testFileReadableError('input'));115test('stdin handles errors from a Node.js Readable with a file descriptor', () => testFileReadableError(0));116test('stdio[*] handles errors from a Node.js Readable with a file descriptor', () => testFileReadableError(3));117116const testFileReadableOpen = async (t, fdNumber, useSingle, execaMethod) => {118const testFileReadableOpen = async (fdNumber, useSingle, execaMethod) => {119 const {stream, filePath} = await createFileReadStream();118 t.deepEqual(stream.eventNames(), []);120 assert.deepEqual(stream.eventNames(), []);121122 const stdioOption = useSingle ? stream : [stream, 'pipe'];123 await execaMethod('empty.js', getStdio(fdNumber, stdioOption));124123 t.is(stream.readable, useSingle && fdNumber !== 'input');124 t.deepEqual(stream.eventNames(), []);125 assert.equal(stream.readable, useSingle && fdNumber !== 'input');126 assert.deepEqual(stream.eventNames(), []);127128 await rm(filePath);129};130129test('input closes a Node.js Readable with a file descriptor', testFileReadableOpen, 'input', true, execa);130test('stdin leaves open a single Node.js Readable with a file descriptor', testFileReadableOpen, 0, true, execa);131test('stdin closes a combined Node.js Readable with a file descriptor', testFileReadableOpen, 0, false, execa);132test('stdio[*] leaves open a single Node.js Readable with a file descriptor', testFileReadableOpen, 3, true, execa);133test('stdin leaves open a single Node.js Readable with a file descriptor - sync', testFileReadableOpen, 0, true, execaSync);134test('stdio[*] leaves open a single Node.js Readable with a file descriptor - sync', testFileReadableOpen, 3, true, execaSync);131test('input closes a Node.js Readable with a file descriptor', () => testFileReadableOpen('input', true, execa));132test('stdin leaves open a single Node.js Readable with a file descriptor', () => testFileReadableOpen(0, true, execa));133test('stdin closes a combined Node.js Readable with a file descriptor', () => testFileReadableOpen(0, false, execa));134test('stdio[*] leaves open a single Node.js Readable with a file descriptor', () => testFileReadableOpen(3, true, execa));135test('stdin leaves open a single Node.js Readable with a file descriptor - sync', () => testFileReadableOpen(0, true, execaSync));136test('stdio[*] leaves open a single Node.js Readable with a file descriptor - sync', () => testFileReadableOpen(3, true, execaSync));137136const testFileWritable = async (t, fdNumber, execaMethod) => {138const testFileWritable = async (fdNumber, execaMethod) => {139 const {stream, filePath} = await createFileWriteStream();140141 await execaMethod('noop-fd.js', [`${fdNumber}`, 'foobar'], getStdio(fdNumber, stream));140 t.is(await readFile(filePath, 'utf8'), 'foobar');142 assert.equal(await readFile(filePath, 'utf8'), 'foobar');143144 await rm(filePath);145};146145test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, 1, execa);146test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, 2, execa);147test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, 3, execa);148test('stdout can be a Node.js Writable with a file descriptor - sync', testFileWritable, 1, execaSync);149test('stderr can be a Node.js Writable with a file descriptor - sync', testFileWritable, 2, execaSync);150test('stdio[*] can be a Node.js Writable with a file descriptor - sync', testFileWritable, 3, execaSync);147test('stdout can be a Node.js Writable with a file descriptor', () => testFileWritable(1, execa));148test('stderr can be a Node.js Writable with a file descriptor', () => testFileWritable(2, execa));149test('stdio[*] can be a Node.js Writable with a file descriptor', () => testFileWritable(3, execa));150test('stdout can be a Node.js Writable with a file descriptor - sync', () => testFileWritable(1, execaSync));151test('stderr can be a Node.js Writable with a file descriptor - sync', () => testFileWritable(2, execaSync));152test('stdio[*] can be a Node.js Writable with a file descriptor - sync', () => testFileWritable(3, execaSync));153152const testFileWritableError = async (t, fdNumber) => {154const testFileWritableError = async fdNumber => {155 const {stream, filePath} = await createFileWriteStream();156157 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, stream));158157 await assertFileStreamError(t, subprocess, stream, filePath);159 await assertFileStreamError(subprocess, stream, filePath);160};161160test.serial('stdout handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 1);161test.serial('stderr handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 2);162test.serial('stdio[*] handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 3);162test('stdout handles errors from a Node.js Writable with a file descriptor', () => testFileWritableError(1));163test('stderr handles errors from a Node.js Writable with a file descriptor', () => testFileWritableError(2));164test('stdio[*] handles errors from a Node.js Writable with a file descriptor', () => testFileWritableError(3));165164const testFileWritableOpen = async (t, fdNumber, useSingle, execaMethod) => {166const testFileWritableOpen = async (fdNumber, useSingle, execaMethod) => {167 const {stream, filePath} = await createFileWriteStream();166 t.deepEqual(stream.eventNames(), []);168 assert.deepEqual(stream.eventNames(), []);169170 const stdioOption = useSingle ? stream : [stream, 'pipe'];171 await execaMethod('empty.js', getStdio(fdNumber, stdioOption));172171 t.is(stream.writable, useSingle);172 t.deepEqual(stream.eventNames(), []);173 assert.equal(stream.writable, useSingle);174 assert.deepEqual(stream.eventNames(), []);175176 await rm(filePath);177};178177test('stdout leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 1, true, execa);178test('stdout closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 1, false, execa);179test('stderr leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 2, true, execa);180test('stderr closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 2, false, execa);181test('stdio[*] leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 3, true, execa);182test('stdio[*] closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 3, false, execa);183test('stdout leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 1, true, execaSync);184test('stderr leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 2, true, execaSync);185test('stdio[*] leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 3, true, execaSync);179test('stdout leaves open a single Node.js Writable with a file descriptor', () => testFileWritableOpen(1, true, execa));180test('stdout closes a combined Node.js Writable with a file descriptor', () => testFileWritableOpen(1, false, execa));181test('stderr leaves open a single Node.js Writable with a file descriptor', () => testFileWritableOpen(2, true, execa));182test('stderr closes a combined Node.js Writable with a file descriptor', () => testFileWritableOpen(2, false, execa));183test('stdio[*] leaves open a single Node.js Writable with a file descriptor', () => testFileWritableOpen(3, true, execa));184test('stdio[*] closes a combined Node.js Writable with a file descriptor', () => testFileWritableOpen(3, false, execa));185test('stdout leaves open a single Node.js Writable with a file descriptor - sync', () => testFileWritableOpen(1, true, execaSync));186test('stderr leaves open a single Node.js Writable with a file descriptor - sync', () => testFileWritableOpen(2, true, execaSync));187test('stdio[*] leaves open a single Node.js Writable with a file descriptor - sync', () => testFileWritableOpen(3, true, execaSync));
modified:test/stdio/stdio-option.js+44 added-38 removed
1import assert from 'node:assert/strict';2import {inspect} from 'node:util';2import test from 'ava';3import test from 'node:test';4import {assertThrows} from '../helpers/assert.js';5import {normalizeStdioOption} from '../../lib/stdio/stdio-option.js';65const stdioMacro = (t, input, expected) => {7const stdioMacro = (input, expected) => {8 if (expected instanceof Error) {7 t.throws(() => {9 assertThrows(() => {10 normalizeStdioOption(input);11 }, {message: expected.message});12 return;13 }1413 t.deepEqual(normalizeStdioOption(input), expected);15 assert.deepEqual(normalizeStdioOption(input), expected);16};1716stdioMacro.title = (_, input) => `execa() ${(inspect(input))}`;18const stdioCases = [19 [{stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']],20 [{stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']],21 [{stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']],2218test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);19test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);20test(stdioMacro, {stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']);23 [{}, ['pipe', 'pipe', 'pipe']],24 [{stdio: []}, ['pipe', 'pipe', 'pipe']],25 [{stdio: [0]}, [0, 'pipe', 'pipe']],26 [{stdio: [0, 1]}, [0, 1, 'pipe']],27 [{stdio: [0, 1, 2]}, [0, 1, 2]],28 [{stdio: [0, 1, 2, 3]}, [0, 1, 2, 3]],29 [{stdio: [undefined, 1, 2]}, ['pipe', 1, 2]],30 [{stdio: [null, 1, 2]}, ['pipe', 1, 2]],31 [{stdio: [0, undefined, 2]}, [0, 'pipe', 2]],32 [{stdio: [0, null, 2]}, [0, 'pipe', 2]],33 [{stdio: [0, 1, undefined]}, [0, 1, 'pipe']],34 [{stdio: [0, 1, null]}, [0, 1, 'pipe']],35 [{stdio: [0, 1, 2, undefined]}, [0, 1, 2, 'ignore']],36 [{stdio: [0, 1, 2, null]}, [0, 1, 2, 'ignore']],3722test(stdioMacro, {}, ['pipe', 'pipe', 'pipe']);23test(stdioMacro, {stdio: []}, ['pipe', 'pipe', 'pipe']);24test(stdioMacro, {stdio: [0]}, [0, 'pipe', 'pipe']);25test(stdioMacro, {stdio: [0, 1]}, [0, 1, 'pipe']);26test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);27test(stdioMacro, {stdio: [0, 1, 2, 3]}, [0, 1, 2, 3]);28test(stdioMacro, {stdio: [undefined, 1, 2]}, ['pipe', 1, 2]);29test(stdioMacro, {stdio: [null, 1, 2]}, ['pipe', 1, 2]);30test(stdioMacro, {stdio: [0, undefined, 2]}, [0, 'pipe', 2]);31test(stdioMacro, {stdio: [0, null, 2]}, [0, 'pipe', 2]);32test(stdioMacro, {stdio: [0, 1, undefined]}, [0, 1, 'pipe']);33test(stdioMacro, {stdio: [0, 1, null]}, [0, 1, 'pipe']);34test(stdioMacro, {stdio: [0, 1, 2, undefined]}, [0, 1, 2, 'ignore']);35test(stdioMacro, {stdio: [0, 1, 2, null]}, [0, 1, 2, 'ignore']);38 [{stdin: 'pipe'}, ['pipe', 'pipe', 'pipe']],39 [{stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']],40 [{stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']],41 [{stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']],42 [{stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']],43 [{stdin: 'pipe', stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']],44 [{stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']],45 [{stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]],46 [{stdin: 0, stdout: 1}, [0, 1, 'pipe']],47 [{stdin: 0, stderr: 2}, [0, 'pipe', 2]],48 [{stdout: 1, stderr: 2}, ['pipe', 1, 2]],4937test(stdioMacro, {stdin: 'pipe'}, ['pipe', 'pipe', 'pipe']);38test(stdioMacro, {stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);39test(stdioMacro, {stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);40test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);41test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);42test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);43test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);44test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);45test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, 'pipe']);46test(stdioMacro, {stdin: 0, stderr: 2}, [0, 'pipe', 2]);47test(stdioMacro, {stdout: 1, stderr: 2}, ['pipe', 1, 2]);50 [{stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`')],5149test(stdioMacro, {stdio: {foo: 'bar'}}, new TypeError('Expected `stdio` to be of type `string` or `Array`, got `object`'));52 [{stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`')],53 [{stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`')],54 [{stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`')],55 [{stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`')],56];5751test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));52test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));53test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));54test(stdioMacro, {stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));58for (const [input, expected] of stdioCases) {59 test(`execa() ${inspect(input)}`, () => stdioMacro(input, expected));60}
modified:test/stdio/type-invalid.js+46 added-46 removed
1import test from 'ava';1import test from 'node:test';2import {assertThrows} from '../helpers/assert.js';3import {execa, execaSync} from '../../index.js';4import {getStdio} from '../helpers/stdio.js';5import {noopGenerator} from '../helpers/generator.js';6import {generatorsMap} from '../helpers/map.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';89setFixtureDirectory();1010const testInvalidGenerator = (t, fdNumber, stdioOption, execaMethod) => {11 t.throws(() => {11const testInvalidGenerator = (fdNumber, stdioOption, execaMethod) => {12 assertThrows(() => {13 execaMethod('empty.js', getStdio(fdNumber, {...noopGenerator(), ...stdioOption}));14 }, {message: 'final' in stdioOption ? /must be a generator/ : /must be a generator, a Duplex stream or a web TransformStream/});15};1616test('Cannot use invalid "transform" with stdin', testInvalidGenerator, 0, {transform: true}, execa);17test('Cannot use invalid "transform" with stdout', testInvalidGenerator, 1, {transform: true}, execa);18test('Cannot use invalid "transform" with stderr', testInvalidGenerator, 2, {transform: true}, execa);19test('Cannot use invalid "transform" with stdio[*]', testInvalidGenerator, 3, {transform: true}, execa);20test('Cannot use invalid "final" with stdin', testInvalidGenerator, 0, {final: true}, execa);21test('Cannot use invalid "final" with stdout', testInvalidGenerator, 1, {final: true}, execa);22test('Cannot use invalid "final" with stderr', testInvalidGenerator, 2, {final: true}, execa);23test('Cannot use invalid "final" with stdio[*]', testInvalidGenerator, 3, {final: true}, execa);24test('Cannot use invalid "transform" with stdin, sync', testInvalidGenerator, 0, {transform: true}, execaSync);25test('Cannot use invalid "transform" with stdout, sync', testInvalidGenerator, 1, {transform: true}, execaSync);26test('Cannot use invalid "transform" with stderr, sync', testInvalidGenerator, 2, {transform: true}, execaSync);27test('Cannot use invalid "transform" with stdio[*], sync', testInvalidGenerator, 3, {transform: true}, execaSync);28test('Cannot use invalid "final" with stdin, sync', testInvalidGenerator, 0, {final: true}, execaSync);29test('Cannot use invalid "final" with stdout, sync', testInvalidGenerator, 1, {final: true}, execaSync);30test('Cannot use invalid "final" with stderr, sync', testInvalidGenerator, 2, {final: true}, execaSync);31test('Cannot use invalid "final" with stdio[*], sync', testInvalidGenerator, 3, {final: true}, execaSync);17test('Cannot use invalid "transform" with stdin', () => testInvalidGenerator(0, {transform: true}, execa));18test('Cannot use invalid "transform" with stdout', () => testInvalidGenerator(1, {transform: true}, execa));19test('Cannot use invalid "transform" with stderr', () => testInvalidGenerator(2, {transform: true}, execa));20test('Cannot use invalid "transform" with stdio[*]', () => testInvalidGenerator(3, {transform: true}, execa));21test('Cannot use invalid "final" with stdin', () => testInvalidGenerator(0, {final: true}, execa));22test('Cannot use invalid "final" with stdout', () => testInvalidGenerator(1, {final: true}, execa));23test('Cannot use invalid "final" with stderr', () => testInvalidGenerator(2, {final: true}, execa));24test('Cannot use invalid "final" with stdio[*]', () => testInvalidGenerator(3, {final: true}, execa));25test('Cannot use invalid "transform" with stdin, sync', () => testInvalidGenerator(0, {transform: true}, execaSync));26test('Cannot use invalid "transform" with stdout, sync', () => testInvalidGenerator(1, {transform: true}, execaSync));27test('Cannot use invalid "transform" with stderr, sync', () => testInvalidGenerator(2, {transform: true}, execaSync));28test('Cannot use invalid "transform" with stdio[*], sync', () => testInvalidGenerator(3, {transform: true}, execaSync));29test('Cannot use invalid "final" with stdin, sync', () => testInvalidGenerator(0, {final: true}, execaSync));30test('Cannot use invalid "final" with stdout, sync', () => testInvalidGenerator(1, {final: true}, execaSync));31test('Cannot use invalid "final" with stderr, sync', () => testInvalidGenerator(2, {final: true}, execaSync));32test('Cannot use invalid "final" with stdio[*], sync', () => testInvalidGenerator(3, {final: true}, execaSync));3333// eslint-disable-next-line max-params34const testInvalidBinary = (t, fdNumber, optionName, type, execaMethod) => {35 t.throws(() => {34const testInvalidBinary = (fdNumber, optionName, type, execaMethod) => {35 assertThrows(() => {36 execaMethod('empty.js', getStdio(fdNumber, {...generatorsMap[type].uppercase(), [optionName]: 'true'}));37 }, {message: /a boolean/});38};3940test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0, 'binary', 'generator', execa);41test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1, 'binary', 'generator', execa);42test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2, 'binary', 'generator', execa);43test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3, 'binary', 'generator', execa);44test('Cannot use invalid "objectMode" with stdin, generators', testInvalidBinary, 0, 'objectMode', 'generator', execa);45test('Cannot use invalid "objectMode" with stdout, generators', testInvalidBinary, 1, 'objectMode', 'generator', execa);46test('Cannot use invalid "objectMode" with stderr, generators', testInvalidBinary, 2, 'objectMode', 'generator', execa);47test('Cannot use invalid "objectMode" with stdio[*], generators', testInvalidBinary, 3, 'objectMode', 'generator', execa);48test('Cannot use invalid "binary" with stdin, sync', testInvalidBinary, 0, 'binary', 'generator', execaSync);49test('Cannot use invalid "binary" with stdout, sync', testInvalidBinary, 1, 'binary', 'generator', execaSync);50test('Cannot use invalid "binary" with stderr, sync', testInvalidBinary, 2, 'binary', 'generator', execaSync);51test('Cannot use invalid "binary" with stdio[*], sync', testInvalidBinary, 3, 'binary', 'generator', execaSync);52test('Cannot use invalid "objectMode" with stdin, generators, sync', testInvalidBinary, 0, 'objectMode', 'generator', execaSync);53test('Cannot use invalid "objectMode" with stdout, generators, sync', testInvalidBinary, 1, 'objectMode', 'generator', execaSync);54test('Cannot use invalid "objectMode" with stderr, generators, sync', testInvalidBinary, 2, 'objectMode', 'generator', execaSync);55test('Cannot use invalid "objectMode" with stdio[*], generators, sync', testInvalidBinary, 3, 'objectMode', 'generator', execaSync);56test('Cannot use invalid "objectMode" with stdin, duplexes', testInvalidBinary, 0, 'objectMode', 'duplex', execa);57test('Cannot use invalid "objectMode" with stdout, duplexes', testInvalidBinary, 1, 'objectMode', 'duplex', execa);58test('Cannot use invalid "objectMode" with stderr, duplexes', testInvalidBinary, 2, 'objectMode', 'duplex', execa);59test('Cannot use invalid "objectMode" with stdio[*], duplexes', testInvalidBinary, 3, 'objectMode', 'duplex', execa);60test('Cannot use invalid "objectMode" with stdin, webTransforms', testInvalidBinary, 0, 'objectMode', 'webTransform', execa);61test('Cannot use invalid "objectMode" with stdout, webTransforms', testInvalidBinary, 1, 'objectMode', 'webTransform', execa);62test('Cannot use invalid "objectMode" with stderr, webTransforms', testInvalidBinary, 2, 'objectMode', 'webTransform', execa);63test('Cannot use invalid "objectMode" with stdio[*], webTransforms', testInvalidBinary, 3, 'objectMode', 'webTransform', execa);40test('Cannot use invalid "binary" with stdin', () => testInvalidBinary(0, 'binary', 'generator', execa));41test('Cannot use invalid "binary" with stdout', () => testInvalidBinary(1, 'binary', 'generator', execa));42test('Cannot use invalid "binary" with stderr', () => testInvalidBinary(2, 'binary', 'generator', execa));43test('Cannot use invalid "binary" with stdio[*]', () => testInvalidBinary(3, 'binary', 'generator', execa));44test('Cannot use invalid "objectMode" with stdin, generators', () => testInvalidBinary(0, 'objectMode', 'generator', execa));45test('Cannot use invalid "objectMode" with stdout, generators', () => testInvalidBinary(1, 'objectMode', 'generator', execa));46test('Cannot use invalid "objectMode" with stderr, generators', () => testInvalidBinary(2, 'objectMode', 'generator', execa));47test('Cannot use invalid "objectMode" with stdio[*], generators', () => testInvalidBinary(3, 'objectMode', 'generator', execa));48test('Cannot use invalid "binary" with stdin, sync', () => testInvalidBinary(0, 'binary', 'generator', execaSync));49test('Cannot use invalid "binary" with stdout, sync', () => testInvalidBinary(1, 'binary', 'generator', execaSync));50test('Cannot use invalid "binary" with stderr, sync', () => testInvalidBinary(2, 'binary', 'generator', execaSync));51test('Cannot use invalid "binary" with stdio[*], sync', () => testInvalidBinary(3, 'binary', 'generator', execaSync));52test('Cannot use invalid "objectMode" with stdin, generators, sync', () => testInvalidBinary(0, 'objectMode', 'generator', execaSync));53test('Cannot use invalid "objectMode" with stdout, generators, sync', () => testInvalidBinary(1, 'objectMode', 'generator', execaSync));54test('Cannot use invalid "objectMode" with stderr, generators, sync', () => testInvalidBinary(2, 'objectMode', 'generator', execaSync));55test('Cannot use invalid "objectMode" with stdio[*], generators, sync', () => testInvalidBinary(3, 'objectMode', 'generator', execaSync));56test('Cannot use invalid "objectMode" with stdin, duplexes', () => testInvalidBinary(0, 'objectMode', 'duplex', execa));57test('Cannot use invalid "objectMode" with stdout, duplexes', () => testInvalidBinary(1, 'objectMode', 'duplex', execa));58test('Cannot use invalid "objectMode" with stderr, duplexes', () => testInvalidBinary(2, 'objectMode', 'duplex', execa));59test('Cannot use invalid "objectMode" with stdio[*], duplexes', () => testInvalidBinary(3, 'objectMode', 'duplex', execa));60test('Cannot use invalid "objectMode" with stdin, webTransforms', () => testInvalidBinary(0, 'objectMode', 'webTransform', execa));61test('Cannot use invalid "objectMode" with stdout, webTransforms', () => testInvalidBinary(1, 'objectMode', 'webTransform', execa));62test('Cannot use invalid "objectMode" with stderr, webTransforms', () => testInvalidBinary(2, 'objectMode', 'webTransform', execa));63test('Cannot use invalid "objectMode" with stdio[*], webTransforms', () => testInvalidBinary(3, 'objectMode', 'webTransform', execa));
modified:test/stdio/type-undefined.js+48 added-48 removed
1import test from 'ava';1import test from 'node:test';2import {assertThrows} from '../helpers/assert.js';3import {execa, execaSync} from '../../index.js';4import {getStdio} from '../helpers/stdio.js';5import {uppercaseGenerator} from '../helpers/generator.js';6import {uppercaseBufferDuplex} from '../helpers/duplex.js';
2 unmodified lines
9import {setFixtureDirectory} from '../helpers/fixtures-directory.js';1011setFixtureDirectory();1212// eslint-disable-next-line max-params13const testUndefinedOption = (t, fdNumber, optionName, type, optionValue) => {14 t.throws(() => {13const testUndefinedOption = (fdNumber, optionName, type, optionValue) => {14 assertThrows(() => {15 execa('empty.js', getStdio(fdNumber, {...generatorsMap[type].uppercase(), [optionName]: optionValue}));16 }, {message: /can only be defined when using a generator/});17};1819test('Cannot use "binary" with duplexes and stdin', testUndefinedOption, 0, 'binary', 'duplex', true);20test('Cannot use "binary" with duplexes and stdout', testUndefinedOption, 1, 'binary', 'duplex', true);21test('Cannot use "binary" with duplexes and stderr', testUndefinedOption, 2, 'binary', 'duplex', true);22test('Cannot use "binary" with duplexes and stdio[*]', testUndefinedOption, 3, 'binary', 'duplex', true);23test('Cannot use "final" with duplexes and stdin', testUndefinedOption, 0, 'final', 'duplex', uppercaseBufferDuplex().transform);24test('Cannot use "final" with duplexes and stdout', testUndefinedOption, 1, 'final', 'duplex', uppercaseBufferDuplex().transform);25test('Cannot use "final" with duplexes and stderr', testUndefinedOption, 2, 'final', 'duplex', uppercaseBufferDuplex().transform);26test('Cannot use "final" with duplexes and stdio[*]', testUndefinedOption, 3, 'final', 'duplex', uppercaseBufferDuplex().transform);27test('Cannot use "binary" with webTransforms and stdin', testUndefinedOption, 0, 'binary', 'webTransform', true);28test('Cannot use "binary" with webTransforms and stdout', testUndefinedOption, 1, 'binary', 'webTransform', true);29test('Cannot use "binary" with webTransforms and stderr', testUndefinedOption, 2, 'binary', 'webTransform', true);30test('Cannot use "binary" with webTransforms and stdio[*]', testUndefinedOption, 3, 'binary', 'webTransform', true);31test('Cannot use "final" with webTransforms and stdin', testUndefinedOption, 0, 'final', 'webTransform', uppercaseBufferWebTransform().transform);32test('Cannot use "final" with webTransforms and stdout', testUndefinedOption, 1, 'final', 'webTransform', uppercaseBufferWebTransform().transform);33test('Cannot use "final" with webTransforms and stderr', testUndefinedOption, 2, 'final', 'webTransform', uppercaseBufferWebTransform().transform);34test('Cannot use "final" with webTransforms and stdio[*]', testUndefinedOption, 3, 'final', 'webTransform', uppercaseBufferWebTransform().transform);19test('Cannot use "binary" with duplexes and stdin', () => testUndefinedOption(0, 'binary', 'duplex', true));20test('Cannot use "binary" with duplexes and stdout', () => testUndefinedOption(1, 'binary', 'duplex', true));21test('Cannot use "binary" with duplexes and stderr', () => testUndefinedOption(2, 'binary', 'duplex', true));22test('Cannot use "binary" with duplexes and stdio[*]', () => testUndefinedOption(3, 'binary', 'duplex', true));23test('Cannot use "final" with duplexes and stdin', () => testUndefinedOption(0, 'final', 'duplex', uppercaseBufferDuplex().transform));24test('Cannot use "final" with duplexes and stdout', () => testUndefinedOption(1, 'final', 'duplex', uppercaseBufferDuplex().transform));25test('Cannot use "final" with duplexes and stderr', () => testUndefinedOption(2, 'final', 'duplex', uppercaseBufferDuplex().transform));26test('Cannot use "final" with duplexes and stdio[*]', () => testUndefinedOption(3, 'final', 'duplex', uppercaseBufferDuplex().transform));27test('Cannot use "binary" with webTransforms and stdin', () => testUndefinedOption(0, 'binary', 'webTransform', true));28test('Cannot use "binary" with webTransforms and stdout', () => testUndefinedOption(1, 'binary', 'webTransform', true));29test('Cannot use "binary" with webTransforms and stderr', () => testUndefinedOption(2, 'binary', 'webTransform', true));30test('Cannot use "binary" with webTransforms and stdio[*]', () => testUndefinedOption(3, 'binary', 'webTransform', true));31test('Cannot use "final" with webTransforms and stdin', () => testUndefinedOption(0, 'final', 'webTransform', uppercaseBufferWebTransform().transform));32test('Cannot use "final" with webTransforms and stdout', () => testUndefinedOption(1, 'final', 'webTransform', uppercaseBufferWebTransform().transform));33test('Cannot use "final" with webTransforms and stderr', () => testUndefinedOption(2, 'final', 'webTransform', uppercaseBufferWebTransform().transform));34test('Cannot use "final" with webTransforms and stdio[*]', () => testUndefinedOption(3, 'final', 'webTransform', uppercaseBufferWebTransform().transform));3536const testUndefinedFinal = (t, fdNumber, type, useTransform) => {37 t.throws(() => {36const testUndefinedFinal = (fdNumber, type, useTransform) => {37 assertThrows(() => {38 execa('empty.js', getStdio(fdNumber, {39 transform: useTransform ? uppercaseGenerator().transform : undefined,40 final: generatorsMap[type].uppercase().transform,41 }));42 }, {message: type === 'duplex' ? /must not be a Duplex/ : /must not be a web TransformStream/});43};4445test('Cannot use "final" with duplexes and stdin, without transform', testUndefinedFinal, 0, 'duplex', false);46test('Cannot use "final" with duplexes and stdout, without transform', testUndefinedFinal, 1, 'duplex', false);47test('Cannot use "final" with duplexes and stderr, without transform', testUndefinedFinal, 2, 'duplex', false);48test('Cannot use "final" with duplexes and stdio[*], without transform', testUndefinedFinal, 3, 'duplex', false);49test('Cannot use "final" with duplexes and stdin, with transform', testUndefinedFinal, 0, 'duplex', true);50test('Cannot use "final" with duplexes and stdout, with transform', testUndefinedFinal, 1, 'duplex', true);51test('Cannot use "final" with duplexes and stderr, with transform', testUndefinedFinal, 2, 'duplex', true);52test('Cannot use "final" with duplexes and stdio[*], with transform', testUndefinedFinal, 3, 'duplex', true);53test('Cannot use "final" with webTransforms and stdin, without transform', testUndefinedFinal, 0, 'webTransform', false);54test('Cannot use "final" with webTransforms and stdout, without transform', testUndefinedFinal, 1, 'webTransform', false);55test('Cannot use "final" with webTransforms and stderr, without transform', testUndefinedFinal, 2, 'webTransform', false);56test('Cannot use "final" with webTransforms and stdio[*], without transform', testUndefinedFinal, 3, 'webTransform', false);57test('Cannot use "final" with webTransforms and stdin, with transform', testUndefinedFinal, 0, 'webTransform', true);58test('Cannot use "final" with webTransforms and stdout, with transform', testUndefinedFinal, 1, 'webTransform', true);59test('Cannot use "final" with webTransforms and stderr, with transform', testUndefinedFinal, 2, 'webTransform', true);60test('Cannot use "final" with webTransforms and stdio[*], with transform', testUndefinedFinal, 3, 'webTransform', true);45test('Cannot use "final" with duplexes and stdin, without transform', () => testUndefinedFinal(0, 'duplex', false));46test('Cannot use "final" with duplexes and stdout, without transform', () => testUndefinedFinal(1, 'duplex', false));47test('Cannot use "final" with duplexes and stderr, without transform', () => testUndefinedFinal(2, 'duplex', false));48test('Cannot use "final" with duplexes and stdio[*], without transform', () => testUndefinedFinal(3, 'duplex', false));49test('Cannot use "final" with duplexes and stdin, with transform', () => testUndefinedFinal(0, 'duplex', true));50test('Cannot use "final" with duplexes and stdout, with transform', () => testUndefinedFinal(1, 'duplex', true));51test('Cannot use "final" with duplexes and stderr, with transform', () => testUndefinedFinal(2, 'duplex', true));52test('Cannot use "final" with duplexes and stdio[*], with transform', () => testUndefinedFinal(3, 'duplex', true));53test('Cannot use "final" with webTransforms and stdin, without transform', () => testUndefinedFinal(0, 'webTransform', false));54test('Cannot use "final" with webTransforms and stdout, without transform', () => testUndefinedFinal(1, 'webTransform', false));55test('Cannot use "final" with webTransforms and stderr, without transform', () => testUndefinedFinal(2, 'webTransform', false));56test('Cannot use "final" with webTransforms and stdio[*], without transform', () => testUndefinedFinal(3, 'webTransform', false));57test('Cannot use "final" with webTransforms and stdin, with transform', () => testUndefinedFinal(0, 'webTransform', true));58test('Cannot use "final" with webTransforms and stdout, with transform', () => testUndefinedFinal(1, 'webTransform', true));59test('Cannot use "final" with webTransforms and stderr, with transform', () => testUndefinedFinal(2, 'webTransform', true));60test('Cannot use "final" with webTransforms and stdio[*], with transform', () => testUndefinedFinal(3, 'webTransform', true));6162const testSyncMethodsDuplex = (t, fdNumber, type) => {63 t.throws(() => {62const testSyncMethodsDuplex = (fdNumber, type) => {63 assertThrows(() => {64 execaSync('empty.js', getStdio(fdNumber, generatorsMap[type].uppercase()));65 }, {message: type === 'duplex' ? /cannot be a Duplex stream/ : /cannot be a web TransformStream/});66};6768test('Cannot use duplexes with sync methods and stdin', testSyncMethodsDuplex, 0, 'duplex');69test('Cannot use duplexes with sync methods and stdout', testSyncMethodsDuplex, 1, 'duplex');70test('Cannot use duplexes with sync methods and stderr', testSyncMethodsDuplex, 2, 'duplex');71test('Cannot use duplexes with sync methods and stdio[*]', testSyncMethodsDuplex, 3, 'duplex');72test('Cannot use webTransforms with sync methods and stdin', testSyncMethodsDuplex, 0, 'webTransform');73test('Cannot use webTransforms with sync methods and stdout', testSyncMethodsDuplex, 1, 'webTransform');74test('Cannot use webTransforms with sync methods and stderr', testSyncMethodsDuplex, 2, 'webTransform');75test('Cannot use webTransforms with sync methods and stdio[*]', testSyncMethodsDuplex, 3, 'webTransform');68test('Cannot use duplexes with sync methods and stdin', () => testSyncMethodsDuplex(0, 'duplex'));69test('Cannot use duplexes with sync methods and stdout', () => testSyncMethodsDuplex(1, 'duplex'));70test('Cannot use duplexes with sync methods and stderr', () => testSyncMethodsDuplex(2, 'duplex'));71test('Cannot use duplexes with sync methods and stdio[*]', () => testSyncMethodsDuplex(3, 'duplex'));72test('Cannot use webTransforms with sync methods and stdin', () => testSyncMethodsDuplex(0, 'webTransform'));73test('Cannot use webTransforms with sync methods and stdout', () => testSyncMethodsDuplex(1, 'webTransform'));74test('Cannot use webTransforms with sync methods and stderr', () => testSyncMethodsDuplex(2, 'webTransform'));75test('Cannot use webTransforms with sync methods and stdio[*]', () => testSyncMethodsDuplex(3, 'webTransform'));
modified:test/stdio/typed-array.js+21 added-19 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {getStdio} from '../helpers/stdio.js';7import {foobarUint8Array, foobarBuffer, foobarString} from '../helpers/input.js';89setFixtureDirectory();109const testUint8Array = async (t, fdNumber, stdioOption, execaMethod) => {11const testUint8Array = async (fdNumber, stdioOption, execaMethod) => {12 const {stdout} = await execaMethod('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, stdioOption));11 t.is(stdout, foobarString);13 assert.equal(stdout, foobarString);14};1514test('stdin option can be a Uint8Array', testUint8Array, 0, foobarUint8Array, execa);15test('stdio[*] option can be a Uint8Array', testUint8Array, 3, foobarUint8Array, execa);16test('stdin option can be a Uint8Array - sync', testUint8Array, 0, foobarUint8Array, execaSync);17test('stdin option can be a Buffer', testUint8Array, 0, foobarBuffer, execa);18test('stdio[*] option can be a Buffer', testUint8Array, 3, foobarBuffer, execa);19test('stdin option can be a Buffer - sync', testUint8Array, 0, foobarBuffer, execaSync);16test('stdin option can be a Uint8Array', () => testUint8Array(0, foobarUint8Array, execa));17test('stdio[*] option can be a Uint8Array', () => testUint8Array(3, foobarUint8Array, execa));18test('stdin option can be a Uint8Array - sync', () => testUint8Array(0, foobarUint8Array, execaSync));19test('stdin option can be a Buffer', () => testUint8Array(0, foobarBuffer, execa));20test('stdio[*] option can be a Buffer', () => testUint8Array(3, foobarBuffer, execa));21test('stdin option can be a Buffer - sync', () => testUint8Array(0, foobarBuffer, execaSync));2221const testNoUint8ArrayOutput = (t, fdNumber, stdioOption, execaMethod) => {22 t.throws(() => {23const testNoUint8ArrayOutput = (fdNumber, stdioOption, execaMethod) => {24 assertThrows(() => {25 execaMethod('empty.js', getStdio(fdNumber, stdioOption));26 }, {message: /cannot be a Uint8Array/});27};2827test('stdout option cannot be a Uint8Array', testNoUint8ArrayOutput, 1, foobarUint8Array, execa);28test('stderr option cannot be a Uint8Array', testNoUint8ArrayOutput, 2, foobarUint8Array, execa);29test('stdout option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, 1, foobarUint8Array, execaSync);30test('stderr option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, 2, foobarUint8Array, execaSync);31test('stdout option cannot be a Buffer', testNoUint8ArrayOutput, 1, foobarBuffer, execa);32test('stderr option cannot be a Buffer', testNoUint8ArrayOutput, 2, foobarBuffer, execa);33test('stdout option cannot be a Buffer - sync', testNoUint8ArrayOutput, 1, foobarBuffer, execaSync);34test('stderr option cannot be a Buffer - sync', testNoUint8ArrayOutput, 2, foobarBuffer, execaSync);29test('stdout option cannot be a Uint8Array', () => testNoUint8ArrayOutput(1, foobarUint8Array, execa));30test('stderr option cannot be a Uint8Array', () => testNoUint8ArrayOutput(2, foobarUint8Array, execa));31test('stdout option cannot be a Uint8Array - sync', () => testNoUint8ArrayOutput(1, foobarUint8Array, execaSync));32test('stderr option cannot be a Uint8Array - sync', () => testNoUint8ArrayOutput(2, foobarUint8Array, execaSync));33test('stdout option cannot be a Buffer', () => testNoUint8ArrayOutput(1, foobarBuffer, execa));34test('stderr option cannot be a Buffer', () => testNoUint8ArrayOutput(2, foobarBuffer, execa));35test('stdout option cannot be a Buffer - sync', () => testNoUint8ArrayOutput(1, foobarBuffer, execaSync));36test('stderr option cannot be a Buffer - sync', () => testNoUint8ArrayOutput(2, foobarBuffer, execaSync));
modified:test/stdio/web-stream.js+41 added-39 removed
1import assert from 'node:assert/strict';2import {Readable} from 'node:stream';3import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import test from 'node:test';5import {assertThrows, assertRejects} from '../helpers/assert.js';6import {execa, execaSync} from '../../index.js';7import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8import {getStdio} from '../helpers/stdio.js';910setFixtureDirectory();1110const testReadableStream = async (t, fdNumber) => {12const testReadableStream = async fdNumber => {13 const readableStream = Readable.toWeb(Readable.from('foobar'));14 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, readableStream));13 t.is(stdout, 'foobar');15 assert.equal(stdout, 'foobar');16};1716test('stdin can be a ReadableStream', testReadableStream, 0);17test('stdio[*] can be a ReadableStream', testReadableStream, 3);18test('stdin can be a ReadableStream', () => testReadableStream(0));19test('stdio[*] can be a ReadableStream', () => testReadableStream(3));2019const testWritableStream = async (t, fdNumber) => {21const testWritableStream = async fdNumber => {22 const result = [];23 const writableStream = new WritableStream({24 write(chunk) {25 result.push(chunk);26 },27 });28 await execa('noop-fd.js', [`${fdNumber}`, 'foobar'], getStdio(fdNumber, writableStream));27 t.is(result.join(''), 'foobar');29 assert.equal(result.join(''), 'foobar');30};3130test('stdout can be a WritableStream', testWritableStream, 1);31test('stderr can be a WritableStream', testWritableStream, 2);32test('stdio[*] can be a WritableStream', testWritableStream, 3);32test('stdout can be a WritableStream', () => testWritableStream(1));33test('stderr can be a WritableStream', () => testWritableStream(2));34test('stdio[*] can be a WritableStream', () => testWritableStream(3));3534const testWebStreamSync = (t, StreamClass, fdNumber, optionName) => {35 t.throws(() => {36const testWebStreamSync = (StreamClass, fdNumber, optionName) => {37 assertThrows(() => {38 execaSync('empty.js', getStdio(fdNumber, new StreamClass()));39 }, {message: `The \`${optionName}\` option cannot be a web stream with synchronous methods.`});40};4140test('stdin cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, 0, 'stdin');41test('stdio[*] cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, 3, 'stdio[3]');42test('stdout cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 1, 'stdout');43test('stderr cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 2, 'stderr');44test('stdio[*] cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 3, 'stdio[3]');42test('stdin cannot be a ReadableStream - sync', () => testWebStreamSync(ReadableStream, 0, 'stdin'));43test('stdio[*] cannot be a ReadableStream - sync', () => testWebStreamSync(ReadableStream, 3, 'stdio[3]'));44test('stdout cannot be a WritableStream - sync', () => testWebStreamSync(WritableStream, 1, 'stdout'));45test('stderr cannot be a WritableStream - sync', () => testWebStreamSync(WritableStream, 2, 'stderr'));46test('stdio[*] cannot be a WritableStream - sync', () => testWebStreamSync(WritableStream, 3, 'stdio[3]'));4746const testLongWritableStream = async (t, fdNumber) => {48const testLongWritableStream = async fdNumber => {49 let isResult = false;50 const writableStream = new WritableStream({51 async close() {52 await setImmediate();53 isResult = true;54 },55 });56 await execa('empty.js', getStdio(fdNumber, writableStream));55 t.true(isResult);57 assert.equal(isResult, true);58};5958test('stdout waits for WritableStream completion', testLongWritableStream, 1);59test('stderr waits for WritableStream completion', testLongWritableStream, 2);60test('stdio[*] waits for WritableStream completion', testLongWritableStream, 3);60test('stdout waits for WritableStream completion', () => testLongWritableStream(1));61test('stderr waits for WritableStream completion', () => testLongWritableStream(2));62test('stdio[*] waits for WritableStream completion', () => testLongWritableStream(3));6362const testWritableStreamError = async (t, fdNumber) => {64const testWritableStreamError = async fdNumber => {65 const cause = new Error('foobar');66 const writableStream = new WritableStream({67 start(controller) {68 controller.error(cause);69 },70 });69 const error = await t.throwsAsync(execa('noop.js', getStdio(fdNumber, writableStream)));70 t.is(error.cause, cause);71 const error = await assertRejects(execa('noop.js', getStdio(fdNumber, writableStream)));72 assert.equal(error.cause, cause);73};7473test('stdout option handles errors in WritableStream', testWritableStreamError, 1);74test('stderr option handles errors in WritableStream', testWritableStreamError, 2);75test('stdio[*] option handles errors in WritableStream', testWritableStreamError, 3);75test('stdout option handles errors in WritableStream', () => testWritableStreamError(1));76test('stderr option handles errors in WritableStream', () => testWritableStreamError(2));77test('stdio[*] option handles errors in WritableStream', () => testWritableStreamError(3));7877const testReadableStreamError = async (t, fdNumber) => {79const testReadableStreamError = async fdNumber => {80 const cause = new Error('foobar');81 const readableStream = new ReadableStream({82 start(controller) {83 controller.error(cause);84 },85 });84 const error = await t.throwsAsync(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, readableStream)));85 t.is(error.cause, cause);86 const error = await assertRejects(execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, readableStream)));87 assert.equal(error.cause, cause);88};8988test('stdin option handles errors in ReadableStream', testReadableStreamError, 0);89test('stdio[*] option handles errors in ReadableStream', testReadableStreamError, 3);90test('stdin option handles errors in ReadableStream', () => testReadableStreamError(0));91test('stdio[*] option handles errors in ReadableStream', () => testReadableStreamError(3));9291test('ReadableStream with stdin is canceled on subprocess exit', async t => {93test('ReadableStream with stdin is canceled on subprocess exit', async () => {94 let readableStream;95 const promise = new Promise(resolve => {96 readableStream = new ReadableStream({cancel: resolve});97 });96 await t.throwsAsync(execa('stdin.js', {stdin: readableStream, timeout: 1}), {message: /timed out/});98 await assertRejects(execa('stdin.js', {stdin: readableStream, timeout: 1}), {message: /timed out/});99 await promise;100});101102// A web stream can only be used once, but like Node.js streams, the same instance103// passed to multiple file descriptors should send its data to each of them.102const testSharedReadableStream = async (t, fixtureArguments, stdio) => {104const testSharedReadableStream = async (fixtureArguments, stdio) => {105 const readableStream = Readable.toWeb(Readable.from('foobar'));106 const {stdout} = await execa('stdin-fd.js', fixtureArguments, {stdio: stdio.map(value => value === 'shared' ? readableStream : value)});105 t.is(stdout, 'foobar');107 assert.equal(stdout, 'foobar');108};109108test('stdin can share a ReadableStream with stdio[*]', testSharedReadableStream, ['0'], ['shared', 'pipe', 'pipe', 'shared']);109test('stdio[*] can share a ReadableStream with another stdio[*]', testSharedReadableStream, ['3'], ['pipe', 'pipe', 'pipe', 'shared', 'shared']);110test('stdin can share a ReadableStream with stdio[*]', () => testSharedReadableStream(['0'], ['shared', 'pipe', 'pipe', 'shared']));111test('stdio[*] can share a ReadableStream with another stdio[*]', () => testSharedReadableStream(['3'], ['pipe', 'pipe', 'pipe', 'shared', 'shared']));
modified:test/stdio/web-transform.js+6 added-5 removed
1import assert from 'node:assert/strict';2import {promisify} from 'node:util';3import {gunzip} from 'node:zlib';3import test from 'ava';4import test from 'node:test';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {foobarString, foobarUtf16Uint8Array, foobarUint8Array} from '../helpers/input.js';89setFixtureDirectory();1010test('Can use CompressionStream()', async t => {11test('Can use CompressionStream()', async () => {12 const {stdout} = await execa('noop-fd.js', ['1', foobarString], {stdout: new CompressionStream('gzip'), encoding: 'buffer'});13 const decompressedStdout = await promisify(gunzip)(stdout);13 t.is(decompressedStdout.toString(), foobarString);14 assert.equal(decompressedStdout.toString(), foobarString);15});1616test('Can use TextDecoderStream()', async t => {17test('Can use TextDecoderStream()', async () => {18 const {stdout} = await execa('stdin.js', {19 input: foobarUtf16Uint8Array,20 stdout: new TextDecoderStream('utf-16le'),21 encoding: 'buffer',22 });22 t.deepEqual(stdout, foobarUint8Array);23 assert.deepEqual(stdout, foobarUint8Array);24});
modified:test/terminate/cancel.js+103 added-101 removed
1import assert from 'node:assert/strict';2import {once, getEventListeners} from 'node:events';2import test from 'ava';3import test from 'node:test';4import {assertThrows, assertRejects} from '../helpers/assert.js';5import {execa, execaSync} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {foobarString} from '../helpers/input.js';89setFixtureDirectory();109const testValidCancelSignal = (t, cancelSignal) => {10 t.throws(() => {11const testValidCancelSignal = cancelSignal => {12 assertThrows(() => {13 execa('empty.js', {cancelSignal});14 }, {message: /must be an AbortSignal/});15};1615test('cancelSignal option cannot be AbortController', testValidCancelSignal, new AbortController());16test('cancelSignal option cannot be {}', testValidCancelSignal, {});17test('cancelSignal option cannot be null', testValidCancelSignal, null);18test('cancelSignal option cannot be a symbol', testValidCancelSignal, Symbol('test'));17test('cancelSignal option cannot be AbortController', () => testValidCancelSignal(new AbortController()));18test('cancelSignal option cannot be {}', () => testValidCancelSignal({}));19test('cancelSignal option cannot be null', () => testValidCancelSignal(null));20test('cancelSignal option cannot be a symbol', () => testValidCancelSignal(Symbol('test')));2120test('result.isCanceled is false when abort isn\'t called (success)', async t => {22test('result.isCanceled is false when abort isn\'t called (success)', async () => {23 const {isCanceled, isGracefullyCanceled} = await execa('noop.js');22 t.false(isCanceled);23 t.false(isGracefullyCanceled);24 assert.equal(isCanceled, false);25 assert.equal(isGracefullyCanceled, false);26});2726test('result.isCanceled is false when abort isn\'t called (failure)', async t => {27 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(execa('fail.js'));28 t.false(isCanceled);29 t.false(isGracefullyCanceled);28test('result.isCanceled is false when abort isn\'t called (failure)', async () => {29 const {isCanceled, isGracefullyCanceled} = await assertRejects(execa('fail.js'));30 assert.equal(isCanceled, false);31 assert.equal(isGracefullyCanceled, false);32});3332test('result.isCanceled is false when abort isn\'t called in sync mode (success)', t => {34test('result.isCanceled is false when abort isn\'t called in sync mode (success)', () => {35 const {isCanceled, isGracefullyCanceled} = execaSync('noop.js');34 t.false(isCanceled);35 t.false(isGracefullyCanceled);36 assert.equal(isCanceled, false);37 assert.equal(isGracefullyCanceled, false);38});3938test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', t => {39 const {isCanceled, isGracefullyCanceled} = t.throws(() => {40test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', () => {41 const {isCanceled, isGracefullyCanceled} = assertThrows(() => {42 execaSync('fail.js');43 });42 t.false(isCanceled);43 t.false(isGracefullyCanceled);44 assert.equal(isCanceled, false);45 assert.equal(isGracefullyCanceled, false);46});4746const testCancelSuccess = async (t, options) => {48const testCancelSuccess = async options => {49 const abortController = new AbortController();50 const subprocess = execa('noop.js', {cancelSignal: abortController.signal, ...options});51 abortController.abort();50 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);51 t.true(isCanceled);52 t.false(isGracefullyCanceled);52 const {isCanceled, isGracefullyCanceled} = await assertRejects(subprocess);53 assert.equal(isCanceled, true);54 assert.equal(isGracefullyCanceled, false);55};5655test('error.isCanceled is true when abort is used', testCancelSuccess, {});56test('gracefulCancel can be false with cancelSignal', testCancelSuccess, {gracefulCancel: false});57test('ipc can be false with cancelSignal', testCancelSuccess, {ipc: false});58test('serialization can be "json" with cancelSignal', testCancelSuccess, {ipc: true, serialization: 'json'});57test('error.isCanceled is true when abort is used', () => testCancelSuccess({}));58test('gracefulCancel can be false with cancelSignal', () => testCancelSuccess({gracefulCancel: false}));59test('ipc can be false with cancelSignal', () => testCancelSuccess({ipc: false}));60test('serialization can be "json" with cancelSignal', () => testCancelSuccess({ipc: true, serialization: 'json'}));6160test('error.isCanceled is false when kill method is used', async t => {62test('error.isCanceled is false when kill method is used', async () => {63 const abortController = new AbortController();64 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});65 subprocess.kill();64 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);65 t.false(isCanceled);66 t.false(isGracefullyCanceled);66 const {isCanceled, isGracefullyCanceled} = await assertRejects(subprocess);67 assert.equal(isCanceled, false);68 assert.equal(isGracefullyCanceled, false);69});7069test('calling abort is considered a signal termination', async t => {71test('calling abort is considered a signal termination', async () => {72 const abortController = new AbortController();73 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});74 await once(subprocess.nodeChildProcess, 'spawn');75 abortController.abort();74 const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await t.throwsAsync(subprocess);75 t.true(isCanceled);76 t.false(isGracefullyCanceled);77 t.true(isTerminated);78 t.is(signal, 'SIGTERM');76 const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await assertRejects(subprocess);77 assert.equal(isCanceled, true);78 assert.equal(isGracefullyCanceled, false);79 assert.equal(isTerminated, true);80 assert.equal(signal, 'SIGTERM');81});8281test('cancelSignal can already be aborted', async t => {83test('cancelSignal can already be aborted', async () => {84 const cancelSignal = AbortSignal.abort();83 const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await t.throwsAsync(execa('forever.js', {cancelSignal}));84 t.true(isCanceled);85 t.false(isGracefullyCanceled);86 t.true(isTerminated);87 t.is(signal, 'SIGTERM');88 t.deepEqual(getEventListeners(cancelSignal, 'abort'), []);85 const {isCanceled, isGracefullyCanceled, isTerminated, signal} = await assertRejects(execa('forever.js', {cancelSignal}));86 assert.equal(isCanceled, true);87 assert.equal(isGracefullyCanceled, false);88 assert.equal(isTerminated, true);89 assert.equal(signal, 'SIGTERM');90 assert.deepEqual(getEventListeners(cancelSignal, 'abort'), []);91});9291test('calling abort does not emit the "error" event', async t => {93test('calling abort does not emit the "error" event', async () => {94 const abortController = new AbortController();95 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});96 let error;97 subprocess.nodeChildProcess.once('error', errorArgument => {98 error = errorArgument;99 });100 abortController.abort();99 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);100 t.true(isCanceled);101 t.false(isGracefullyCanceled);102 t.is(error, undefined);101 const {isCanceled, isGracefullyCanceled} = await assertRejects(subprocess);102 assert.equal(isCanceled, true);103 assert.equal(isGracefullyCanceled, false);104 assert.equal(error, undefined);105});106105test('calling abort cleans up listeners on cancelSignal, called', async t => {107test('calling abort cleans up listeners on cancelSignal, called', async () => {108 const abortController = new AbortController();109 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});108 t.is(getEventListeners(abortController.signal, 'abort').length, 1);110 assert.equal(getEventListeners(abortController.signal, 'abort').length, 1);111 abortController.abort();110 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);111 t.true(isCanceled);112 t.false(isGracefullyCanceled);113 t.is(getEventListeners(abortController.signal, 'abort').length, 0);112 const {isCanceled, isGracefullyCanceled} = await assertRejects(subprocess);113 assert.equal(isCanceled, true);114 assert.equal(isGracefullyCanceled, false);115 assert.equal(getEventListeners(abortController.signal, 'abort').length, 0);116});117116test('calling abort cleans up listeners on cancelSignal, not called', async t => {118test('calling abort cleans up listeners on cancelSignal, not called', async () => {119 const abortController = new AbortController();120 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});119 t.is(getEventListeners(abortController.signal, 'abort').length, 1);121 assert.equal(getEventListeners(abortController.signal, 'abort').length, 1);122 await subprocess;121 t.is(getEventListeners(abortController.signal, 'abort').length, 0);123 assert.equal(getEventListeners(abortController.signal, 'abort').length, 0);124});125124test('calling abort cleans up listeners on cancelSignal, already aborted', async t => {126test('calling abort cleans up listeners on cancelSignal, already aborted', async () => {127 const cancelSignal = AbortSignal.abort();128 const subprocess = execa('noop.js', {cancelSignal});127 t.is(getEventListeners(cancelSignal, 'abort').length, 0);128 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);129 t.true(isCanceled);130 t.false(isGracefullyCanceled);131 t.is(getEventListeners(cancelSignal, 'abort').length, 0);129 assert.equal(getEventListeners(cancelSignal, 'abort').length, 0);130 const {isCanceled, isGracefullyCanceled} = await assertRejects(subprocess);131 assert.equal(isCanceled, true);132 assert.equal(isGracefullyCanceled, false);133 assert.equal(getEventListeners(cancelSignal, 'abort').length, 0);134});135134test('calling abort throws an error with message "Command was canceled"', async t => {136test('calling abort throws an error with message "Command was canceled"', async () => {137 const abortController = new AbortController();138 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});139 abortController.abort();138 await t.throwsAsync(subprocess, {message: /Command was canceled/});140 await assertRejects(subprocess, {message: /Command was canceled/});141});142141test('calling abort with no argument keeps error properties', async t => {143test('calling abort with no argument keeps error properties', async () => {144 const abortController = new AbortController();145 const subprocess = execa('empty.js', {cancelSignal: abortController.signal});146 abortController.abort();145 const {cause, originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);146 t.is(cause.message, 'This operation was aborted');147 t.is(cause.name, 'AbortError');148 t.is(originalMessage, 'This operation was aborted');149 t.is(shortMessage, 'Command was canceled: empty.js\nThis operation was aborted');150 t.is(message, 'Command was canceled: empty.js\nThis operation was aborted');147 const {cause, originalMessage, shortMessage, message} = await assertRejects(subprocess);148 assert.equal(cause.message, 'This operation was aborted');149 assert.equal(cause.name, 'AbortError');150 assert.equal(originalMessage, 'This operation was aborted');151 assert.equal(shortMessage, 'Command was canceled: empty.js\nThis operation was aborted');152 assert.equal(message, 'Command was canceled: empty.js\nThis operation was aborted');153});154153test('calling abort with an error instance keeps error properties', async t => {155test('calling abort with an error instance keeps error properties', async () => {156 const abortController = new AbortController();157 const subprocess = execa('empty.js', {cancelSignal: abortController.signal});158 const error = new Error(foobarString);159 error.code = foobarString;160 abortController.abort(error);159 const {cause, originalMessage, shortMessage, message, code} = await t.throwsAsync(subprocess);160 t.is(cause, error);161 t.is(originalMessage, foobarString);162 t.is(shortMessage, `Command was canceled: empty.js\n${foobarString}`);163 t.is(message, `Command was canceled: empty.js\n${foobarString}`);164 t.is(code, foobarString);161 const {cause, originalMessage, shortMessage, message, code} = await assertRejects(subprocess);162 assert.equal(cause, error);163 assert.equal(originalMessage, foobarString);164 assert.equal(shortMessage, `Command was canceled: empty.js\n${foobarString}`);165 assert.equal(message, `Command was canceled: empty.js\n${foobarString}`);166 assert.equal(code, foobarString);167});168167test('calling abort with null keeps error properties', async t => {169test('calling abort with null keeps error properties', async () => {170 const abortController = new AbortController();171 const subprocess = execa('empty.js', {cancelSignal: abortController.signal});172 abortController.abort(null);171 const {cause, originalMessage, shortMessage, message} = await t.throwsAsync(subprocess);172 t.is(cause, null);173 t.is(originalMessage, 'null');174 t.is(shortMessage, 'Command was canceled: empty.js\nnull');175 t.is(message, 'Command was canceled: empty.js\nnull');173 const {cause, originalMessage, shortMessage, message} = await assertRejects(subprocess);174 assert.equal(cause, null);175 assert.equal(originalMessage, 'null');176 assert.equal(shortMessage, 'Command was canceled: empty.js\nnull');177 assert.equal(message, 'Command was canceled: empty.js\nnull');178});179178test('calling abort twice should show the same behaviour as calling it once', async t => {180test('calling abort twice should show the same behaviour as calling it once', async () => {181 const abortController = new AbortController();182 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});183 abortController.abort();184 abortController.abort();183 const {isCanceled, isGracefullyCanceled} = await t.throwsAsync(subprocess);184 t.true(isCanceled);185 t.false(isGracefullyCanceled);185 const {isCanceled, isGracefullyCanceled} = await assertRejects(subprocess);186 assert.equal(isCanceled, true);187 assert.equal(isGracefullyCanceled, false);188});189188test('calling abort on a successfully completed subprocess does not make result.isCanceled true', async t => {190test('calling abort on a successfully completed subprocess does not make result.isCanceled true', async () => {191 const abortController = new AbortController();192 const subprocess = execa('noop.js', {cancelSignal: abortController.signal});193 const {isCanceled, isGracefullyCanceled} = await subprocess;194 abortController.abort();193 t.false(isCanceled);194 t.false(isGracefullyCanceled);195 assert.equal(isCanceled, false);196 assert.equal(isGracefullyCanceled, false);197});198197test('Throws when using the former "signal" option name', t => {199test('Throws when using the former "signal" option name', () => {200 const abortController = new AbortController();199 t.throws(() => {201 assertThrows(() => {202 execa('empty.js', {signal: abortController.signal});203 }, {message: /renamed to "cancelSignal"/});204});205204test('Throws when using the former "signal" option name, sync', t => {206test('Throws when using the former "signal" option name, sync', () => {207 const abortController = new AbortController();206 t.throws(() => {208 assertThrows(() => {209 execaSync('empty.js', {signal: abortController.signal});210 }, {message: /renamed to "cancelSignal"/});211});212211test('Cannot use cancelSignal, sync', t => {213test('Cannot use cancelSignal, sync', () => {214 const abortController = new AbortController();213 t.throws(() => {215 assertThrows(() => {216 execaSync('empty.js', {cancelSignal: abortController.signal});217 }, {message: /The "cancelSignal" option cannot be used/});218});
modified:test/terminate/cleanup.js+40 added-38 removed
1import assert from 'node:assert/strict';2import process from 'node:process';3import {setTimeout} from 'node:timers/promises';3import test from 'ava';4import test from 'node:test';5import isRunning from 'is-running';6import {assertThrows, assertRejects} from '../helpers/assert.js';7import {execa, execaSync} from '../../index.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9import {nestedSubprocess} from '../helpers/nested.js';10import {foobarString} from '../helpers/input.js';
2 unmodified lines
1314const isWindows = process.platform === 'win32';1516// When subprocess exits before current process15const spawnAndExit = async (t, worker, cleanup, detached) => {17const spawnAndExit = async (worker, cleanup, detached) => {18 const {nestedResult: {stdout}} = await nestedSubprocess('noop-fd.js', ['1', foobarString], {worker, cleanup, detached});17 t.is(stdout, foobarString);19 assert.equal(stdout, foobarString);20};2120test('spawnAndExit', spawnAndExit, false, false, false);21test('spawnAndExit cleanup', spawnAndExit, false, true, false);22test('spawnAndExit detached', spawnAndExit, false, false, true);23test('spawnAndExit cleanup detached', spawnAndExit, false, true, true);24test('spawnAndExit, worker', spawnAndExit, true, false, false);25test('spawnAndExit cleanup, worker', spawnAndExit, true, true, false);26test('spawnAndExit detached, worker', spawnAndExit, true, false, true);27test('spawnAndExit cleanup detached, worker', spawnAndExit, true, true, true);22test('spawnAndExit', () => spawnAndExit(false, false, false));23test('spawnAndExit cleanup', () => spawnAndExit(false, true, false));24test('spawnAndExit detached', () => spawnAndExit(false, false, true));25test('spawnAndExit cleanup detached', () => spawnAndExit(false, true, true));26test('spawnAndExit, worker', () => spawnAndExit(true, false, false));27test('spawnAndExit cleanup, worker', () => spawnAndExit(true, true, false));28test('spawnAndExit detached, worker', () => spawnAndExit(true, false, true));29test('spawnAndExit cleanup detached, worker', () => spawnAndExit(true, true, true));3031// When current process exits before subprocess30const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {32const spawnAndKill = async ([signal, cleanup, detached, isKilled]) => {33 const subprocess = execa('ipc-send-pid.js', [cleanup, detached], {stdio: 'ignore', ipc: true});3435 const pid = await subprocess.getOneMessage();34 t.true(Number.isInteger(pid));35 t.true(isRunning(pid));36 assert.ok(Number.isInteger(pid));37 assert.ok(isRunning(pid));3839 process.kill(subprocess.pid, signal);4039 await t.throwsAsync(subprocess);40 t.false(isRunning(subprocess.pid));41 await assertRejects(subprocess);42 assert.ok(!isRunning(subprocess.pid));4344 if (isKilled) {45 await Promise.race([46 setTimeout(1e4, undefined, {ref: false}),47 pollForSubprocessExit(pid),48 ]);47 t.is(isRunning(pid), false);49 assert.equal(isRunning(pid), false);50 } else {49 t.is(isRunning(pid), true);51 assert.equal(isRunning(pid), true);52 process.kill(pid, 'SIGKILL');53 }54};55
9 unmodified lines
65// if `options.detached: true`66// - on Linux subprocesses are never killed regardless of `options.detached`67// With `options.cleanup`, subprocesses are always killed68// - `options.cleanup` with SIGKILL is a noop, since it cannot be handled67test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);68test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);69test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);70test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);71test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);72test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);73test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);74test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);69test('spawnAndKill SIGTERM', () => spawnAndKill(['SIGTERM', false, false, isWindows]));70test('spawnAndKill SIGKILL', () => spawnAndKill(['SIGKILL', false, false, isWindows]));71test('spawnAndKill cleanup SIGTERM', () => spawnAndKill(['SIGTERM', true, false, true]));72test('spawnAndKill cleanup SIGKILL', () => spawnAndKill(['SIGKILL', true, false, isWindows]));73test('spawnAndKill detached SIGTERM', () => spawnAndKill(['SIGTERM', false, true, false]));74test('spawnAndKill detached SIGKILL', () => spawnAndKill(['SIGKILL', false, true, false]));75test('spawnAndKill cleanup detached SIGTERM', () => spawnAndKill(['SIGTERM', true, true, false]));76test('spawnAndKill cleanup detached SIGKILL', () => spawnAndKill(['SIGKILL', true, true, false]));7778if (!isWindows) {77 test('spawnAndKill cleanup uses killSignal', async t => {79 test('spawnAndKill cleanup uses killSignal', async () => {80 const subprocess = execa('ipc-send-pid.js', ['true', 'false', 'no-killable'], {stdio: 'ignore', ipc: true});8182 const pid = await subprocess.getOneMessage();81 t.true(Number.isInteger(pid));82 t.true(isRunning(pid));83 assert.ok(Number.isInteger(pid));84 assert.ok(isRunning(pid));8586 process.kill(subprocess.pid, 'SIGTERM');8786 await t.throwsAsync(subprocess);88 await assertRejects(subprocess);89 await Promise.race([90 setTimeout(1e4, undefined, {ref: false}),91 pollForSubprocessExit(pid),92 ]);91 t.false(isRunning(pid));93 assert.ok(!isRunning(pid));94 });95}9697// See #12896test('removes exit handler on exit', async t => {98test('removes exit handler on exit', async () => {99 // @todo this relies on `signal-exit` internals100 const exitListeners = globalThis[Symbol.for('signal-exit emitter')].listeners.exit;101102 const subprocess = execa('noop.js');103 const listener = exitListeners.at(-1);104105 await subprocess;104 t.false(exitListeners.includes(listener));106 assert.ok(!exitListeners.includes(listener));107});108107test('detach subprocess', async t => {109test('detach subprocess', async () => {110 const {stdout} = await execa('detach.js');111 const pid = Number(stdout);110 t.true(Number.isInteger(pid));111 t.true(isRunning(pid));112 assert.ok(Number.isInteger(pid));113 assert.ok(isRunning(pid));114115 process.kill(pid, 'SIGKILL');116});117116test('Cannot use "detached" option, sync', t => {117 t.throws(() => {118test('Cannot use "detached" option, sync', () => {119 assertThrows(() => {120 execaSync('empty.js', {detached: true});121 }, {message: /The "detached: true" option cannot be used/});122});
modified:test/terminate/graceful.js+100 added-98 removed
1import assert from 'node:assert/strict';2import {setTimeout} from 'node:timers/promises';2import test from 'ava';3import test from 'node:test';4import {assertThrows, assertRejects} from '../helpers/assert.js';5import {execa} from '../../index.js';6import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7import {foobarString} from '../helpers/input.js';8import {mockSendIoError} from '../helpers/ipc.js';910setFixtureDirectory();1110test('cancelSignal cannot be undefined with gracefulCancel', t => {11 t.throws(() => {12test('cancelSignal cannot be undefined with gracefulCancel', () => {13 assertThrows(() => {14 execa('empty.js', {gracefulCancel: true});15 }, {message: /The `cancelSignal` option must be defined/});16});1716test('ipc cannot be false with gracefulCancel', t => {17 t.throws(() => {18test('ipc cannot be false with gracefulCancel', () => {19 assertThrows(() => {20 execa('empty.js', {gracefulCancel: true, cancelSignal: AbortSignal.abort(), ipc: false});21 }, {message: /The `ipc` option cannot be false/});22});2322test('serialization cannot be "json" with gracefulCancel', t => {23 t.throws(() => {24test('serialization cannot be "json" with gracefulCancel', () => {25 assertThrows(() => {26 execa('empty.js', {gracefulCancel: true, cancelSignal: AbortSignal.abort(), serialization: 'json'});27 }, {message: /The `serialization` option cannot be 'json'/});28});2928test('Current process can send a message right away', async t => {30test('Current process can send a message right away', async () => {31 const controller = new AbortController();32 const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true});33 await subprocess.sendMessage(foobarString);34 const {ipcOutput} = await subprocess;33 t.deepEqual(ipcOutput, [foobarString]);35 assert.deepEqual(ipcOutput, [foobarString]);36});3736test('Current process can receive a message right away', async t => {38test('Current process can receive a message right away', async () => {39 const controller = new AbortController();40 const subprocess = execa('ipc-send.js', {cancelSignal: controller.signal, gracefulCancel: true});39 t.is(await subprocess.getOneMessage(), foobarString);41 assert.equal(await subprocess.getOneMessage(), foobarString);42 const {ipcOutput} = await subprocess;41 t.deepEqual(ipcOutput, [foobarString]);43 assert.deepEqual(ipcOutput, [foobarString]);44});4544test('Does not disconnect during I/O errors when sending the abort reason', async t => {46test('Does not disconnect during I/O errors when sending the abort reason', async () => {47 const controller = new AbortController();48 const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});49 const error = mockSendIoError(subprocess);50 controller.abort(foobarString);51 await setTimeout(0);50 t.true(subprocess.nodeChildProcess.connected);52 assert.equal(subprocess.nodeChildProcess.connected, true);53 subprocess.kill();52 const {isCanceled, isGracefullyCanceled, signal, ipcOutput, cause} = await t.throwsAsync(subprocess);53 t.false(isCanceled);54 t.false(isGracefullyCanceled);55 t.is(signal, 'SIGTERM');56 t.deepEqual(ipcOutput, []);57 t.is(cause, error);54 const {isCanceled, isGracefullyCanceled, signal, ipcOutput, cause} = await assertRejects(subprocess);55 assert.equal(isCanceled, false);56 assert.equal(isGracefullyCanceled, false);57 assert.equal(signal, 'SIGTERM');58 assert.deepEqual(ipcOutput, []);59 assert.equal(cause, error);60});6162class AbortError extends Error {63 name = 'AbortError';64}6564test('Abort reason is sent to the subprocess', async t => {66test('Abort reason is sent to the subprocess', async () => {67 const controller = new AbortController();68 const subprocess = execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});69 const error = new AbortError(foobarString);70 controller.abort(error);69 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);70 t.true(isCanceled);71 t.true(isGracefullyCanceled);72 t.false(isTerminated);73 t.is(exitCode, 0);74 t.is(cause, error);75 t.is(ipcOutput[0].message, error.message);76 t.is(ipcOutput[0].stack, error.stack);77 t.is(ipcOutput[0].name, 'Error');71 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await assertRejects(subprocess);72 assert.equal(isCanceled, true);73 assert.equal(isGracefullyCanceled, true);74 assert.equal(isTerminated, false);75 assert.equal(exitCode, 0);76 assert.equal(cause, error);77 assert.equal(ipcOutput[0].message, error.message);78 assert.equal(ipcOutput[0].stack, error.stack);79 assert.equal(ipcOutput[0].name, 'Error');80});8180test('Abort default reason is sent to the subprocess', async t => {82test('Abort default reason is sent to the subprocess', async () => {83 const controller = new AbortController();84 const subprocess = execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});85 controller.abort();84 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);85 t.true(isCanceled);86 t.true(isGracefullyCanceled);87 t.false(isTerminated);88 t.is(exitCode, 0);86 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await assertRejects(subprocess);87 assert.equal(isCanceled, true);88 assert.equal(isGracefullyCanceled, true);89 assert.equal(isTerminated, false);90 assert.equal(exitCode, 0);91 const {reason} = controller.signal;90 t.is(cause.stack, reason.stack);91 t.is(ipcOutput[0].message, reason.message);92 t.is(ipcOutput[0].stack, reason.stack);92 assert.equal(cause.stack, reason.stack);93 assert.equal(ipcOutput[0].message, reason.message);94 assert.equal(ipcOutput[0].stack, reason.stack);95});9695test('Fail when sending non-serializable abort reason', async t => {97test('Fail when sending non-serializable abort reason', async () => {98 const controller = new AbortController();99 const subprocess = execa('ipc-echo.js', {cancelSignal: controller.signal, gracefulCancel: true, forceKillAfterDelay: false});100 controller.abort(() => {});101 await setTimeout(0);100 t.true(subprocess.nodeChildProcess.connected);102 assert.equal(subprocess.nodeChildProcess.connected, true);103 await subprocess.sendMessage(foobarString);102 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await t.throwsAsync(subprocess);103 t.false(isCanceled);104 t.false(isGracefullyCanceled);105 t.false(isTerminated);106 t.is(exitCode, 0);107 t.deepEqual(ipcOutput, [foobarString]);108 t.is(cause.message, '`cancelSignal`\'s `controller.abort()`\'s argument type is invalid: the message cannot be serialized: () => {}.');109 t.is(cause.cause.message, '() => {} could not be cloned.');104 const {isCanceled, isGracefullyCanceled, isTerminated, exitCode, cause, ipcOutput} = await assertRejects(subprocess);105 assert.equal(isCanceled, false);106 assert.equal(isGracefullyCanceled, false);107 assert.equal(isTerminated, false);108 assert.equal(exitCode, 0);109 assert.deepEqual(ipcOutput, [foobarString]);110 assert.equal(cause.message, '`cancelSignal`\'s `controller.abort()`\'s argument type is invalid: the message cannot be serialized: () => {}.');111 assert.equal(cause.cause.message, '() => {} could not be cloned.');112});113112test('timeout does not use graceful cancelSignal', async t => {114test('timeout does not use graceful cancelSignal', async () => {115 const controller = new AbortController();114 const {timedOut, isCanceled, isGracefullyCanceled, isTerminated, signal, exitCode, shortMessage, ipcOutput} = await t.throwsAsync(execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, timeout: 1}));115 t.true(timedOut);116 t.false(isCanceled);117 t.false(isGracefullyCanceled);118 t.true(isTerminated);119 t.is(signal, 'SIGTERM');120 t.is(exitCode, undefined);121 t.is(shortMessage, 'Command timed out after 1 milliseconds: graceful-send.js');122 t.deepEqual(ipcOutput, []);116 const {timedOut, isCanceled, isGracefullyCanceled, isTerminated, signal, exitCode, shortMessage, ipcOutput} = await assertRejects(execa('graceful-send.js', {cancelSignal: controller.signal, gracefulCancel: true, timeout: 1}));117 assert.equal(timedOut, true);118 assert.equal(isCanceled, false);119 assert.equal(isGracefullyCanceled, false);120 assert.equal(isTerminated, true);121 assert.equal(signal, 'SIGTERM');122 assert.equal(exitCode, undefined);123 assert.equal(shortMessage, 'Command timed out after 1 milliseconds: graceful-send.js');124 assert.deepEqual(ipcOutput, []);125});126125test('error on graceful cancelSignal on non-0 exit code', async t => {126 const {isCanceled, isGracefullyCanceled, isTerminated, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(execa('wait-fail.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: false}));127 t.true(isCanceled);128 t.true(isGracefullyCanceled);129 t.false(isTerminated);130 t.false(isForcefullyTerminated);131 t.is(exitCode, 2);132 t.is(shortMessage, 'Command was gracefully canceled with exit code 2: wait-fail.js');127test('error on graceful cancelSignal on non-0 exit code', async () => {128 const {isCanceled, isGracefullyCanceled, isTerminated, isForcefullyTerminated, exitCode, shortMessage} = await assertRejects(execa('wait-fail.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: false}));129 assert.equal(isCanceled, true);130 assert.equal(isGracefullyCanceled, true);131 assert.equal(isTerminated, false);132 assert.equal(isForcefullyTerminated, false);133 assert.equal(exitCode, 2);134 assert.equal(shortMessage, 'Command was gracefully canceled with exit code 2: wait-fail.js');135});136135test('error on graceful cancelSignal on forceful termination', async t => {136 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(execa('forever.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: 1}));137 t.true(isCanceled);138 t.true(isGracefullyCanceled);139 t.true(isTerminated);140 t.is(signal, 'SIGKILL');141 t.true(isForcefullyTerminated);142 t.is(exitCode, undefined);143 t.is(shortMessage, 'Command was gracefully canceled and was forcefully terminated after 1 milliseconds: forever.js');137test('error on graceful cancelSignal on forceful termination', async () => {138 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await assertRejects(execa('forever.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: 1}));139 assert.equal(isCanceled, true);140 assert.equal(isGracefullyCanceled, true);141 assert.equal(isTerminated, true);142 assert.equal(signal, 'SIGKILL');143 assert.equal(isForcefullyTerminated, true);144 assert.equal(exitCode, undefined);145 assert.equal(shortMessage, 'Command was gracefully canceled and was forcefully terminated after 1 milliseconds: forever.js');146});147146test('error on graceful cancelSignal on non-forceful termination', async t => {148test('error on graceful cancelSignal on non-forceful termination', async () => {149 const subprocess = execa('ipc-send-get.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: 1e6});148 t.is(await subprocess.getOneMessage(), foobarString);150 assert.equal(await subprocess.getOneMessage(), foobarString);151 subprocess.kill();150 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(subprocess);151 t.true(isCanceled);152 t.true(isGracefullyCanceled);153 t.true(isTerminated);154 t.is(signal, 'SIGTERM');155 t.false(isForcefullyTerminated);156 t.is(exitCode, undefined);157 t.is(shortMessage, 'Command was gracefully canceled with SIGTERM (Termination): ipc-send-get.js');152 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await assertRejects(subprocess);153 assert.equal(isCanceled, true);154 assert.equal(isGracefullyCanceled, true);155 assert.equal(isTerminated, true);156 assert.equal(signal, 'SIGTERM');157 assert.equal(isForcefullyTerminated, false);158 assert.equal(exitCode, undefined);159 assert.equal(shortMessage, 'Command was gracefully canceled with SIGTERM (Termination): ipc-send-get.js');160});161160test('`forceKillAfterDelay: false` with the "cancelSignal" option when graceful', async t => {162test('`forceKillAfterDelay: false` with the "cancelSignal" option when graceful', async () => {163 const subprocess = execa('forever.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true, forceKillAfterDelay: false});164 await setTimeout(6e3);165 subprocess.kill('SIGKILL');164 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await t.throwsAsync(subprocess);165 t.true(isCanceled);166 t.true(isGracefullyCanceled);167 t.true(isTerminated);168 t.is(signal, 'SIGKILL');169 t.false(isForcefullyTerminated);170 t.is(exitCode, undefined);171 t.is(shortMessage, 'Command was gracefully canceled with SIGKILL (Forced termination): forever.js');166 const {isCanceled, isGracefullyCanceled, isTerminated, signal, isForcefullyTerminated, exitCode, shortMessage} = await assertRejects(subprocess);167 assert.equal(isCanceled, true);168 assert.equal(isGracefullyCanceled, true);169 assert.equal(isTerminated, true);170 assert.equal(signal, 'SIGKILL');171 assert.equal(isForcefullyTerminated, false);172 assert.equal(exitCode, undefined);173 assert.equal(shortMessage, 'Command was gracefully canceled with SIGKILL (Forced termination): forever.js');174});175174test('subprocess.getCancelSignal() is not defined', async t => {176test('subprocess.getCancelSignal() is not defined', async () => {177 const subprocess = execa('empty.js', {cancelSignal: AbortSignal.abort(''), gracefulCancel: true});176 t.is(subprocess.getCancelSignal, undefined);177 await t.throwsAsync(subprocess);178 assert.equal(subprocess.getCancelSignal, undefined);179 await assertRejects(subprocess);180});
modified:test/terminate/kill-descendants.js+89 added-110 removed
1import assert from 'node:assert/strict';2import childProcess from 'node:child_process';3import {syncBuiltinESMExports} from 'node:module';4import path from 'node:path/win32';5import process from 'node:process';6import {setTimeout} from 'node:timers/promises';6import test from 'ava';7import test from 'node:test';8import isRunning from 'is-running';9import {assertThrows, assertRejects} from '../helpers/assert.js';10import {execa, execaSync} from '../../index.js';11import {getTaskkillFile} from '../../lib/terminate/kill-descendants.js';12import {setFixtureDirectory} from '../helpers/fixtures-directory.js';13
19 unmodified lines
33 const descendantPid = await subprocess.getOneMessage();34 return {subprocess, descendantPid};35};3635test('killDescendants terminates descendant processes', async t => {37test('killDescendants terminates descendant processes', async () => {38 const {subprocess, descendantPid} = await spawnDescendant(true);37 t.true(isRunning(descendantPid));39 assert.ok(isRunning(descendantPid));4041 subprocess.kill();40 await t.throwsAsync(subprocess);41 t.false(isRunning(subprocess.pid));42 await assertRejects(subprocess);43 assert.ok(!isRunning(subprocess.pid));4445 await Promise.race([46 setTimeout(1e4, undefined, {ref: false}),47 pollForSubprocessExit(descendantPid),48 ]);47 t.false(isRunning(descendantPid));49 assert.ok(!isRunning(descendantPid));50});5150test('killDescendants also terminates descendant processes when the subprocess times out', async t => {52test('killDescendants also terminates descendant processes when the subprocess times out', async () => {53 const {subprocess, descendantPid} = await spawnDescendant(true, {timeout: 1000});52 t.true(isRunning(descendantPid));54 assert.ok(isRunning(descendantPid));5554 const {timedOut} = await t.throwsAsync(subprocess);55 t.true(timedOut);56 const {timedOut} = await assertRejects(subprocess);57 assert.equal(timedOut, true);5859 await Promise.race([60 setTimeout(1e4, undefined, {ref: false}),61 pollForSubprocessExit(descendantPid),62 ]);61 t.false(isRunning(descendantPid));63 assert.ok(!isRunning(descendantPid));64});6566// On Windows, terminating the direct subprocess already terminates its descendants, so this67// only asserts the default Unix behavior of leaving descendants running.68if (!isWindows) {67 test('descendant processes are not terminated without killDescendants', async t => {69 test('descendant processes are not terminated without killDescendants', async () => {70 const {subprocess, descendantPid} = await spawnDescendant(false);69 t.true(isRunning(descendantPid));71 assert.ok(isRunning(descendantPid));7273 subprocess.kill();72 await t.throwsAsync(subprocess);73 t.false(isRunning(subprocess.pid));74 await assertRejects(subprocess);75 assert.ok(!isRunning(subprocess.pid));7675 t.true(isRunning(descendantPid));77 assert.ok(isRunning(descendantPid));78 process.kill(descendantPid, 'SIGKILL');79 });8079 test('timeout does not terminate descendants without killDescendants', async t => {81 test('timeout does not terminate descendants without killDescendants', async () => {82 const {subprocess, descendantPid} = await spawnDescendant(false, {timeout: 1000});81 t.true(isRunning(descendantPid));83 assert.ok(isRunning(descendantPid));8483 const {timedOut} = await t.throwsAsync(subprocess);84 t.true(timedOut);85 t.true(isRunning(descendantPid));85 const {timedOut} = await assertRejects(subprocess);86 assert.equal(timedOut, true);87 assert.ok(isRunning(descendantPid));88 process.kill(descendantPid, 'SIGKILL');89 });90}91
1 unmodified line
93The `forceKillAfterDelay` escalation happens after the subprocess exited, since that is when its termination has been noticed.94A descendant which ignores `SIGTERM` is still running then, so the escalation must still reach it.95Otherwise, since that descendant keeps the subprocess' `stdout` open, awaiting the subprocess would never settle.96*/95test('killDescendants escalates to descendants which outlive the subprocess', async t => {97test('killDescendants escalates to descendants which outlive the subprocess', async () => {98 const subprocess = execa('ipc-send-pid-stubborn.js', {99 ipc: true,100 killDescendants: true,101 forceKillAfterDelay: 1000,102 });103 const descendantPid = await subprocess.getOneMessage();102 t.true(isRunning(descendantPid));104 assert.ok(isRunning(descendantPid));105106 subprocess.kill();107 const settled = await Promise.race([106 t.throwsAsync(subprocess).then(() => 'settled'),108 assertRejects(subprocess).then(() => 'settled'),109 setTimeout(1e4, 'pending', {ref: false}),110 ]);109 t.is(settled, 'settled');110 t.false(isRunning(descendantPid));111 assert.equal(settled, 'settled');112 assert.ok(!isRunning(descendantPid));113});114115if (!isWindows) {114 // A PID can be re-assigned to an unrelated process once Execa is done with the subprocess, so its process group must not be signaled anymore115 const testAbandonedProcessGroup = test.macro(async (t, getSubprocess) => {116 const subprocess = getSubprocess();117 await t.throwsAsync(subprocess);116 // The process group ID stays reserved while a descendant is running, so the descendants which outlive the subprocess can still be terminated once Execa is done with it117 test('killDescendants terminates background descendants once Execa is done with the subprocess', async () => {118 const subprocess = execa({shell: true, killDescendants: true})`sleep 100 > /dev/null 2>&1 & echo $!`;119 const {stdout} = await subprocess;120 const descendantPid = Number(stdout);121119 const originalKill = process.kill;120 t.teardown(() => {121 process.kill = originalKill;122 });123124 const signaledProcesses = [];125 process.kill = (pid, signal) => {126 signaledProcesses.push([pid, signal]);127 return true;128 };129130 t.false(subprocess.kill('SIGKILL'));131 t.deepEqual(signaledProcesses, []);122 try {123 assert.ok(isRunning(descendantPid));124 assert.ok(subprocess.kill());125 await pollForSubprocessExit(descendantPid);126 } finally {127 if (isRunning(descendantPid)) {128 process.kill(descendantPid, 'SIGKILL');129 }130 }131 });132134 test.serial('killDescendants does not signal the process group once Execa is done with the subprocess', testAbandonedProcessGroup, () => execa('fail.js', {killDescendants: true}));135136 test.serial('killDescendants does not signal the process group once Execa is done with a terminated subprocess', testAbandonedProcessGroup, () => {137 const subprocess = execa('forever.js', {killDescendants: true});138 subprocess.kill('SIGTERM');139 return subprocess;133 // Once the whole process group exited, its PID is not signaled since `process.kill()` fails134 test('killDescendants returns false once the whole process group exited', async () => {135 const subprocess = execa('empty.js', {killDescendants: true});136 await subprocess;137 assert.equal(subprocess.kill(), false);138 });139140 // While Execa is still waiting on the subprocess, its process group is still its own143 test.serial('killDescendants signals the process group while Execa is not done with the subprocess', async t => {141 test('killDescendants signals the process group while Execa is not done with the subprocess', async t => {142 const subprocess = execa('forever.js', {killDescendants: true});143144 const originalKill = process.kill;147 t.teardown(() => {145 t.after(() => {146 process.kill = originalKill;147 });148149 const signaledProcesses = [];
1 unmodified line
151 signaledProcesses.push([pid, signal]);152 return originalKill(pid, signal);153 };154157 t.true(subprocess.kill('SIGTERM'));158 t.deepEqual(signaledProcesses, [[-subprocess.pid, 'SIGTERM']]);155 assert.ok(subprocess.kill('SIGTERM'));156 assert.deepEqual(signaledProcesses, [[-subprocess.pid, 'SIGTERM']]);157 process.kill = originalKill;160 await t.throwsAsync(subprocess);158 await assertRejects(subprocess);159 });160}161164test('Cannot use "killDescendants" option, sync', t => {165 t.throws(() => {162test('Cannot use "killDescendants" option, sync', () => {163 assertThrows(() => {164 execaSync('empty.js', {killDescendants: true});165 }, {message: /The "killDescendants: true" option cannot be used/});166});167170test.serial('taskkill is resolved from the Windows directory when available', t => {168test('taskkill is resolved from the Windows directory when available', t => {169 const {SystemRoot, windir} = process.env;172 t.teardown(() => {170 t.after(() => {171 restoreEnvironment('SystemRoot', SystemRoot);172 restoreEnvironment('windir', windir);173 });174175 process.env.SystemRoot = 'C:\\Windows';176 process.env.windir = 'D:\\Windows';179 t.is(getTaskkillFile(), path.join('C:\\Windows', 'System32', 'taskkill.exe'));177 assert.equal(getTaskkillFile(), path.join('C:\\Windows', 'System32', 'taskkill.exe'));178179 process.env.SystemRoot = 'C:/Windows';182 t.is(getTaskkillFile(), path.join('C:/Windows', 'System32', 'taskkill.exe'));180 assert.equal(getTaskkillFile(), path.join('C:/Windows', 'System32', 'taskkill.exe'));181182 process.env.SystemRoot = 'Windows';185 t.is(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));183 assert.equal(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));184185 process.env.SystemRoot = '\\Windows';188 t.is(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));186 assert.equal(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));187188 delete process.env.SystemRoot;191 t.is(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));189 assert.equal(getTaskkillFile(), path.join('D:\\Windows', 'System32', 'taskkill.exe'));190191 process.env.windir = 'Windows';194 t.is(getTaskkillFile(), undefined);192 assert.equal(getTaskkillFile(), undefined);193194 process.env.windir = '\\Windows';197 t.is(getTaskkillFile(), undefined);195 assert.equal(getTaskkillFile(), undefined);196197 process.env.windir = '\\\\server\\share\\Windows';200 t.is(getTaskkillFile(), undefined);198 assert.equal(getTaskkillFile(), undefined);199200 process.env.windir = '';203 t.is(getTaskkillFile(), undefined);201 assert.equal(getTaskkillFile(), undefined);202203 delete process.env.windir;206 t.is(getTaskkillFile(), undefined);204 assert.equal(getTaskkillFile(), undefined);205});206207/*208The `taskkill` logic only runs on Windows, so the platform, the Windows directory and `taskkill` itself are faked to test it on any OS.
4 unmodified lines
213const fakeWindows = async (t, systemRoot, execFile = () => {}) => {214 const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform');215 const originalExecFile = childProcess.execFile;216 const {SystemRoot, windir} = process.env;219 t.teardown(() => {217 t.after(() => {218 Object.defineProperty(process, 'platform', platformDescriptor);219 childProcess.execFile = originalExecFile;220 syncBuiltinESMExports();221 restoreEnvironment('SystemRoot', SystemRoot);
24 unmodified lines
246 };247 return subprocess;248};249252const abortedController = () => {253 const controller = new AbortController();254 controller.abort();255 return controller;256};257258test.serial('taskkill fallback uses direct subprocess kill when Windows directory is unavailable', async t => {250test('taskkill fallback uses direct subprocess kill when Windows directory is unavailable', async t => {251 const getKillFunction = await fakeWindows(t, 'Windows');252 const subprocess = createFakeSubprocess();253262 const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());263 t.true(kill('SIGTERM'));264 t.is(subprocess.killedWith, 'SIGTERM');254 const kill = getKillFunction(subprocess, {killDescendants: true});255 assert.ok(kill('SIGTERM'));256 assert.equal(subprocess.killedWith, 'SIGTERM');257});258267test.serial('taskkill fallback uses direct subprocess kill when taskkill cannot be spawned', async t => {259test('taskkill fallback uses direct subprocess kill when taskkill cannot be spawned', async t => {260 const taskkillFailure = Promise.withResolvers();261 const getKillFunction = await fakeWindows(t, 'C:\\MissingWindows', (file, arguments_, callback) => {270 t.is(file, path.join('C:\\MissingWindows', 'System32', 'taskkill.exe'));271 t.deepEqual(arguments_, ['/pid', '123', '/T', '/F']);262 assert.equal(file, path.join('C:\\MissingWindows', 'System32', 'taskkill.exe'));263 assert.deepEqual(arguments_, ['/pid', '123', '/T', '/F']);264 queueMicrotask(() => {265 callback(new Error('spawn failed'));266 taskkillFailure.resolve();267 });268 });269 const subprocess = createFakeSubprocess();270279 const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());280 t.true(kill('SIGTERM'));281 t.is(subprocess.killedWith, undefined);271 const kill = getKillFunction(subprocess, {killDescendants: true});272 assert.ok(kill('SIGTERM'));273 assert.equal(subprocess.killedWith, undefined);274275 await taskkillFailure.promise;284 t.is(subprocess.killedWith, 'SIGTERM');276 assert.equal(subprocess.killedWith, 'SIGTERM');277});278287// Once Execa is done with the subprocess, its PID can be re-assigned by the OS, so its process tree must not be terminated anymore288test.serial('taskkill is not spawned once Execa is done with the subprocess', async t => {279// On Windows, the PID is not reserved anymore once the subprocess exited, even while Execa is still waiting on it280test('taskkill is not spawned once the subprocess exited', async t => {281 let isTaskkillSpawned = false;282 const getKillFunction = await fakeWindows(t, 'C:\\Windows', () => {283 isTaskkillSpawned = true;284 });285 const subprocess = createFakeSubprocess({exitCode: 0});286295 const kill = getKillFunction(subprocess, {killDescendants: true}, abortedController());296 t.false(kill('SIGTERM'));297 t.false(isTaskkillSpawned);298 t.is(subprocess.killedWith, undefined);287 const kill = getKillFunction(subprocess, {killDescendants: true});288 assert.equal(kill('SIGTERM'), false);289 assert.equal(isTaskkillSpawned, false);290 assert.equal(subprocess.killedWith, undefined);291});292301// While Execa is still waiting on the subprocess, its process tree is still its own, even after it exited302test.serial('taskkill is still spawned after the subprocess exited', async t => {303 let taskkillArguments;304 const getKillFunction = await fakeWindows(t, 'C:\\Windows', (file, arguments_) => {305 taskkillArguments = arguments_;306 });307 const subprocess = createFakeSubprocess({exitCode: 0});308309 const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());310 t.true(kill('SIGTERM'));311 t.deepEqual(taskkillArguments, ['/pid', '123', '/T', '/F']);312});313293// A subprocess which never spawned has no PID to signal315test.serial('taskkill is not spawned when the subprocess has no PID', async t => {294test('taskkill is not spawned when the subprocess has no PID', async t => {295 let isTaskkillSpawned = false;296 const getKillFunction = await fakeWindows(t, 'C:\\Windows', () => {297 isTaskkillSpawned = true;298 });299 const subprocess = createFakeSubprocess();300 subprocess.pid = undefined;301323 const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());324 t.false(kill('SIGTERM'));325 t.false(isTaskkillSpawned);326 t.is(subprocess.killedWith, undefined);302 const kill = getKillFunction(subprocess, {killDescendants: true});303 assert.equal(kill('SIGTERM'), false);304 assert.equal(isTaskkillSpawned, false);305 assert.equal(subprocess.killedWith, undefined);306});307308const restoreEnvironment = (name, value) => {309 if (value === undefined) {
5 unmodified lines
modified:test/terminate/kill-error.js+40 added-38 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {setImmediate} from 'node:timers/promises';3import test from 'ava';4import test from 'node:test';5import isRunning from 'is-running';6import {assertRejects} from '../helpers/assert.js';7import {execa} from '../../index.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';910setFixtureDirectory();1110test('.kill(error) propagates error', async t => {12test('.kill(error) propagates error', async () => {13 const subprocess = execa('forever.js');14 const originalMessage = 'test';15 const cause = new Error(originalMessage);14 t.true(subprocess.kill(cause));15 const error = await t.throwsAsync(subprocess);16 t.is(error.cause, cause);17 t.true(cause.stack.includes(import.meta.url));18 t.is(error.exitCode, undefined);19 t.is(error.signal, 'SIGTERM');20 t.true(error.isTerminated);21 t.is(error.originalMessage, originalMessage);22 t.true(error.message.includes(originalMessage));23 t.true(error.message.includes('was killed with SIGTERM'));16 assert.ok(subprocess.kill(cause));17 const error = await assertRejects(subprocess);18 assert.equal(error.cause, cause);19 assert.ok(cause.stack.includes(import.meta.url));20 assert.equal(error.exitCode, undefined);21 assert.equal(error.signal, 'SIGTERM');22 assert.equal(error.isTerminated, true);23 assert.equal(error.originalMessage, originalMessage);24 assert.ok(error.message.includes(originalMessage));25 assert.ok(error.message.includes('was killed with SIGTERM'));26});2726test('.kill(error) uses killSignal', async t => {28test('.kill(error) uses killSignal', async () => {29 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});30 const cause = new Error('test');31 subprocess.kill(cause);30 const error = await t.throwsAsync(subprocess);31 t.is(error.cause, cause);32 t.is(error.signal, 'SIGINT');32 const error = await assertRejects(subprocess);33 assert.equal(error.cause, cause);34 assert.equal(error.signal, 'SIGINT');35});3635test('.kill(signal, error) uses signal', async t => {37test('.kill(signal, error) uses signal', async () => {38 const subprocess = execa('forever.js');39 const cause = new Error('test');40 subprocess.kill('SIGINT', cause);39 const error = await t.throwsAsync(subprocess);40 t.is(error.cause, cause);41 t.is(error.signal, 'SIGINT');41 const error = await assertRejects(subprocess);42 assert.equal(error.cause, cause);43 assert.equal(error.signal, 'SIGINT');44});4544test('.kill(error) is a noop if subprocess already exited', async t => {46test('.kill(error) is a noop if subprocess already exited', async () => {47 const subprocess = execa('empty.js');48 await subprocess;47 t.false(isRunning(subprocess.pid));48 t.false(subprocess.kill(new Error('test')));49 assert.ok(!isRunning(subprocess.pid));50 assert.ok(!subprocess.kill(new Error('test')));51});5251test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {53test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async () => {54 const subprocess = execa('forever.js');55 const cause = new Error('first');56 subprocess.stdout.destroy(cause);57 await setImmediate();58 const secondError = new Error('second');57 t.true(subprocess.kill(secondError));58 const error = await t.throwsAsync(subprocess);59 t.is(error.cause, cause);60 t.is(error.exitCode, undefined);61 t.is(error.signal, 'SIGTERM');62 t.true(error.isTerminated);63 t.false(error.message.includes(secondError.message));59 assert.ok(subprocess.kill(secondError));60 const error = await assertRejects(subprocess);61 assert.equal(error.cause, cause);62 assert.equal(error.exitCode, undefined);63 assert.equal(error.signal, 'SIGTERM');64 assert.equal(error.isTerminated, true);65 assert.ok(!error.message.includes(secondError.message));66});6766test('.kill(error) twice in a row', async t => {68test('.kill(error) twice in a row', async () => {69 const subprocess = execa('forever.js');70 const cause = new Error('first');71 subprocess.kill(cause);72 const secondCause = new Error('second');73 subprocess.kill(secondCause);72 const error = await t.throwsAsync(subprocess);73 t.is(error.cause, cause);74 t.false(error.message.includes(secondCause.message));74 const error = await assertRejects(subprocess);75 assert.equal(error.cause, cause);76 assert.ok(!error.message.includes(secondCause.message));77});7877test('.kill(error) does not emit the "error" event', async t => {79test('.kill(error) does not emit the "error" event', async () => {80 const subprocess = execa('forever.js');81 const cause = new Error('test');82 subprocess.kill(cause);81 const error = await Promise.race([t.throwsAsync(subprocess), once(subprocess.nodeChildProcess, 'error')]);82 t.is(error.cause, cause);83 const error = await Promise.race([assertRejects(subprocess), once(subprocess.nodeChildProcess, 'error')]);84 assert.equal(error.cause, cause);85});
modified:test/terminate/kill-force.js+96 added-94 removed
1import assert from 'node:assert/strict';2import process from 'node:process';3import {once, defaultMaxListeners} from 'node:events';4import {constants} from 'node:os';5import {setTimeout} from 'node:timers/promises';5import test from 'ava';6import test from 'node:test';7import isRunning from 'is-running';8import {assertThrows, assertRejects} from '../helpers/assert.js';9import {execa} from '../../index.js';10import {setFixtureDirectory} from '../helpers/fixtures-directory.js';11import {assertMaxListeners} from '../helpers/listeners.js';12import {foobarString} from '../helpers/input.js';
15 unmodified lines
2829const noKillableSimpleOptions = {killSignal: 'SIGWINCH', forceKillAfterDelay: 1};30const spawnNoKillableSimple = options => execa('forever.js', {...noKillableSimpleOptions, ...options});3130test('kill("SIGKILL") should terminate cleanly', async t => {32test('kill("SIGKILL") should terminate cleanly', async () => {33 const {subprocess} = await spawnNoKillable();3435 subprocess.kill('SIGKILL');3635 const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);36 t.true(isTerminated);37 t.is(signal, 'SIGKILL');38 t.false(isForcefullyTerminated);39 t.is(shortMessage, 'Command was killed with SIGKILL (Forced termination): no-killable.js');37 const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await assertRejects(subprocess);38 assert.equal(isTerminated, true);39 assert.equal(signal, 'SIGKILL');40 assert.equal(isForcefullyTerminated, false);41 assert.equal(shortMessage, 'Command was killed with SIGKILL (Forced termination): no-killable.js');42});4342const testInvalidForceKill = async (t, forceKillAfterDelay) => {43 t.throws(() => {44const testInvalidForceKill = async forceKillAfterDelay => {45 assertThrows(() => {46 execa('empty.js', {forceKillAfterDelay});47 }, {instanceOf: TypeError, message: /non-negative integer/});48};4948test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, NaN);49test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);50test('`forceKillAfterDelay` should not be NaN', () => testInvalidForceKill(NaN));51test('`forceKillAfterDelay` should not be negative', () => testInvalidForceKill(-1));5253// `SIGTERM` cannot be caught on Windows, and it always aborts the subprocess (like `SIGKILL` on Unix).54// Therefore, this feature and those tests must be different on Windows.55if (isWindows) {54 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async t => {56 test('Can call `.kill()` with `forceKillAfterDelay` on Windows', async () => {57 const {subprocess} = await spawnNoKillable();58 subprocess.kill();5958 const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);59 t.true(isTerminated);60 t.is(signal, 'SIGTERM');61 t.false(isForcefullyTerminated);62 t.is(shortMessage, 'Command was killed with SIGTERM (Termination): no-killable.js');60 const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await assertRejects(subprocess);61 assert.equal(isTerminated, true);62 assert.equal(signal, 'SIGTERM');63 assert.equal(isForcefullyTerminated, false);64 assert.equal(shortMessage, 'Command was killed with SIGTERM (Termination): no-killable.js');65 });66} else {65 const testNoForceKill = async (t, forceKillAfterDelay, killArgument, options) => {67 const testNoForceKill = async (forceKillAfterDelay, killArgument, options) => {68 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);6970 subprocess.kill(killArgument);7172 await setTimeout(6e3);71 t.true(isRunning(subprocess.pid));73 assert.ok(isRunning(subprocess.pid));74 subprocess.kill('SIGKILL');7574 const {isTerminated, signal, isForcefullyTerminated} = await t.throwsAsync(subprocess);75 t.true(isTerminated);76 t.is(signal, 'SIGKILL');77 t.false(isForcefullyTerminated);76 const {isTerminated, signal, isForcefullyTerminated} = await assertRejects(subprocess);77 assert.equal(isTerminated, true);78 assert.equal(signal, 'SIGKILL');79 assert.equal(isForcefullyTerminated, false);80 };8180 test('`forceKillAfterDelay: false` should not kill after a timeout', testNoForceKill, false);81 test('`forceKillAfterDelay` should not kill after a timeout with other signals', testNoForceKill, true, 'SIGINT');82 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', testNoForceKill, true, 'SIGTERM', {killSignal: 'SIGINT'});83 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', testNoForceKill, true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT});82 test('`forceKillAfterDelay: false` should not kill after a timeout', () => testNoForceKill(false));83 test('`forceKillAfterDelay` should not kill after a timeout with other signals', () => testNoForceKill(true, 'SIGINT'));84 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal string', () => testNoForceKill(true, 'SIGTERM', {killSignal: 'SIGINT'}));85 test('`forceKillAfterDelay` should not kill after a timeout with wrong killSignal number', () => testNoForceKill(true, constants.signals.SIGTERM, {killSignal: constants.signals.SIGINT}));8687 // eslint-disable-next-line max-params86 const testForceKill = async (t, forceKillAfterDelay, killSignal, expectedDelay, expectedKillSignal, options) => {88 const testForceKill = async (forceKillAfterDelay, killSignal, expectedDelay, expectedKillSignal, options) => {89 const {subprocess} = await spawnNoKillable(forceKillAfterDelay, options);9091 subprocess.kill(killSignal);9291 const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);92 t.true(isTerminated);93 t.is(signal, 'SIGKILL');94 t.true(isForcefullyTerminated);93 const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await assertRejects(subprocess);94 assert.equal(isTerminated, true);95 assert.equal(signal, 'SIGKILL');96 assert.equal(isForcefullyTerminated, true);97 const messageSuffix = killSignal instanceof Error ? `\n${killSignal.message}` : '';98 const signalDescription = expectedKillSignal === 'SIGINT' ? 'User interruption with CTRL-C' : 'Termination';97 t.is(shortMessage, `Command was killed with ${expectedKillSignal} (${signalDescription}) and was forcefully terminated after ${expectedDelay} milliseconds: no-killable.js${messageSuffix}`);99 assert.equal(shortMessage, `Command was killed with ${expectedKillSignal} (${signalDescription}) and was forcefully terminated after ${expectedDelay} milliseconds: no-killable.js${messageSuffix}`);100 };101100 test('`forceKillAfterDelay: number` should kill after a timeout', testForceKill, 50, undefined, 50, 'SIGTERM');101 test('`forceKillAfterDelay: true` should kill after a timeout', testForceKill, true, undefined, 5e3, 'SIGTERM');102 test('`forceKillAfterDelay: undefined` should kill after a timeout', testForceKill, undefined, undefined, 5e3, 'SIGTERM');103 test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', testForceKill, 50, 'SIGTERM', 50, 'SIGTERM');104 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', testForceKill, 50, 'SIGINT', 50, 'SIGINT', {killSignal: 'SIGINT'});105 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string, mixed', testForceKill, 50, 'SIGINT', 50, 'SIGINT', {killSignal: constants.signals.SIGINT});106 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', testForceKill, 50, constants.signals.SIGINT, 50, 'SIGINT', {killSignal: constants.signals.SIGINT});107 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number, mixed', testForceKill, 50, constants.signals.SIGINT, 50, 'SIGINT', {killSignal: 'SIGINT'});108 test('`forceKillAfterDelay` should kill after a timeout with an error', testForceKill, 50, new Error('test'), 50, 'SIGTERM');109 test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', testForceKill, 50, new Error('test'), 50, 'SIGINT', {killSignal: 'SIGINT'});102 test('`forceKillAfterDelay: number` should kill after a timeout', () => testForceKill(50, undefined, 50, 'SIGTERM'));103 test('`forceKillAfterDelay: true` should kill after a timeout', () => testForceKill(true, undefined, 5e3, 'SIGTERM'));104 test('`forceKillAfterDelay: undefined` should kill after a timeout', () => testForceKill(undefined, undefined, 5e3, 'SIGTERM'));105 test('`forceKillAfterDelay` should kill after a timeout with SIGTERM', () => testForceKill(50, 'SIGTERM', 50, 'SIGTERM'));106 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string', () => testForceKill(50, 'SIGINT', 50, 'SIGINT', {killSignal: 'SIGINT'}));107 test('`forceKillAfterDelay` should kill after a timeout with the killSignal string, mixed', () => testForceKill(50, 'SIGINT', 50, 'SIGINT', {killSignal: constants.signals.SIGINT}));108 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number', () => testForceKill(50, constants.signals.SIGINT, 50, 'SIGINT', {killSignal: constants.signals.SIGINT}));109 test('`forceKillAfterDelay` should kill after a timeout with the killSignal number, mixed', () => testForceKill(50, constants.signals.SIGINT, 50, 'SIGINT', {killSignal: 'SIGINT'}));110 test('`forceKillAfterDelay` should kill after a timeout with an error', () => testForceKill(50, new Error('test'), 50, 'SIGTERM'));111 test('`forceKillAfterDelay` should kill after a timeout with an error and a killSignal', () => testForceKill(50, new Error('test'), 50, 'SIGINT', {killSignal: 'SIGINT'}));112111 test('`forceKillAfterDelay` works with the "cancelSignal" option', async t => {113 test('`forceKillAfterDelay` works with the "cancelSignal" option', async () => {114 const abortController = new AbortController();115 const subprocess = spawnNoKillableSimple({cancelSignal: abortController.signal});116 await once(subprocess.nodeChildProcess, 'spawn');117 abortController.abort('');116 const {isTerminated, signal, isCanceled, isGracefullyCanceled, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);117 t.true(isTerminated);118 t.is(signal, 'SIGKILL');119 t.true(isCanceled);120 t.false(isGracefullyCanceled);121 t.true(isForcefullyTerminated);122 t.is(shortMessage, 'Command was canceled and was forcefully terminated after 1 milliseconds: forever.js');118 const {isTerminated, signal, isCanceled, isGracefullyCanceled, isForcefullyTerminated, shortMessage} = await assertRejects(subprocess);119 assert.equal(isTerminated, true);120 assert.equal(signal, 'SIGKILL');121 assert.equal(isCanceled, true);122 assert.equal(isGracefullyCanceled, false);123 assert.equal(isForcefullyTerminated, true);124 assert.equal(shortMessage, 'Command was canceled and was forcefully terminated after 1 milliseconds: forever.js');125 });126125 test('`forceKillAfterDelay` works with the "timeout" option', async t => {126 const {isTerminated, signal, timedOut, isForcefullyTerminated, shortMessage} = await t.throwsAsync(spawnNoKillableSimple({timeout: 1}));127 t.true(isTerminated);128 t.is(signal, 'SIGKILL');129 t.true(timedOut);130 t.true(isForcefullyTerminated);131 t.is(shortMessage, 'Command timed out after 1 milliseconds and was forcefully terminated after 1 milliseconds: forever.js');127 test('`forceKillAfterDelay` works with the "timeout" option', async () => {128 const {isTerminated, signal, timedOut, isForcefullyTerminated, shortMessage} = await assertRejects(spawnNoKillableSimple({timeout: 1}));129 assert.equal(isTerminated, true);130 assert.equal(signal, 'SIGKILL');131 assert.equal(timedOut, true);132 assert.equal(isForcefullyTerminated, true);133 assert.equal(shortMessage, 'Command timed out after 1 milliseconds and was forcefully terminated after 1 milliseconds: forever.js');134 });135134 test('`forceKillAfterDelay` works with the "maxBuffer" option', async t => {136 test('`forceKillAfterDelay` works with the "maxBuffer" option', async () => {137 const subprocess = execa('noop-forever.js', ['.'], {...noKillableSimpleOptions, maxBuffer: 1});138 const [chunk] = await once(subprocess.stdout, 'data');137 t.is(chunk.toString(), '.\n');139 assert.equal(chunk.toString(), '.\n');140 subprocess.kill();139 const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await t.throwsAsync(subprocess);140 t.true(isTerminated);141 t.is(signal, 'SIGKILL');142 t.true(isForcefullyTerminated);143 t.is(shortMessage, 'Command\'s stdout was larger than 1 characters and was forcefully terminated after 1 milliseconds: noop-forever.js .\nmaxBuffer exceeded');141 const {isTerminated, signal, isForcefullyTerminated, shortMessage} = await assertRejects(subprocess);142 assert.equal(isTerminated, true);143 assert.equal(signal, 'SIGKILL');144 assert.equal(isForcefullyTerminated, true);145 assert.equal(shortMessage, 'Command\'s stdout was larger than 1 characters and was forcefully terminated after 1 milliseconds: noop-forever.js .\nmaxBuffer exceeded');146 });147146 test('`forceKillAfterDelay` works with the "error" event', async t => {148 test('`forceKillAfterDelay` works with the "error" event', async () => {149 const subprocess = spawnNoKillableSimple();150 await once(subprocess.nodeChildProcess, 'spawn');151 const error = new Error(foobarString);152 error.code = 'ECODE';153 subprocess.nodeChildProcess.emit('error', error);154 subprocess.kill();153 const {isTerminated, signal, isForcefullyTerminated, shortMessage, originalMessage, cause} = await t.throwsAsync(subprocess);154 t.true(isTerminated);155 t.is(signal, 'SIGKILL');156 t.true(isForcefullyTerminated);157 t.is(cause, error);158 t.is(originalMessage, error.message);159 t.is(shortMessage, `Command failed with ${error.code} and was forcefully terminated after 1 milliseconds: forever.js\n${error.message}`);155 const {isTerminated, signal, isForcefullyTerminated, shortMessage, originalMessage, cause} = await assertRejects(subprocess);156 assert.equal(isTerminated, true);157 assert.equal(signal, 'SIGKILL');158 assert.equal(isForcefullyTerminated, true);159 assert.equal(cause, error);160 assert.equal(originalMessage, error.message);161 assert.equal(shortMessage, `Command failed with ${error.code} and was forcefully terminated after 1 milliseconds: forever.js\n${error.message}`);162 });163162 test.serial('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async t => {163 const checkMaxListeners = assertMaxListeners(t);164 test('Can call `.kill()` with `forceKillAfterDelay` many times without triggering the maxListeners warning', async () => {165 const checkMaxListeners = assertMaxListeners();166167 const subprocess = spawnNoKillableSimple();168 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {169 subprocess.kill();170 }171170 const {isTerminated, signal, isForcefullyTerminated} = await t.throwsAsync(subprocess);171 t.true(isTerminated);172 t.is(signal, 'SIGKILL');173 t.true(isForcefullyTerminated);172 const {isTerminated, signal, isForcefullyTerminated} = await assertRejects(subprocess);173 assert.equal(isTerminated, true);174 assert.equal(signal, 'SIGKILL');175 assert.equal(isForcefullyTerminated, true);176177 checkMaxListeners();178 });179178 test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async t => {180 test('Can call `.kill()` with `forceKillAfterDelay` multiple times', async () => {181 const subprocess = spawnNoKillableSimple();182 subprocess.kill();183 subprocess.kill();184183 const {isTerminated, signal, isForcefullyTerminated} = await t.throwsAsync(subprocess);184 t.true(isTerminated);185 t.is(signal, 'SIGKILL');186 t.true(isForcefullyTerminated);185 const {isTerminated, signal, isForcefullyTerminated} = await assertRejects(subprocess);186 assert.equal(isTerminated, true);187 assert.equal(signal, 'SIGKILL');188 assert.equal(isForcefullyTerminated, true);189 });190}191190test('result.isForcefullyTerminated is false on success', async t => {192test('result.isForcefullyTerminated is false on success', async () => {193 const {isForcefullyTerminated} = await execa('empty.js');192 t.false(isForcefullyTerminated);194 assert.equal(isForcefullyTerminated, false);195});196195test('error.isForcefullyTerminated is false on spawn errors', async t => {196 const {isForcefullyTerminated} = await t.throwsAsync(getEarlyErrorSubprocess());197 t.false(isForcefullyTerminated);197test('error.isForcefullyTerminated is false on spawn errors', async () => {198 const {isForcefullyTerminated} = await assertRejects(getEarlyErrorSubprocess());199 assert.equal(isForcefullyTerminated, false);200});201200test('error.isForcefullyTerminated is false when already terminated', async t => {202test('error.isForcefullyTerminated is false when already terminated', async () => {203 const abortController = new AbortController();204 const final = async function * () {205 try {206 await setTimeout(1e6, undefined, {signal: abortController.signal});
5 unmodified lines
212 const subprocess = execa('forever.js', {stdout: {final}});213 subprocess.kill();214 await setTimeout(6e3);215 abortController.abort();214 const {isForcefullyTerminated, isTerminated, signal} = await t.throwsAsync(subprocess);215 t.false(isForcefullyTerminated);216 t.true(isTerminated);217 t.is(signal, 'SIGTERM');216 const {isForcefullyTerminated, isTerminated, signal} = await assertRejects(subprocess);217 assert.equal(isForcefullyTerminated, false);218 assert.equal(isTerminated, true);219 assert.equal(signal, 'SIGTERM');220});
modified:test/terminate/kill-signal.js+66 added-64 removed
1import assert from 'node:assert/strict';2import {once} from 'node:events';3import {constants} from 'node:os';4import {setImmediate} from 'node:timers/promises';4import test from 'ava';5import test from 'node:test';6import {assertThrows, assertRejects} from '../helpers/assert.js';7import {execa, execaSync} from '../../index.js';8import {setFixtureDirectory} from '../helpers/fixtures-directory.js';910setFixtureDirectory();1110const testKillSignal = async (t, killSignal) => {11 const {isTerminated, signal} = await t.throwsAsync(execa('forever.js', {killSignal, timeout: 1}));12 t.true(isTerminated);13 t.is(signal, 'SIGINT');12const testKillSignal = async killSignal => {13 const {isTerminated, signal} = await assertRejects(execa('forever.js', {killSignal, timeout: 1}));14 assert.equal(isTerminated, true);15 assert.equal(signal, 'SIGINT');16};1716test('Can use killSignal: "SIGINT"', testKillSignal, 'SIGINT');17test('Can use killSignal: 2', testKillSignal, constants.signals.SIGINT);18test('Can use killSignal: "SIGINT"', () => testKillSignal('SIGINT'));19test('Can use killSignal: 2', () => testKillSignal(constants.signals.SIGINT));2019const testKillSignalSync = (t, killSignal) => {20 const {isTerminated, signal} = t.throws(() => {21const testKillSignalSync = killSignal => {22 const {isTerminated, signal} = assertThrows(() => {23 execaSync('forever.js', {killSignal, timeout: 1});24 });23 t.true(isTerminated);24 t.is(signal, 'SIGINT');25 assert.equal(isTerminated, true);26 assert.equal(signal, 'SIGINT');27};2827test('Can use killSignal: "SIGINT", sync', testKillSignalSync, 'SIGINT');28test('Can use killSignal: 2, sync', testKillSignalSync, constants.signals.SIGINT);29test('Can use killSignal: "SIGINT", sync', () => testKillSignalSync('SIGINT'));30test('Can use killSignal: 2, sync', () => testKillSignalSync(constants.signals.SIGINT));3130test('Can call .kill("SIGTERM")', async t => {32test('Can call .kill("SIGTERM")', async () => {33 const subprocess = execa('forever.js');34 subprocess.kill('SIGTERM');33 const {isTerminated, signal} = await t.throwsAsync(subprocess);34 t.true(isTerminated);35 t.is(signal, 'SIGTERM');35 const {isTerminated, signal} = await assertRejects(subprocess);36 assert.equal(isTerminated, true);37 assert.equal(signal, 'SIGTERM');38});3938test('Can call .kill(15)', async t => {40test('Can call .kill(15)', async () => {41 const subprocess = execa('forever.js');42 subprocess.kill(constants.signals.SIGTERM);41 const {isTerminated, signal} = await t.throwsAsync(subprocess);42 t.true(isTerminated);43 t.is(signal, 'SIGTERM');43 const {isTerminated, signal} = await assertRejects(subprocess);44 assert.equal(isTerminated, true);45 assert.equal(signal, 'SIGTERM');46});4746test('Can call .kill(0)', async t => {48test('Can call .kill(0)', async () => {49 const subprocess = execa('forever.js');48 t.true(subprocess.kill(0));50 assert.ok(subprocess.kill(0));51 subprocess.kill();50 await t.throwsAsync(subprocess);51 t.false(subprocess.kill(0));52 await assertRejects(subprocess);53 assert.ok(!subprocess.kill(0));54});5554test('Can call `.kill()` multiple times', async t => {56test('Can call `.kill()` multiple times', async () => {57 const subprocess = execa('forever.js');58 subprocess.kill();59 subprocess.kill();6059 const {exitCode, isTerminated, signal, code} = await t.throwsAsync(subprocess);60 t.is(exitCode, undefined);61 t.true(isTerminated);62 t.is(signal, 'SIGTERM');63 t.is(code, undefined);61 const {exitCode, isTerminated, signal, code} = await assertRejects(subprocess);62 assert.equal(exitCode, undefined);63 assert.equal(isTerminated, true);64 assert.equal(signal, 'SIGTERM');65 assert.equal(code, undefined);66});6766test('execa() returns a promise with kill()', async t => {68test('execa() returns a promise with kill()', async () => {69 const subprocess = execa('noop.js', ['foo']);68 t.is(typeof subprocess.kill, 'function');70 assert.equal(typeof subprocess.kill, 'function');71 await subprocess;72});7372const testInvalidKillArgument = async (t, killArgument, secondKillArgument) => {74const testInvalidKillArgument = async (killArgument, secondKillArgument) => {75 const subprocess = execa('empty.js');74 const message = secondKillArgument instanceof Error || secondKillArgument === undefined76 const message = secondKillArgument === undefined || secondKillArgument instanceof Error77 ? /error instance or a signal name/78 : /second argument is optional/;77 t.throws(() => {79 assertThrows(() => {80 subprocess.kill(killArgument, secondKillArgument);81 }, {message});82 await subprocess;83};8483test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});84test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);85test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);86test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);87test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));85test('Cannot call .kill(errorObject)', () => testInvalidKillArgument({name: '', message: '', stack: ''}));86test('Cannot call .kill(errorArray)', () => testInvalidKillArgument([new Error('test')]));87test('Cannot call .kill(undefined, true)', () => testInvalidKillArgument(undefined, true));88test('Cannot call .kill("SIGTERM", true)', () => testInvalidKillArgument('SIGTERM', true));89test('Cannot call .kill(true, error)', () => testInvalidKillArgument(true, new Error('test')));9089test('subprocess errors are handled before spawn', async t => {91test('subprocess errors are handled before spawn', async () => {92 const subprocess = execa('forever.js');93 const cause = new Error('test');94 subprocess.nodeChildProcess.emit('error', cause);95 subprocess.kill();94 const error = await t.throwsAsync(subprocess);95 t.is(error.cause, cause);96 t.is(error.exitCode, undefined);97 t.is(error.signal, undefined);98 t.false(error.isTerminated);96 const error = await assertRejects(subprocess);97 assert.equal(error.cause, cause);98 assert.equal(error.exitCode, undefined);99 assert.equal(error.signal, undefined);100 assert.equal(error.isTerminated, false);101});102101test('subprocess errors are handled after spawn', async t => {103test('subprocess errors are handled after spawn', async () => {104 const subprocess = execa('forever.js');105 await once(subprocess.nodeChildProcess, 'spawn');106 const cause = new Error('test');107 subprocess.nodeChildProcess.emit('error', cause);108 subprocess.kill();107 const error = await t.throwsAsync(subprocess);108 t.is(error.cause, cause);109 t.is(error.exitCode, undefined);110 t.is(error.signal, 'SIGTERM');111 t.true(error.isTerminated);109 const error = await assertRejects(subprocess);110 assert.equal(error.cause, cause);111 assert.equal(error.exitCode, undefined);112 assert.equal(error.signal, 'SIGTERM');113 assert.equal(error.isTerminated, true);114});115114test('subprocess double errors are handled after spawn', async t => {116test('subprocess double errors are handled after spawn', async () => {117 const abortController = new AbortController();118 const subprocess = execa('forever.js', {cancelSignal: abortController.signal});119 await once(subprocess.nodeChildProcess, 'spawn');120 const cause = new Error('test');121 subprocess.nodeChildProcess.emit('error', cause);122 await setImmediate();123 abortController.abort();124 subprocess.nodeChildProcess.emit('error', cause);123 const error = await t.throwsAsync(subprocess);124 t.is(error.cause, cause);125 t.is(error.exitCode, undefined);126 t.is(error.signal, 'SIGTERM');127 t.true(error.isTerminated);125 const error = await assertRejects(subprocess);126 assert.equal(error.cause, cause);127 assert.equal(error.exitCode, undefined);128 assert.equal(error.signal, 'SIGTERM');129 assert.equal(error.isTerminated, true);130});131130test('subprocess errors use killSignal', async t => {132test('subprocess errors use killSignal', async () => {133 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});134 await once(subprocess.nodeChildProcess, 'spawn');135 const cause = new Error('test');136 subprocess.nodeChildProcess.emit('error', cause);137 subprocess.kill();136 const error = await t.throwsAsync(subprocess);137 t.is(error.cause, cause);138 t.true(error.isTerminated);139 t.is(error.signal, 'SIGINT');138 const error = await assertRejects(subprocess);139 assert.equal(error.cause, cause);140 assert.equal(error.isTerminated, true);141 assert.equal(error.signal, 'SIGINT');142});
modified:test/terminate/signal.js+58 added-54 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';67setFixtureDirectory();
5 unmodified lines
13 rename: 'please rename it to',14 zero: '0 cannot be used',15};1615const validateMessage = (t, message, type) => {16 t.true(message.includes(VALIDATION_MESSAGES[type]));17const validateMessage = (message, type) => {18 assert.ok(message.includes(VALIDATION_MESSAGES[type]));1918 if (type !== 'rename' && type !== 'zero') {19 t.true(message.includes('Available signal names: \'SIGABRT\', '));20 t.true(message.includes('Available signal numbers: 1, '));20 if (type === 'rename' || type === 'zero') {21 return;22 }2324 assert.ok(message.includes('Available signal names: \'SIGABRT\', '));25 assert.ok(message.includes('Available signal numbers: 1, '));26};2724const testInvalidKillSignal = (t, killSignal, type, execaMethod) => {25 const {message} = t.throws(() => {28const testInvalidKillSignal = (killSignal, type, execaMethod) => {29 const {message} = assertThrows(() => {30 execaMethod('empty.js', {killSignal});31 });28 t.true(message.includes('Invalid option `killSignal`'));29 validateMessage(t, message, type);32 assert.ok(message.includes('Invalid option `killSignal`'));33 validateMessage(message, type);34};3532test('Cannot use killSignal: "SIGOTHER"', testInvalidKillSignal, 'SIGOTHER', 'string', execa);33test('Cannot use killSignal: "Sigterm"', testInvalidKillSignal, 'Sigterm', 'rename', execa);34test('Cannot use killSignal: "sigterm"', testInvalidKillSignal, 'sigterm', 'rename', execa);35test('Cannot use killSignal: -1', testInvalidKillSignal, -1, 'integer', execa);36test('Cannot use killSignal: 200', testInvalidKillSignal, 200, 'integer', execa);37test('Cannot use killSignal: 1n', testInvalidKillSignal, 1n, 'other', execa);38test('Cannot use killSignal: 1.5', testInvalidKillSignal, 1.5, 'other', execa);39test('Cannot use killSignal: Infinity', testInvalidKillSignal, Infinity, 'other', execa);40test('Cannot use killSignal: NaN', testInvalidKillSignal, NaN, 'other', execa);41test('Cannot use killSignal: false', testInvalidKillSignal, false, 'other', execa);42test('Cannot use killSignal: null', testInvalidKillSignal, null, 'other', execa);43test('Cannot use killSignal: symbol', testInvalidKillSignal, Symbol('test'), 'other', execa);44test('Cannot use killSignal: {}', testInvalidKillSignal, {}, 'other', execa);45test('Cannot use killSignal: 0', testInvalidKillSignal, 0, 'zero', execa);46test('Cannot use killSignal: "SIGOTHER", sync', testInvalidKillSignal, 'SIGOTHER', 'string', execaSync);47test('Cannot use killSignal: "Sigterm", sync', testInvalidKillSignal, 'Sigterm', 'rename', execaSync);48test('Cannot use killSignal: "sigterm", sync', testInvalidKillSignal, 'sigterm', 'rename', execaSync);49test('Cannot use killSignal: -1, sync', testInvalidKillSignal, -1, 'integer', execaSync);50test('Cannot use killSignal: 200, sync', testInvalidKillSignal, 200, 'integer', execaSync);51test('Cannot use killSignal: 1.5, sync', testInvalidKillSignal, 1.5, 'other', execaSync);52test('Cannot use killSignal: Infinity, sync', testInvalidKillSignal, Infinity, 'other', execaSync);53test('Cannot use killSignal: NaN, sync', testInvalidKillSignal, NaN, 'other', execaSync);54test('Cannot use killSignal: null, sync', testInvalidKillSignal, null, 'other', execaSync);55test('Cannot use killSignal: symbol, sync', testInvalidKillSignal, Symbol('test'), 'other', execaSync);56test('Cannot use killSignal: {}, sync', testInvalidKillSignal, {}, 'other', execaSync);57test('Cannot use killSignal: 0, sync', testInvalidKillSignal, 0, 'zero', execaSync);36test('Cannot use killSignal: "SIGOTHER"', () => testInvalidKillSignal('SIGOTHER', 'string', execa));37test('Cannot use killSignal: "Sigterm"', () => testInvalidKillSignal('Sigterm', 'rename', execa));38test('Cannot use killSignal: "sigterm"', () => testInvalidKillSignal('sigterm', 'rename', execa));39test('Cannot use killSignal: -1', () => testInvalidKillSignal(-1, 'integer', execa));40test('Cannot use killSignal: 200', () => testInvalidKillSignal(200, 'integer', execa));41test('Cannot use killSignal: 1n', () => testInvalidKillSignal(1n, 'other', execa));42test('Cannot use killSignal: 1.5', () => testInvalidKillSignal(1.5, 'other', execa));43test('Cannot use killSignal: Infinity', () => testInvalidKillSignal(Infinity, 'other', execa));44test('Cannot use killSignal: NaN', () => testInvalidKillSignal(NaN, 'other', execa));45test('Cannot use killSignal: false', () => testInvalidKillSignal(false, 'other', execa));46test('Cannot use killSignal: null', () => testInvalidKillSignal(null, 'other', execa));47test('Cannot use killSignal: symbol', () => testInvalidKillSignal(Symbol('test'), 'other', execa));48test('Cannot use killSignal: {}', () => testInvalidKillSignal({}, 'other', execa));49test('Cannot use killSignal: 0', () => testInvalidKillSignal(0, 'zero', execa));50test('Cannot use killSignal: "SIGOTHER", sync', () => testInvalidKillSignal('SIGOTHER', 'string', execaSync));51test('Cannot use killSignal: "Sigterm", sync', () => testInvalidKillSignal('Sigterm', 'rename', execaSync));52test('Cannot use killSignal: "sigterm", sync', () => testInvalidKillSignal('sigterm', 'rename', execaSync));53test('Cannot use killSignal: -1, sync', () => testInvalidKillSignal(-1, 'integer', execaSync));54test('Cannot use killSignal: 200, sync', () => testInvalidKillSignal(200, 'integer', execaSync));55test('Cannot use killSignal: 1.5, sync', () => testInvalidKillSignal(1.5, 'other', execaSync));56test('Cannot use killSignal: Infinity, sync', () => testInvalidKillSignal(Infinity, 'other', execaSync));57test('Cannot use killSignal: NaN, sync', () => testInvalidKillSignal(NaN, 'other', execaSync));58test('Cannot use killSignal: null, sync', () => testInvalidKillSignal(null, 'other', execaSync));59test('Cannot use killSignal: symbol, sync', () => testInvalidKillSignal(Symbol('test'), 'other', execaSync));60test('Cannot use killSignal: {}, sync', () => testInvalidKillSignal({}, 'other', execaSync));61test('Cannot use killSignal: 0, sync', () => testInvalidKillSignal(0, 'zero', execaSync));6259const testInvalidSignalArgument = async (t, signal, type) => {63const testInvalidSignalArgument = async (signal, type) => {64 const subprocess = execa('empty.js');61 const {message} = t.throws(() => {65 const {message} = assertThrows(() => {66 subprocess.kill(signal);67 });6869 if (type === 'other') {66 t.true(message.includes('must be an error instance or a signal name string/integer'));70 assert.ok(message.includes('must be an error instance or a signal name string/integer'));71 } else {68 t.true(message.includes('Invalid `subprocess.kill()`\'s argument'));69 validateMessage(t, message, type);72 assert.ok(message.includes('Invalid `subprocess.kill()`\'s argument'));73 validateMessage(message, type);74 }7576 await subprocess;77};7875test('Cannot use subprocess.kill("SIGOTHER")', testInvalidSignalArgument, 'SIGOTHER', 'string');76test('Cannot use subprocess.kill("Sigterm")', testInvalidSignalArgument, 'Sigterm', 'rename');77test('Cannot use subprocess.kill("sigterm")', testInvalidSignalArgument, 'sigterm', 'rename');78test('Cannot use subprocess.kill(-1)', testInvalidSignalArgument, -1, 'integer');79test('Cannot use subprocess.kill(200)', testInvalidSignalArgument, 200, 'integer');80test('Cannot use subprocess.kill(1n)', testInvalidSignalArgument, 1n, 'other');81test('Cannot use subprocess.kill(1.5)', testInvalidSignalArgument, 1.5, 'other');82test('Cannot use subprocess.kill(Infinity)', testInvalidSignalArgument, Infinity, 'other');83test('Cannot use subprocess.kill(NaN)', testInvalidSignalArgument, NaN, 'other');84test('Cannot use subprocess.kill(false)', testInvalidSignalArgument, false, 'other');85test('Cannot use subprocess.kill(null)', testInvalidSignalArgument, null, 'other');86test('Cannot use subprocess.kill(symbol)', testInvalidSignalArgument, Symbol('test'), 'other');87test('Cannot use subprocess.kill({})', testInvalidSignalArgument, {}, 'other');79test('Cannot use subprocess.kill("SIGOTHER")', () => testInvalidSignalArgument('SIGOTHER', 'string'));80test('Cannot use subprocess.kill("Sigterm")', () => testInvalidSignalArgument('Sigterm', 'rename'));81test('Cannot use subprocess.kill("sigterm")', () => testInvalidSignalArgument('sigterm', 'rename'));82test('Cannot use subprocess.kill(-1)', () => testInvalidSignalArgument(-1, 'integer'));83test('Cannot use subprocess.kill(200)', () => testInvalidSignalArgument(200, 'integer'));84test('Cannot use subprocess.kill(1n)', () => testInvalidSignalArgument(1n, 'other'));85test('Cannot use subprocess.kill(1.5)', () => testInvalidSignalArgument(1.5, 'other'));86test('Cannot use subprocess.kill(Infinity)', () => testInvalidSignalArgument(Infinity, 'other'));87test('Cannot use subprocess.kill(NaN)', () => testInvalidSignalArgument(NaN, 'other'));88test('Cannot use subprocess.kill(false)', () => testInvalidSignalArgument(false, 'other'));89test('Cannot use subprocess.kill(null)', () => testInvalidSignalArgument(null, 'other'));90test('Cannot use subprocess.kill(symbol)', () => testInvalidSignalArgument(Symbol('test'), 'other'));91test('Cannot use subprocess.kill({})', () => testInvalidSignalArgument({}, 'other'));
modified:test/terminate/timeout.js+42 added-40 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {assertThrows, assertRejects} from '../helpers/assert.js';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';67setFixtureDirectory();87test('timeout kills the subprocess if it times out', async t => {8 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throwsAsync(execa('forever.js', {timeout: 1}));9 t.true(isTerminated);10 t.is(signal, 'SIGTERM');11 t.true(timedOut);12 t.is(originalMessage, undefined);13 t.is(shortMessage, 'Command timed out after 1 milliseconds: forever.js');14 t.is(message, shortMessage);9test('timeout kills the subprocess if it times out', async () => {10 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await assertRejects(execa('forever.js', {timeout: 1}));11 assert.equal(isTerminated, true);12 assert.equal(signal, 'SIGTERM');13 assert.equal(timedOut, true);14 assert.equal(originalMessage, undefined);15 assert.equal(shortMessage, 'Command timed out after 1 milliseconds: forever.js');16 assert.equal(message, shortMessage);17});1817test('timeout kills the subprocess if it times out, in sync mode', async t => {18 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throws(() => {19test('timeout kills the subprocess if it times out, in sync mode', async () => {20 const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await assertThrows(() => {21 execaSync('node', ['forever.js'], {timeout: 1, cwd: FIXTURES_DIRECTORY});22 });21 t.true(isTerminated);22 t.is(signal, 'SIGTERM');23 t.true(timedOut);23 assert.equal(isTerminated, true);24 assert.equal(signal, 'SIGTERM');25 assert.equal(timedOut, true);26 // On Windows, the command is spawned using the absolute path resolved via `PATHEXT`, so it appears in Node.js' own error message25 t.regex(originalMessage, /^spawnSync .*node(?:\.[A-Za-z]+)? ETIMEDOUT$/);26 t.is(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);27 t.is(message, shortMessage);27 assert.match(originalMessage, /^spawnSync .*node(?:\.[A-Za-z]+)? ETIMEDOUT$/);28 assert.equal(shortMessage, `Command timed out after 1 milliseconds: node forever.js\n${originalMessage}`);29 assert.equal(message, shortMessage);30});3130test('timeout does not kill the subprocess if it does not time out', async t => {32test('timeout does not kill the subprocess if it does not time out', async () => {33 const {timedOut} = await execa('delay.js', ['500'], {timeout: 1e8});32 t.false(timedOut);34 assert.equal(timedOut, false);35});3635test('timeout uses killSignal', async t => {36 const {isTerminated, signal, timedOut} = await t.throwsAsync(execa('forever.js', {timeout: 1, killSignal: 'SIGINT'}));37 t.true(isTerminated);38 t.is(signal, 'SIGINT');39 t.true(timedOut);37test('timeout uses killSignal', async () => {38 const {isTerminated, signal, timedOut} = await assertRejects(execa('forever.js', {timeout: 1, killSignal: 'SIGINT'}));39 assert.equal(isTerminated, true);40 assert.equal(signal, 'SIGINT');41 assert.equal(timedOut, true);42});4344const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;4544const testTimeoutValidation = (t, timeout, execaMethod) => {45 t.throws(() => {46const testTimeoutValidation = (timeout, execaMethod) => {47 assertThrows(() => {48 execaMethod('empty.js', {timeout});49 }, {message: INVALID_TIMEOUT_REGEXP});50};5150test('timeout must not be negative', testTimeoutValidation, -1, execa);51test('timeout must be an integer', testTimeoutValidation, false, execa);52test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);53test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);52test('timeout must not be negative', () => testTimeoutValidation(-1, execa));53test('timeout must be an integer', () => testTimeoutValidation(false, execa));54test('timeout must not be negative - sync', () => testTimeoutValidation(-1, execaSync));55test('timeout must be an integer - sync', () => testTimeoutValidation(false, execaSync));5655test('timedOut is false if timeout is undefined', async t => {57test('timedOut is false if timeout is undefined', async () => {58 const {timedOut} = await execa('noop.js');57 t.false(timedOut);59 assert.equal(timedOut, false);60});6160test('timedOut is false if timeout is 0', async t => {62test('timedOut is false if timeout is 0', async () => {63 const {timedOut} = await execa('noop.js', {timeout: 0});62 t.false(timedOut);64 assert.equal(timedOut, false);65});6665test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', t => {67test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', () => {68 const {timedOut} = execaSync('noop.js');67 t.false(timedOut);69 assert.equal(timedOut, false);70});7170test('timedOut is false if the timeout happened after a different error occurred', async t => {72test('timedOut is false if the timeout happened after a different error occurred', async () => {73 const subprocess = execa('forever.js', {timeout: 1e3});74 const cause = new Error('test');75 subprocess.nodeChildProcess.emit('error', cause);74 const error = await t.throwsAsync(subprocess);75 t.is(error.cause, cause);76 t.false(error.timedOut);76 const error = await assertRejects(subprocess);77 assert.equal(error.cause, cause);78 assert.equal(error.timedOut, false);79});
modified:test/transform/encoding-final.js+84 added-84 removed
1import assert from 'node:assert/strict';2import {Buffer} from 'node:buffer';3import {exec} from 'node:child_process';4import {promisify} from 'node:util';4import test from 'ava';5import test from 'node:test';6import getStream from 'get-stream';7import {execa, execaSync} from '../../index.js';8import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';9import {fullStdio} from '../helpers/stdio.js';
2 unmodified lines
12const pExec = promisify(exec);1314setFixtureDirectory();1515const checkEncoding = async (t, encoding, fdNumber, execaMethod) => {16const checkEncoding = async (encoding, fdNumber, execaMethod) => {17 const {stdio} = await execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding});17 compareValues(t, stdio[fdNumber], encoding);18 compareValues(stdio[fdNumber], encoding);1920 if (execaMethod !== execaSync) {21 const subprocess = execaMethod('noop-fd.js', [`${fdNumber}`, STRING_TO_ENCODE], {...fullStdio, encoding});22 const result = await getStream(subprocess.stdio[fdNumber]);22 compareValues(t, result, 'utf8');23 compareValues(result, 'utf8');24 await subprocess;25 }2627 if (fdNumber === 3) {28 return;29 }3031 const {stdout, stderr} = await pExec(`node noop-fd.js ${fdNumber} ${STRING_TO_ENCODE}`, {encoding, cwd: FIXTURES_DIRECTORY});31 compareValues(t, fdNumber === 1 ? stdout : stderr, encoding);32 compareValues(fdNumber === 1 ? stdout : stderr, encoding);33};3434const compareValues = (t, value, encoding) => {35const compareValues = (value, encoding) => {36 if (encoding === 'buffer') {36 t.true(ArrayBuffer.isView(value));37 t.true(BUFFER_TO_ENCODE.equals(value));37 assert.ok(ArrayBuffer.isView(value));38 assert.ok(BUFFER_TO_ENCODE.equals(value));39 } else {39 t.is(value, BUFFER_TO_ENCODE.toString(encoding));40 assert.equal(value, BUFFER_TO_ENCODE.toString(encoding));41 }42};4344// This string gives different outputs with each encoding type45const STRING_TO_ENCODE = '\u{1000}.';46const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);4747test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);48test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);49test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);50test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);51test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);52test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);53test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);54test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);55test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);56test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);57test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);58test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);59test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);60test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);61test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);62test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);63test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);64test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);65test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);66test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);67test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);68test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);69test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);70test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);71test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);72test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);73test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);74test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);75test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);76test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);77test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);78test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);79test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);80test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);81test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);82test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);83test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);84test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);85test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);86test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);87test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);88test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);89test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);90test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);91test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);92test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);93test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);94test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);48test('can pass encoding "buffer" to stdout', () => checkEncoding('buffer', 1, execa));49test('can pass encoding "utf8" to stdout', () => checkEncoding('utf8', 1, execa));50test('can pass encoding "utf16le" to stdout', () => checkEncoding('utf16le', 1, execa));51test('can pass encoding "latin1" to stdout', () => checkEncoding('latin1', 1, execa));52test('can pass encoding "ascii" to stdout', () => checkEncoding('ascii', 1, execa));53test('can pass encoding "hex" to stdout', () => checkEncoding('hex', 1, execa));54test('can pass encoding "base64" to stdout', () => checkEncoding('base64', 1, execa));55test('can pass encoding "base64url" to stdout', () => checkEncoding('base64url', 1, execa));56test('can pass encoding "buffer" to stderr', () => checkEncoding('buffer', 2, execa));57test('can pass encoding "utf8" to stderr', () => checkEncoding('utf8', 2, execa));58test('can pass encoding "utf16le" to stderr', () => checkEncoding('utf16le', 2, execa));59test('can pass encoding "latin1" to stderr', () => checkEncoding('latin1', 2, execa));60test('can pass encoding "ascii" to stderr', () => checkEncoding('ascii', 2, execa));61test('can pass encoding "hex" to stderr', () => checkEncoding('hex', 2, execa));62test('can pass encoding "base64" to stderr', () => checkEncoding('base64', 2, execa));63test('can pass encoding "base64url" to stderr', () => checkEncoding('base64url', 2, execa));64test('can pass encoding "buffer" to stdio[*]', () => checkEncoding('buffer', 3, execa));65test('can pass encoding "utf8" to stdio[*]', () => checkEncoding('utf8', 3, execa));66test('can pass encoding "utf16le" to stdio[*]', () => checkEncoding('utf16le', 3, execa));67test('can pass encoding "latin1" to stdio[*]', () => checkEncoding('latin1', 3, execa));68test('can pass encoding "ascii" to stdio[*]', () => checkEncoding('ascii', 3, execa));69test('can pass encoding "hex" to stdio[*]', () => checkEncoding('hex', 3, execa));70test('can pass encoding "base64" to stdio[*]', () => checkEncoding('base64', 3, execa));71test('can pass encoding "base64url" to stdio[*]', () => checkEncoding('base64url', 3, execa));72test('can pass encoding "buffer" to stdout - sync', () => checkEncoding('buffer', 1, execaSync));73test('can pass encoding "utf8" to stdout - sync', () => checkEncoding('utf8', 1, execaSync));74test('can pass encoding "utf16le" to stdout - sync', () => checkEncoding('utf16le', 1, execaSync));75test('can pass encoding "latin1" to stdout - sync', () => checkEncoding('latin1', 1, execaSync));76test('can pass encoding "ascii" to stdout - sync', () => checkEncoding('ascii', 1, execaSync));77test('can pass encoding "hex" to stdout - sync', () => checkEncoding('hex', 1, execaSync));78test('can pass encoding "base64" to stdout - sync', () => checkEncoding('base64', 1, execaSync));79test('can pass encoding "base64url" to stdout - sync', () => checkEncoding('base64url', 1, execaSync));80test('can pass encoding "buffer" to stderr - sync', () => checkEncoding('buffer', 2, execaSync));81test('can pass encoding "utf8" to stderr - sync', () => checkEncoding('utf8', 2, execaSync));82test('can pass encoding "utf16le" to stderr - sync', () => checkEncoding('utf16le', 2, execaSync));83test('can pass encoding "latin1" to stderr - sync', () => checkEncoding('latin1', 2, execaSync));84test('can pass encoding "ascii" to stderr - sync', () => checkEncoding('ascii', 2, execaSync));85test('can pass encoding "hex" to stderr - sync', () => checkEncoding('hex', 2, execaSync));86test('can pass encoding "base64" to stderr - sync', () => checkEncoding('base64', 2, execaSync));87test('can pass encoding "base64url" to stderr - sync', () => checkEncoding('base64url', 2, execaSync));88test('can pass encoding "buffer" to stdio[*] - sync', () => checkEncoding('buffer', 3, execaSync));89test('can pass encoding "utf8" to stdio[*] - sync', () => checkEncoding('utf8', 3, execaSync));90test('can pass encoding "utf16le" to stdio[*] - sync', () => checkEncoding('utf16le', 3, execaSync));91test('can pass encoding "latin1" to stdio[*] - sync', () => checkEncoding('latin1', 3, execaSync));92test('can pass encoding "ascii" to stdio[*] - sync', () => checkEncoding('ascii', 3, execaSync));93test('can pass encoding "hex" to stdio[*] - sync', () => checkEncoding('hex', 3, execaSync));94test('can pass encoding "base64" to stdio[*] - sync', () => checkEncoding('base64', 3, execaSync));95test('can pass encoding "base64url" to stdio[*] - sync', () => checkEncoding('base64url', 3, execaSync));9696// eslint-disable-next-line max-params97const testEncodingInput = async (t, input, expectedStdout, encoding, execaMethod) => {97const testEncodingInput = async (input, expectedStdout, encoding, execaMethod) => {98 const {stdout} = await execaMethod('stdin.js', {input, encoding});99 t.deepEqual(stdout, expectedStdout);99 assert.deepEqual(stdout, expectedStdout);100};101102test('Can use string input', testEncodingInput, foobarString, foobarString, 'utf8', execa);103test('Can use Uint8Array input', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execa);104test('Can use string input, encoding "buffer"', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execa);105test('Can use Uint8Array input, encoding "buffer"', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execa);106test('Can use string input, encoding "hex"', testEncodingInput, foobarString, foobarHex, 'hex', execa);107test('Can use Uint8Array input, encoding "hex"', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execa);108test('Can use string input, sync', testEncodingInput, foobarString, foobarString, 'utf8', execaSync);109test('Can use Uint8Array input, sync', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execaSync);110test('Can use string input, encoding "buffer", sync', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execaSync);111test('Can use Uint8Array input, encoding "buffer", sync', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execaSync);112test('Can use string input, encoding "hex", sync', testEncodingInput, foobarString, foobarHex, 'hex', execaSync);113test('Can use Uint8Array input, encoding "hex", sync', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execaSync);102test('Can use string input', () => testEncodingInput(foobarString, foobarString, 'utf8', execa));103test('Can use Uint8Array input', () => testEncodingInput(foobarUint8Array, foobarString, 'utf8', execa));104test('Can use string input, encoding "buffer"', () => testEncodingInput(foobarString, foobarUint8Array, 'buffer', execa));105test('Can use Uint8Array input, encoding "buffer"', () => testEncodingInput(foobarUint8Array, foobarUint8Array, 'buffer', execa));106test('Can use string input, encoding "hex"', () => testEncodingInput(foobarString, foobarHex, 'hex', execa));107test('Can use Uint8Array input, encoding "hex"', () => testEncodingInput(foobarUint8Array, foobarHex, 'hex', execa));108test('Can use string input, sync', () => testEncodingInput(foobarString, foobarString, 'utf8', execaSync));109test('Can use Uint8Array input, sync', () => testEncodingInput(foobarUint8Array, foobarString, 'utf8', execaSync));110test('Can use string input, encoding "buffer", sync', () => testEncodingInput(foobarString, foobarUint8Array, 'buffer', execaSync));111test('Can use Uint8Array input, encoding "buffer", sync', () => testEncodingInput(foobarUint8Array, foobarUint8Array, 'buffer', execaSync));112test('Can use string input, encoding "hex", sync', () => testEncodingInput(foobarString, foobarHex, 'hex', execaSync));113test('Can use Uint8Array input, encoding "hex", sync', () => testEncodingInput(foobarUint8Array, foobarHex, 'hex', execaSync));114115const testSubprocessEncoding = (t, encoding) => {115const testSubprocessEncoding = encoding => {116 const subprocess = execa('empty.js', {...fullStdio, encoding});117 t.is(subprocess.stdout.readableEncoding, null);118 t.is(subprocess.stderr.readableEncoding, null);119 t.is(subprocess.stdio[3].readableEncoding, null);117 assert.equal(subprocess.stdout.readableEncoding, null);118 assert.equal(subprocess.stderr.readableEncoding, null);119 assert.equal(subprocess.stdio[3].readableEncoding, null);120};121122test('Does not modify subprocess.std* encoding, "utf8"', testSubprocessEncoding, 'utf8');123test('Does not modify subprocess.std* encoding, "utf16le"', testSubprocessEncoding, 'utf16le');124test('Does not modify subprocess.std* encoding, "buffer"', testSubprocessEncoding, 'buffer');125test('Does not modify subprocess.std* encoding, "hex"', testSubprocessEncoding, 'hex');126test('Does not modify subprocess.std* encoding, "base64"', testSubprocessEncoding, 'base64');127test('Does not modify subprocess.std* encoding, "base64url"', testSubprocessEncoding, 'base64url');128test('Does not modify subprocess.std* encoding, "latin1"', testSubprocessEncoding, 'latin1');129test('Does not modify subprocess.std* encoding, "ascii"', testSubprocessEncoding, 'ascii');122test('Does not modify subprocess.std* encoding, "utf8"', () => testSubprocessEncoding('utf8'));123test('Does not modify subprocess.std* encoding, "utf16le"', () => testSubprocessEncoding('utf16le'));124test('Does not modify subprocess.std* encoding, "buffer"', () => testSubprocessEncoding('buffer'));125test('Does not modify subprocess.std* encoding, "hex"', () => testSubprocessEncoding('hex'));126test('Does not modify subprocess.std* encoding, "base64"', () => testSubprocessEncoding('base64'));127test('Does not modify subprocess.std* encoding, "base64url"', () => testSubprocessEncoding('base64url'));128test('Does not modify subprocess.std* encoding, "latin1"', () => testSubprocessEncoding('latin1'));129test('Does not modify subprocess.std* encoding, "ascii"', () => testSubprocessEncoding('ascii'));
modified:test/transform/encoding-ignored.js+68 added-68 removed
1import assert from 'node:assert/strict';2import process from 'node:process';2import test from 'ava';3import test from 'node:test';4import {execa, execaSync} from '../../index.js';5import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6import {outputObjectGenerator, addNoopGenerator} from '../helpers/generator.js';7import {foobarObject} from '../helpers/input.js';89setFixtureDirectory();1010const testObjectMode = async (t, addNoopTransform, execaMethod) => {11const testObjectMode = async (addNoopTransform, execaMethod) => {12 const {stdout} = await execaMethod('noop.js', {13 stdout: addNoopGenerator(outputObjectGenerator(), addNoopTransform, true),14 encoding: 'base64',15 });15 t.deepEqual(stdout, [foobarObject]);16 assert.deepEqual(stdout, [foobarObject]);17};1818test('Other encodings work with transforms that return objects', testObjectMode, false, execa);19test('Other encodings work with transforms that return objects, noop transform', testObjectMode, true, execa);20test('Other encodings work with transforms that return objects, sync', testObjectMode, false, execaSync);21test('Other encodings work with transforms that return objects, noop transform, sync', testObjectMode, true, execaSync);19test('Other encodings work with transforms that return objects', () => testObjectMode(false, execa));20test('Other encodings work with transforms that return objects, noop transform', () => testObjectMode(true, execa));21test('Other encodings work with transforms that return objects, sync', () => testObjectMode(false, execaSync));22test('Other encodings work with transforms that return objects, noop transform, sync', () => testObjectMode(true, execaSync));2323// eslint-disable-next-line max-params24const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options, execaMethod) => {24const testIgnoredEncoding = async (stdoutOption, isUndefined, options, execaMethod) => {25 const {stdout} = await execaMethod('empty.js', {stdout: stdoutOption, ...options});26 t.is(stdout === undefined, isUndefined);26 assert.equal(stdout === undefined, isUndefined);27};2829const base64Options = {encoding: 'base64'};30const linesOptions = {lines: true};31test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options, execa);32test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options, execa);33test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options, execa);34test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options, execa);35test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options, execa);36test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options, execa);37test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options, execa);38test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options, execa);39test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options, execa);40test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options, execa);41test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options, execa);42test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options, execa);43test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options, execa);44test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options, execa);45test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options, execa);46test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions, execa);47test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions, execa);48test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions, execa);49test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions, execa);50test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions, execa);51test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions, execa);52test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions, execa);53test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions, execa);54test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions, execa);55test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions, execa);56test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions, execa);57test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions, execa);58test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions, execa);59test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions, execa);60test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions, execa);61test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execa);62test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execa);63test('Is ignored with other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, base64Options, execaSync);64test('Is ignored with other encodings and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, base64Options, execaSync);65test('Is ignored with other encodings and "inherit", sync', testIgnoredEncoding, 'inherit', true, base64Options, execaSync);66test('Is ignored with other encodings and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, base64Options, execaSync);67test('Is ignored with other encodings and 1, sync', testIgnoredEncoding, 1, true, base64Options, execaSync);68test('Is ignored with other encodings and [1], sync', testIgnoredEncoding, [1], true, base64Options, execaSync);69test('Is ignored with other encodings and process.stdout, sync', testIgnoredEncoding, process.stdout, true, base64Options, execaSync);70test('Is ignored with other encodings and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, base64Options, execaSync);71test('Is not ignored with other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, base64Options, execaSync);72test('Is not ignored with other encodings and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, base64Options, execaSync);73test('Is not ignored with other encodings and undefined, sync', testIgnoredEncoding, undefined, false, base64Options, execaSync);74test('Is not ignored with other encodings and null, sync', testIgnoredEncoding, null, false, base64Options, execaSync);75test('Is ignored with "lines: true" and "ignore", sync', testIgnoredEncoding, 'ignore', true, linesOptions, execaSync);76test('Is ignored with "lines: true" and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, linesOptions, execaSync);77test('Is ignored with "lines: true" and "inherit", sync', testIgnoredEncoding, 'inherit', true, linesOptions, execaSync);78test('Is ignored with "lines: true" and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, linesOptions, execaSync);79test('Is ignored with "lines: true" and 1, sync', testIgnoredEncoding, 1, true, linesOptions, execaSync);80test('Is ignored with "lines: true" and [1], sync', testIgnoredEncoding, [1], true, linesOptions, execaSync);81test('Is ignored with "lines: true" and process.stdout, sync', testIgnoredEncoding, process.stdout, true, linesOptions, execaSync);82test('Is ignored with "lines: true" and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, linesOptions, execaSync);83test('Is not ignored with "lines: true" and "pipe", sync', testIgnoredEncoding, 'pipe', false, linesOptions, execaSync);84test('Is not ignored with "lines: true" and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, linesOptions, execaSync);85test('Is not ignored with "lines: true" and undefined, sync', testIgnoredEncoding, undefined, false, linesOptions, execaSync);86test('Is not ignored with "lines: true" and null, sync', testIgnoredEncoding, null, false, linesOptions, execaSync);87test('Is ignored with "lines: true", other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execaSync);88test('Is not ignored with "lines: true", other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execaSync);31test('Is ignored with other encodings and "ignore"', () => testIgnoredEncoding('ignore', true, base64Options, execa));32test('Is ignored with other encodings and ["ignore"]', () => testIgnoredEncoding(['ignore'], true, base64Options, execa));33test('Is ignored with other encodings and "inherit"', () => testIgnoredEncoding('inherit', true, base64Options, execa));34test('Is ignored with other encodings and ["inherit"]', () => testIgnoredEncoding(['inherit'], true, base64Options, execa));35test('Is ignored with other encodings and 1', () => testIgnoredEncoding(1, true, base64Options, execa));36test('Is ignored with other encodings and [1]', () => testIgnoredEncoding([1], true, base64Options, execa));37test('Is ignored with other encodings and process.stdout', () => testIgnoredEncoding(process.stdout, true, base64Options, execa));38test('Is ignored with other encodings and [process.stdout]', () => testIgnoredEncoding([process.stdout], true, base64Options, execa));39test('Is not ignored with other encodings and "pipe"', () => testIgnoredEncoding('pipe', false, base64Options, execa));40test('Is not ignored with other encodings and ["pipe"]', () => testIgnoredEncoding(['pipe'], false, base64Options, execa));41test('Is not ignored with other encodings and "overlapped"', () => testIgnoredEncoding('overlapped', false, base64Options, execa));42test('Is not ignored with other encodings and ["overlapped"]', () => testIgnoredEncoding(['overlapped'], false, base64Options, execa));43test('Is not ignored with other encodings and ["inherit", "pipe"]', () => testIgnoredEncoding(['inherit', 'pipe'], false, base64Options, execa));44test('Is not ignored with other encodings and undefined', () => testIgnoredEncoding(undefined, false, base64Options, execa));45test('Is not ignored with other encodings and null', () => testIgnoredEncoding(null, false, base64Options, execa));46test('Is ignored with "lines: true" and "ignore"', () => testIgnoredEncoding('ignore', true, linesOptions, execa));47test('Is ignored with "lines: true" and ["ignore"]', () => testIgnoredEncoding(['ignore'], true, linesOptions, execa));48test('Is ignored with "lines: true" and "inherit"', () => testIgnoredEncoding('inherit', true, linesOptions, execa));49test('Is ignored with "lines: true" and ["inherit"]', () => testIgnoredEncoding(['inherit'], true, linesOptions, execa));50test('Is ignored with "lines: true" and 1', () => testIgnoredEncoding(1, true, linesOptions, execa));51test('Is ignored with "lines: true" and [1]', () => testIgnoredEncoding([1], true, linesOptions, execa));52test('Is ignored with "lines: true" and process.stdout', () => testIgnoredEncoding(process.stdout, true, linesOptions, execa));53test('Is ignored with "lines: true" and [process.stdout]', () => testIgnoredEncoding([process.stdout], true, linesOptions, execa));54test('Is not ignored with "lines: true" and "pipe"', () => testIgnoredEncoding('pipe', false, linesOptions, execa));55test('Is not ignored with "lines: true" and ["pipe"]', () => testIgnoredEncoding(['pipe'], false, linesOptions, execa));56test('Is not ignored with "lines: true" and "overlapped"', () => testIgnoredEncoding('overlapped', false, linesOptions, execa));57test('Is not ignored with "lines: true" and ["overlapped"]', () => testIgnoredEncoding(['overlapped'], false, linesOptions, execa));58test('Is not ignored with "lines: true" and ["inherit", "pipe"]', () => testIgnoredEncoding(['inherit', 'pipe'], false, linesOptions, execa));59test('Is not ignored with "lines: true" and undefined', () => testIgnoredEncoding(undefined, false, linesOptions, execa));60test('Is not ignored with "lines: true" and null', () => testIgnoredEncoding(null, false, linesOptions, execa));61test('Is ignored with "lines: true", other encodings and "ignore"', () => testIgnoredEncoding('ignore', true, {...base64Options, ...linesOptions}, execa));62test('Is not ignored with "lines: true", other encodings and "pipe"', () => testIgnoredEncoding('pipe', false, {...base64Options, ...linesOptions}, execa));63test('Is ignored with other encodings and "ignore", sync', () => testIgnoredEncoding('ignore', true, base64Options, execaSync));64test('Is ignored with other encodings and ["ignore"], sync', () => testIgnoredEncoding(['ignore'], true, base64Options, execaSync));65test('Is ignored with other encodings and "inherit", sync', () => testIgnoredEncoding('inherit', true, base64Options, execaSync));66test('Is ignored with other encodings and ["inherit"], sync', () => testIgnoredEncoding(['inherit'], true, base64Options, execaSync));67test('Is ignored with other encodings and 1, sync', () => testIgnoredEncoding(1, true, base64Options, execaSync));68test('Is ignored with other encodings and [1], sync', () => testIgnoredEncoding([1], true, base64Options, execaSync));69test('Is ignored with other encodings and process.stdout, sync', () => testIgnoredEncoding(process.stdout, true, base64Options, execaSync));70test('Is ignored with other encodings and [process.stdout], sync', () => testIgnoredEncoding([process.stdout], true, base64Options, execaSync));71test('Is not ignored with other encodings and "pipe", sync', () => testIgnoredEncoding('pipe', false, base64Options, execaSync));72test('Is not ignored with other encodings and ["pipe"], sync', () => testIgnoredEncoding(['pipe'], false, base64Options, execaSync));73test('Is not ignored with other encodings and undefined, sync', () => testIgnoredEncoding(undefined, false, base64Options, execaSync));74test('Is not ignored with other encodings and null, sync', () => testIgnoredEncoding(null, false, base64Options, execaSync));75test('Is ignored with "lines: true" and "ignore", sync', () => testIgnoredEncoding('ignore', true, linesOptions, execaSync));76test('Is ignored with "lines: true" and ["ignore"], sync', () => testIgnoredEncoding(['ignore'], true, linesOptions, execaSync));77test('Is ignored with "lines: true" and "inherit", sync', () => testIgnoredEncoding('inherit', true, linesOptions, execaSync));78test('Is ignored with "lines: true" and ["inherit"], sync', () => testIgnoredEncoding(['inherit'], true, linesOptions, execaSync));79test('Is ignored with "lines: true" and 1, sync', () => testIgnoredEncoding(1, true, linesOptions, execaSync));80test('Is ignored with "lines: true" and [1], sync', () => testIgnoredEncoding([1], true, linesOptions, execaSync));81test('Is ignored with "lines: true" and process.stdout, sync', () => testIgnoredEncoding(process.stdout, true, linesOptions, execaSync));82test('Is ignored with "lines: true" and [process.stdout], sync', () => testIgnoredEncoding([process.stdout], true, linesOptions, execaSync));83test('Is not ignored with "lines: true" and "pipe", sync', () => testIgnoredEncoding('pipe', false, linesOptions, execaSync));84test('Is not ignored with "lines: true" and ["pipe"], sync', () => testIgnoredEncoding(['pipe'], false, linesOptions, execaSync));85test('Is not ignored with "lines: true" and undefined, sync', () => testIgnoredEncoding(undefined, false, linesOptions, execaSync));86test('Is not ignored with "lines: true" and null, sync', () => testIgnoredEncoding(null, false, linesOptions, execaSync));87test('Is ignored with "lines: true", other encodings and "ignore", sync', () => testIgnoredEncoding('ignore', true, {...base64Options, ...linesOptions}, execaSync));88test('Is not ignored with "lines: true", other encodings and "pipe", sync', () => testIgnoredEncoding('pipe', false, {...base64Options, ...linesOptions}, execaSync));
modified:test/transform/encoding-multibyte.js+29 added-28 removed
1import test from 'ava';1import assert from 'node:assert/strict';2import test from 'node:test';3import {execa, execaSync} from '../../index.js';4import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5import {noopGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';6import {
7 unmodified lines
14setFixtureDirectory();1516const foobarArray = ['fo', 'ob', 'ar', '..'];1717const testMultibyteCharacters = async (t, objectMode, addNoopTransform, execaMethod) => {18const testMultibyteCharacters = async (objectMode, addNoopTransform, execaMethod) => {19 const {stdout} = await execaMethod('noop.js', {20 stdout: addNoopGenerator(getOutputsGenerator(foobarArray)(objectMode, true), addNoopTransform, objectMode),21 encoding: 'base64',22 });23 if (objectMode) {23 t.deepEqual(stdout, foobarArray);24 assert.deepEqual(stdout, foobarArray);25 } else {26 // eslint-disable-next-line n/prefer-global/buffer -- `Uint8Array#toBase64()` is not available on the minimum supported Node.js version26 t.is(stdout, Buffer.from(foobarArray.join('')).toString('base64'));27 assert.equal(stdout, Buffer.from(foobarArray.join('')).toString('base64'));28 }29};3030test('Handle multibyte characters', testMultibyteCharacters, false, false, execa);31test('Handle multibyte characters, noop transform', testMultibyteCharacters, false, true, execa);32test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false, execa);33test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true, execa);34test('Handle multibyte characters, sync', testMultibyteCharacters, false, false, execaSync);35test('Handle multibyte characters, noop transform, sync', testMultibyteCharacters, false, true, execaSync);36test('Handle multibyte characters, with objectMode, sync', testMultibyteCharacters, true, false, execaSync);37test('Handle multibyte characters, with objectMode, noop transform, sync', testMultibyteCharacters, true, true, execaSync);31test('Handle multibyte characters', () => testMultibyteCharacters(false, false, execa));32test('Handle multibyte characters, noop transform', () => testMultibyteCharacters(false, true, execa));33test('Handle multibyte characters, with objectMode', () => testMultibyteCharacters(true, false, execa));34test('Handle multibyte characters, with objectMode, noop transform', () => testMultibyteCharacters(true, true, execa));35test('Handle multibyte characters, sync', () => testMultibyteCharacters(false, false, execaSync));36test('Handle multibyte characters, noop transform, sync', () => testMultibyteCharacters(false, true, execaSync));37test('Handle multibyte characters, with objectMode, sync', () => testMultibyteCharacters(true, false, execaSync));38test('Handle multibyte characters, with objectMode, noop transform, sync', () => testMultibyteCharacters(true, true, execaSync));3939const testMultibyte = async (t, objectMode, execaMethod) => {40const testMultibyte = async (objectMode, execaMethod) => {41 const {stdout} = await execaMethod('stdin.js', {42 stdin: [43 [multibyteUint8Array.slice(0, breakingLength), multibyteUint8Array.slice(breakingLength)],44 noopGenerator(objectMode, true),45 ],46 });46 t.is(stdout, multibyteString);47 assert.equal(stdout, multibyteString);48};4949test('Generator handles multibyte characters with Uint8Array', testMultibyte, false, execa);50test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true, execa);51test('Generator handles multibyte characters with Uint8Array, sync', testMultibyte, false, execaSync);52test('Generator handles multibyte characters with Uint8Array, objectMode, sync', testMultibyte, true, execaSync);50test('Generator handles multibyte characters with Uint8Array', () => testMultibyte(false, execa));51test('Generator handles multibyte characters with Uint8Array, objectMode', () => testMultibyte(true, execa));52test('Generator handles multibyte characters with Uint8Array, sync', () => testMultibyte(false, execaSync));53test('Generator handles multibyte characters with Uint8Array, objectMode, sync', () => testMultibyte(true, execaSync));5454const testMultibytePartial = async (t, objectMode, execaMethod) => {55const testMultibytePartial = async (objectMode, execaMethod) => {56 const {stdout} = await execaMethod('stdin.js', {57 stdin: [58 [multibyteUint8Array.slice(0, breakingLength)],59 noopGenerator(objectMode, true),60 ],61 });61 t.is(stdout, `${multibyteChar}${brokenSymbol}`);62 assert.equal(stdout, `${multibyteChar}${brokenSymbol}`);63};6464test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false, execa);65test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true, execa);66test('Generator handles partial multibyte characters with Uint8Array, sync', testMultibytePartial, false, execaSync);67test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', testMultibytePartial, true, execaSync);65test('Generator handles partial multibyte characters with Uint8Array', () => testMultibytePartial(false, execa));66test('Generator handles partial multibyte characters with Uint8Array, objectMode', () => testMultibytePartial(true, execa));67test('Generator handles partial multibyte characters with Uint8Array, sync', () => testMultibytePartial(false, execaSync));68test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', () => testMultibytePartial(true, execaSync));6969const testMultibytePartialOutput = async (t, execaMethod) => {70const testMultibytePartialOutput = async execaMethod => {71 const {stdout} = await execaMethod('noop.js', {72 stdout: getOutputsGenerator([73 multibyteUint8Array.slice(0, breakingLength),74 multibyteUint8Array.slice(breakingLength),75 ])(false, true),76 });76 t.is(stdout, multibyteString);77 assert.equal(stdout, multibyteString);78};7979test('Generator handles output multibyte characters with Uint8Array', testMultibytePartialOutput, execa);80test('Generator handles output multibyte characters with Uint8Array, sync', testMultibytePartialOutput, execaSync);80test('Generator handles output multibyte characters with Uint8Array', () => testMultibytePartialOutput(execa));81test('Generator handles output multibyte characters with Uint8Array, sync', () => testMultibytePartialOutput(execaSync));
modified:test/transform/encoding-transform.jsnot shown

Its text is not shown, modified.

modified:test/transform/generator-all.jsnot shown

Its text is not shown, modified.

modified:test/transform/generator-error.jsnot shown

Its text is not shown, modified.

modified:test/transform/generator-final.jsnot shown

Its text is not shown, modified.

modified:test/transform/generator-input.jsnot shown

Its text is not shown, modified.

modified:test/transform/generator-main.jsnot shown

Its text is not shown, modified.

modified:test/transform/generator-mixed.jsnot shown

Its text is not shown, modified.

modified:test/transform/generator-output.jsnot shown

Its text is not shown, modified.

modified:test/transform/generator-return.jsnot shown

Its text is not shown, modified.

modified:test/transform/normalize-transform.jsnot shown

Its text is not shown, modified.

modified:test/transform/split-binary.jsnot shown

Its text is not shown, modified.

modified:test/transform/split-lines.jsnot shown

Its text is not shown, modified.

modified:test/transform/split-newline.jsnot shown

Its text is not shown, modified.

modified:test/transform/split-transform.jsnot shown

Its text is not shown, modified.

modified:test/transform/validate.jsnot shown

Its text is not shown, modified.

modified:test/verbose/complete.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-command.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-common.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-complete.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-error.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-event.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-id.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-ipc.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-options.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-output.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-reject.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-result.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-start.jsnot shown

Its text is not shown, modified.

modified:test/verbose/custom-throw.jsnot shown

Its text is not shown, modified.

modified:test/verbose/error.jsnot shown

Its text is not shown, modified.

modified:test/verbose/info.jsnot shown

Its text is not shown, modified.

modified:test/verbose/ipc.jsnot shown

Its text is not shown, modified.

modified:test/verbose/log.jsnot shown

Its text is not shown, modified.

modified:test/verbose/output-buffer.jsnot shown

Its text is not shown, modified.

modified:test/verbose/output-enable.jsnot shown

Its text is not shown, modified.

modified:test/verbose/output-mixed.jsnot shown

Its text is not shown, modified.

modified:test/verbose/output-noop.jsnot shown

Its text is not shown, modified.

modified:test/verbose/output-pipe.jsnot shown

Its text is not shown, modified.

modified:test/verbose/output-progressive.jsnot shown

Its text is not shown, modified.

modified:test/verbose/start.jsnot shown

Its text is not shown, modified.

modified:types/arguments/options.d.tsnot shown

Its text is not shown, modified.

modified:package.json+51 added-48 removed
3 unmodified lines
4 "description": "Process execution for humans",5 "license": "MIT",6 "repository": "sindresorhus/execa",7 "funding": "https://github.com/sindresorhus/execa?sponsor=1",8 "author": {9 "name": "Sindre Sorhus",10 "email": "sindresorhus@gmail.com",11 "url": "https://sindresorhus.com"12 },8 "author": "Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)",9 "type": "module",10 "exports": {11 "types": "./index.d.ts",12 "default": "./index.js"
4 unmodified lines
17 },18 "scripts": {19 "test": "npm run lint && npm run unit && npm run type",20 "lint": "xo",25 "unit": "c8 --merge-async ava",21 "unit": "c8 --merge-async node --test --test-concurrency=1 --test-timeout=240000 \"test/!(fixtures|helpers)/*.js\"",22 "type": "tsd && tsc"23 },24 "files": [25 "index.js",
27 unmodified lines
53 "human-signals": "^8.0.1",54 "is-plain-obj": "^4.1.0",55 "is-stream": "^4.0.1",56 "npm-run-path": "^6.0.0",61 "pretty-ms": "^9.3.0",57 "pretty-ms": "^9.3.1",58 "signal-exit": "^4.1.0",59 "strip-final-newline": "^4.0.0",60 "which-command": "^0.1.0",65 "yoctocolors": "^2.1.2"61 "yoctocolors": "^2.2.0"62 },63 "devDependencies": {68 "@types/node": "^26.1.0",69 "ava": "^8.0.1",70 "c8": "^11.0.0",64 "@types/node": "^26.6.2",65 "c8": "^12.0.0",66 "get-node": "^15.0.4",67 "is-in-ci": "^2.0.0",68 "is-running": "^2.1.0",69 "log-process-errors": "^12.0.1",
1 unmodified line
71 "path-key": "^4.0.0",72 "tempfile": "^6.0.1",73 "tsd": "^0.33.0",74 "typescript": "^6.0.3",80 "xo": "^4.0.0"75 "xo": "^5.0.1"76 },77 "c8": {78 "reporter": [79 "text",
4 unmodified lines
84 "**/test.js",85 "**/test/**"86 ]87 },93 "ava": {94 "workerThreads": false,95 "concurrency": 1,96 "timeout": "240s"97 },98 "xo": {99 "rules": {100 "unicorn/no-empty-file": "off",101 "unicorn/prefer-string-raw": "off",102 "ava/test-title": "off",103 "@typescript-eslint/no-empty-object-type": "off",104 "unicorn/no-useless-template-literals": "off",105 "require-unicode-regexp": "off",106 "ava/no-nested-assertions": "off",107 "@stylistic/max-len": "off",108 "@typescript-eslint/no-unsafe-call": "off",109 "@typescript-eslint/no-unsafe-member-access": "off",110 "@typescript-eslint/no-unsafe-assignment": "off",111 "@typescript-eslint/await-thenable": "off",112 "@typescript-eslint/no-unnecessary-type-assertion": "off",113 "@typescript-eslint/no-restricted-types": "off",114 "no-shadow": "off",115 "unicorn/no-computed-property-existence-check": "off",116 "unicorn/max-nested-calls": "off",117 "markdown/fenced-code-language": "off",118 "unicorn/no-array-sort": "off",119 "unicorn/prefer-minimal-ternary": "off",120 "unicorn/no-array-reverse": "off",121 "unicorn/no-array-from-fill": "off",122 "unicorn/prefer-number-is-safe-integer": "off",123 "unicorn/require-array-sort-compare": "off",124 "@typescript-eslint/ban-types": "off",125 "regexp/strict": "off",126 "unicorn/require-module-specifiers": "off",127 "jsdoc/require-asterisk-prefix": "off"88 "xo": [89 {90 "rules": {91 "unicorn/no-empty-file": "off",92 "unicorn/prefer-string-raw": "off",93 "@typescript-eslint/no-empty-object-type": "off",94 "unicorn/no-useless-template-literals": "off",95 "require-unicode-regexp": "off",96 "@stylistic/max-len": "off",97 "@typescript-eslint/no-unsafe-call": "off",98 "@typescript-eslint/no-unsafe-member-access": "off",99 "@typescript-eslint/no-unsafe-assignment": "off",100 "@typescript-eslint/await-thenable": "off",101 "@typescript-eslint/no-unnecessary-type-assertion": "off",102 "@typescript-eslint/no-restricted-types": "off",103 "no-shadow": "off",104 "unicorn/no-computed-property-existence-check": "off",105 "unicorn/max-nested-calls": "off",106 "unicorn/no-array-sort": "off",107 "unicorn/prefer-minimal-ternary": "off",108 "unicorn/no-array-reverse": "off",109 "unicorn/no-array-from-fill": "off",110 "unicorn/prefer-number-is-safe-integer": "off",111 "unicorn/require-array-sort-compare": "off",112 "@typescript-eslint/ban-types": "off",113 "regexp/strict": "off",114 "unicorn/require-module-specifiers": "off",115 "jsdoc/require-asterisk-prefix": "off",116 "node-test/require-assertion": "off",117 "node-test/no-import-test-files": "off",118 "node-test/no-conditional-tests": "off",119 "node-test/prefer-test-context-assert": "off",120 "node-test/no-process-env-mutation": "off",121 "node-test/no-useless-assertion": "off"122 }123 },124 {125 "files": [126 "**/*.md"127 ],128 "rules": {129 "markdown/fenced-code-language": "off"130 }131 }129 }132 ]133}