Tweaks
Before adoption: this commit came in with the history the project adopted, so no landing records it.
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
Provenance
- Commit
698a1b8- Tree
51857f1- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
8d3f0a9
208 files changed+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 lines891 _Type:_ `boolean`\892 _Default:_ `true`893 894 If `true`, the subprocess uses both the [`env`](#optionsenv) option and the current process' environment variables ([`process.env`](https://nodejs.org/api/process.html#processenv)).895-If `false`, only the `env` option is used, not `process.env`.895+If `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`.896 897 [More info.](input.md#environment-variables)898 899 ### options.input282 unmodified lines1182 This is useful when the subprocess spawns its own processes, such as when using the [`shell`](#optionsshell) option.1183 1184 On 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).1185 1186-This 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.1186+This 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.1187 1188 [More info.](termination.md#killing-descendant-processes)1189 1190 ### options.uid175 unmodified linesmodified:docs/debugging.md+1 added-1 removed
114 unmodified lines115 It 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)).116 117 If a string is returned, it is printed on `stderr`. If `undefined` is returned, nothing is printed.118 119-If 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.119+If 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).120 121 ### Filter logs122 123 ```js81 unmodified linesmodified:docs/execution.md+1 added-1 removed
157 unmodified lines158 - 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.165 166 <hr>3 unmodified linesmodified:docs/termination.md+1 added-1 removed
207 unmodified lines208 ```209 210 On 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.211 212-This 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.212+This 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.213 214 This option cannot be used with [synchronous methods](execution.md#synchronous-execution).215 216 ## Signal termination163 unmodified linesmodified:lib/arguments/command-file.js+2 added-6 removed
10 unmodified lines11 // 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};13 14 // 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- }18-19- return escapeWindowsCommand(parsed);15+ return options.shell || process.platform !== 'win32' ? parsed : escapeWindowsCommand(parsed);16 };17 18 // Only `.exe` and `.com` files can be spawned directly; anything else needs `cmd.exe`19 const directlyExecutableRegExp = /\.(?:com|exe)$/i;131 unmodified lines151 if (!shebangLine) {152 return undefined;153 }154 159- 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 linesmodified:lib/arguments/cwd.js+1 added-5 removed
37 unmodified lines38 } catch (error) {39 return `The "cwd" option is invalid: ${cwd}.\n${error.message}\n${originalMessage}`;40 }41 42- 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- }45-46- return originalMessage;43 };modified:lib/arguments/fd-options.js+3 added-7 removed
56 unmodified lines57 throw new TypeError(`"${getOptionName(isWritable)}" must not be ${fdName}. That file descriptor does not exist.58 Please set the "stdio" option to ensure that file descriptor exists.`);59 }60 61- 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 }64 65- 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.67 If you meant to use it as input, please set its "stdio" option to \`{value: 'pipe', input: true}\`.`);68 }69 };18 unmodified lines88 if (usedDescriptor === 1 && stdout !== undefined) {89 return {optionName: 'stdout', optionValue: stdout};90 }91 92- if (usedDescriptor === 2 && stderr !== undefined) {93- return {optionName: 'stderr', optionValue: stderr};94- }95-96- return {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};92+ return usedDescriptor === 2 && stderr !== undefined ? {optionName: 'stderr', optionValue: stderr} : {optionName: `stdio[${usedDescriptor}]`, optionValue: stdio[usedDescriptor]};93 };94 95 const getUsedDescriptor = fdNumber => fdNumber === 'all' ? 1 : fdNumber;96 9 unmodified linesmodified:lib/arguments/options.js+1 added
110 unmodified lines111 }112 113 return env;114 };115+modified:lib/convert/duplex.js+2 added-2 removed
1 import {Duplex} from 'node:stream';2 import {callbackify} from 'node:util';3 import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4+import {copyOptions} from '../utils/options.js';5 import {6 getSubprocessStdout,7 getReadableOptions,8 getReadableMethods,8 unmodified lines17 } from './writable.js';18 19 // Create a `Duplex` stream combining both `subprocess.readable()` and `subprocess.writable()`20 export 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 linesmodified:lib/convert/iterable.js+2 added-2 removed
1 import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';2 import {getFromStream} from '../arguments/fd-options.js';3 import {iterateOnSubprocessStream} from '../io/iterate.js';4+import {copyOptions} from '../utils/options.js';5 6 // Convert the subprocess to an async iterable7 export 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 linesmodified:lib/convert/readable.js+2 added-2 removed
2 unmodified lines3 import {BINARY_ENCODINGS} from '../arguments/encoding-option.js';4 import {getFromStream} from '../arguments/fd-options.js';5 import {iterateOnSubprocessStream, DEFAULT_OBJECT_HIGH_WATER_MARK} from '../io/iterate.js';6 import {createDeferred} from '../utils/deferred.js';7+import {copyOptions} from '../utils/options.js';8 import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';9 import {10 safeWaitForSubprocessStdin,11 waitForSubprocessStdout,2 unmodified lines14 } from './shared.js';15 16 // Create a `Readable` stream that forwards from `stdout` and awaits the subprocess17 export 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 linesmodified:lib/convert/writable.js+7 added-5 removed
1 import {Writable} from 'node:stream';2 import {callbackify} from 'node:util';3 import {getToStream} from '../arguments/fd-options.js';4 import {isStreamAbort} from '../resolve/wait-stream.js';5+import {copyOptions} from '../utils/options.js';6 import {addConcurrentStream, waitForConcurrentStreams} from './concurrent.js';7 import {8 safeWaitForSubprocessStdout,9 waitForSubprocessStdin,2 unmodified lines12 } from './shared.js';13 14 // Create a `Writable` stream that forwards to `stdin` and awaits the subprocess15 export 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 lines101 102 // When `writable` aborts/errors, do the same on `subprocess.stdin`103 export 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 }108+109+ destroyOtherWritable(subprocessStdin, error);110+ await waitForSubprocess(subprocess, error);111 };112 113 const destroyOtherWritable = (stream, error) => {114 destroyOtherStream(stream, stream.writable, error);1 unmodified linemodified:lib/io/contents.js+1 added-5 removed
80 unmodified lines81 if (readableObjectMode || lines) {82 return await getStreamAsArray(iterable, {maxBuffer});83 }84 85- if (encoding === 'buffer') {86- return new Uint8Array(await getStreamAsArrayBuffer(iterable, {maxBuffer}));87- }88-89- 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 linesmodified:lib/io/max-buffer.js+2 added-10 removed
26 unmodified lines27 if (lines) {28 return 'lines';29 }30 31- if (encoding === 'buffer') {32- return 'bytes';33- }34-35- return 'characters';31+ return encoding === 'buffer' ? 'bytes' : 'characters';32 };33 34 // 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 lines56 57 const {maxBufferInfo: {fdNumber, unit, threshold = getFdSpecificValue(maxBuffer, fdNumber)}} = error;58 delete error.maxBufferInfo;59 64- if (fdNumber === 'ipc') {65- return {streamName: 'IPC output', threshold, unit: 'messages'};66- }67-68- return {streamName: getStreamName(fdNumber), threshold, unit};60+ return fdNumber === 'ipc' ? {streamName: 'IPC output', threshold, unit: 'messages'} : {streamName: getStreamName(fdNumber), threshold, unit};61 };62 63 // 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 linesmodified:lib/io/output-sync.js+2 added-6 removed
8 unmodified lines9 10 // Apply `stdout`/`stderr` options, after spawning, in sync mode11 export 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 }15 16 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 ones79 unmodified lines97 return {serializedResult: joinToUint8Array(chunks)};98 }99 100 const serializedResult = joinToString(chunks, encoding);101- if (lines[fdNumber]) {102- return {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)};103- }104-105- return {serializedResult};101+ return lines[fdNumber] ? {serializedResult, finalResult: splitLinesSync(serializedResult, !stripFinalNewline[fdNumber], objectMode)} : {serializedResult};102 };103 104 const logOutputSync = ({serializedResult, fdNumber, verboseInfo, encoding, stdioItems, objectMode}) => {105 if (!shouldLogOutput({44 unmodified linesmodified:lib/io/strip-newline.js+1 added-1 removed
1 import stripFinalNewlineFunction from 'strip-final-newline';2 3 // 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.5-export const stripNewline = (value, {stripFinalNewline}, fdNumber, allFds) => getStripFinalNewline(stripFinalNewline, fdNumber, allFds) && value !== undefined && !Array.isArray(value)5+export const stripNewline = (value, {stripFinalNewline}, fdNumber, allFds) => value !== undefined && !Array.isArray(value) && getStripFinalNewline(stripFinalNewline, fdNumber, allFds)6 ? stripFinalNewlineFunction(value)7 : value;8 9 // Retrieve `stripFinalNewline` option value, including with `subprocess.all`4 unmodified linesmodified:lib/ipc/get-each.js+2 added-2 removed
1 import {once, on} from 'node:events';2+import {copyOptions} from '../utils/options.js';3 import {4 validateIpcMethod,5 disconnect,6 getStrictResponseError,6- getIpcOptions,7 } from './validation.js';8 import {getIpcEmitter, isConnected} from './forward.js';9 import {addReference, removeReference} from './reference.js';10 11 export const internalGetEachMessageOptions = Symbol('internalGetEachMessageOptions');12 13 // Like `[sub]process.on('message')` but promise-based14 export 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 linesmodified:lib/ipc/get-one.js+2 added-2 removed
1 import {once, on} from 'node:events';2+import {copyOptions} from '../utils/options.js';3 import {4 validateIpcMethod,5 throwOnEarlyDisconnect,6 disconnect,7 getStrictResponseError,7- getIpcOptions,8 } from './validation.js';9 import {getIpcEmitter, isConnected} from './forward.js';10 import {addReference, removeReference} from './reference.js';11 12 export const internalGetOneMessageOptions = Symbol('internalGetOneMessageOptions');13 14 // Like `[sub]process.once('message')` but promise-based15 export 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] ?? {};19 20 validateIpcMethod({74 unmodified linesmodified:lib/ipc/incoming.js+1 added-1 removed
24 unmodified lines25 // The `message` event so it is emitted at most once per macrotask.26 export 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 }32 33 if (!INCOMING_MESSAGES.has(anyProcess)) {53 unmodified linesmodified:lib/ipc/send.js+2 added-2 removed
1 import {promisify} from 'node:util';2+import {copyOptions} from '../utils/options.js';3 import {4 validateIpcMethod,5 handleEpipeError,6 handleSerializationError,7 disconnect,7- getIpcOptions,8 } from './validation.js';9 import {startSendMessage, endSendMessage} from './outgoing.js';10 import {handleSendStrict, waitForStrictResponse} from './strict.js';11 1 unmodified line13 // 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.16 export 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 linesmodified:lib/ipc/strict.js+10 added-5 removed
32 unmodified lines33 }34 35 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 lines61 62 return message;63 };64 65-// Reception of the acknowledgment response66-export 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.67+export const handleStrictResponse = (wrappedMessage, anyProcess) => {68 if (wrappedMessage?.type !== RESPONSE_TYPE) {69 return false;70 }71 72 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+ }77+78 return true;79 };80 81 // Wait for the other process to receive the message from `sendMessage()`2 unmodified lines84 return;85 }86 87 const deferred = createDeferred();83- STRICT_RESPONSES[wrappedMessage.id] = deferred;88+ STRICT_RESPONSES[wrappedMessage.id] = {deferred, anyProcess};89 const controller = new AbortController();90 91 try {92 const {isDeadlock, hasListeners} = await Promise.race([27 unmodified linesmodified:lib/ipc/validation.js-10 removed
107 unmodified lines108 if (anyProcess.connected) {109 anyProcess.disconnect();110 }111 };112-113-// The options are kept on a null-prototype object, otherwise a polluted `Object.prototype` would inject option values.114-// Like destructuring them, `null` throws.115-export const getIpcOptions = (options = {}) => {116- if (options === null) {117- throw new TypeError('The options must be an object, not `null`.');118- }119-120- return {__proto__: null, ...options};121-};modified:lib/methods/bind.js+1 added-7 removed
10 unmodified lines11 ]));12 return {__proto__: null, ...safeBoundOptions, ...mergedOptions};13 };14 15-const mergeOption = (optionName, boundOptionValue, optionValue) => {16- if (DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue)) {17- return {...boundOptionValue, ...optionValue};18- }15+const mergeOption = (optionName, boundOptionValue, optionValue) => DEEP_OPTIONS.has(optionName) && isPlainObject(boundOptionValue) && isPlainObject(optionValue) ? {...boundOptionValue, ...optionValue} : optionValue;16 20- return optionValue;21-};22-17 const DEEP_OPTIONS = new Set(['env', ...FD_SPECIFIC_OPTIONS]);modified:lib/methods/main-async.js+2 added-2 removed
102 unmodified lines103 104 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 lines200 });201 return handleResult(result, verboseInfo, options);202 };203 204-const getAsyncResult = ({errorInfo, exitCode, signal, stdio, all, ipcOutput, context, options, command, escapedCommand, startTime}) => 'error' in errorInfo204+const 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 linesmodified:lib/methods/main-sync.js+2 added-1 removed
119 unmodified lines120 const 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 linesmodified:lib/pipe/pipe-arguments.js+4 added-4 removed
1 import {normalizeParameters} from '../methods/parameters.js';2 import {getStartTime} from '../return/duration.js';3 import {SUBPROCESS_OPTIONS, getToStream, getFromStream} from '../arguments/fd-options.js';4 import {isDenoExecPath} from '../arguments/file-url.js';5+import {copyOptions} from '../utils/options.js';6 7 // Normalize and validate arguments passed to `source.pipe(destination)`8 export const normalizePipeArguments = ({source, sourcePromise, boundOptions, createNested}, ...pipeArguments) => {9 const startTime = getStartTime();29 unmodified lines39 return {destinationError: error};40 }41 42 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);44 45 try {46 const destinationStream = getToStream(destination, to);47 return {10 unmodified lines58 59 /*60 The destination has already been spawned at that point, since the `to` option is validated afterwards.61 When 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.62-In both cases, its error must be handled, otherwise it becomes an unhandled rejection which crashes the current process.62+In 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 */64 const abortDestination = (destination, firstArgument) => {65 if (destination !== firstArgument) {66 destination.kill();39 unmodified lines106 __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 linesmodified:lib/pipe/throw.js+5 added-3 removed
36 unmodified lines37 abortSourceStream(sourceStream);38 return destinationError;39 }40 41- if (sourceError !== undefined) {42- endDestinationStream(destinationStream);43- return sourceError;41+ if (sourceError === undefined) {42+ return;43 }44+45+ endDestinationStream(destinationStream);46+ return sourceError;47 };48 49 // Specific error return value when passing invalid arguments to `subprocess.pipe()` or when using `unpipeSignal`50 export const createNonCommandError = ({error, fileDescriptors, sourceOptions, startTime}) => makeEarlyError({10 unmodified linesmodified:lib/resolve/all-async.js+2 added-10 removed
8 unmodified lines9 return;10 }11 12 const fileDescriptors = [[stdout, 1], [stderr, 2]].filter(([stream]) => stream);13- if (fileDescriptors.length === 0) {14- return;15- }16-17- return setAllStream(mergeStreams(fileDescriptors.map(([stream]) => stream)));13+ return fileDescriptors.length === 0 ? undefined : setAllStream(mergeStreams(fileDescriptors.map(([stream]) => stream)));14 };15 16 // 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 included38 unmodified lines56 if (!bufferStdout) {57 return {stream: stderr, buffer, drainedStream: all};58 }59 64- if (!bufferStderr) {65- return {stream: stdout, buffer, drainedStream: all};60+ return bufferStderr ? {stream: all, buffer} : {stream: stdout, buffer, drainedStream: all};66- }67-68- return {stream: all, buffer};61 };62 63 // 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 chunk6 unmodified linesmodified:lib/resolve/all-sync.js+2 added-6 removed
32 unmodified lines33 if (Array.isArray(stdout) || Array.isArray(stderr)) {34 return [stdout, stderr].flat();35 }36 37- if (isUint8Array(stdout) && isUint8Array(stderr)) {38- return concatUint8Arrays([stdout, stderr]);39- }40-41- return `${stdout}${stderr}`;37+ return isUint8Array(stdout) && isUint8Array(stderr) ? concatUint8Arrays([stdout, stderr]) : `${stdout}${stderr}`;38 };39 40 const hasLines = ({lines}) => Boolean(lines[1] || lines[2]);41 42 // Each file descriptor is either already split into lines, or is a string which still needs to be split47-const splitAllLines = (value, allFds, options) => Array.isArray(value) || !hasLines(options)43+const 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 lines112 if (signal !== undefined) {113 return `Command was killed with ${signal} (${signalDescription})`;114 }115 116- if (exitCode !== undefined) {117- return `Command failed with exit code ${exitCode}`;116+ return exitCode === undefined ? 'Command failed' : `Command failed with exit code ${exitCode}`;118- }119-120- return 'Command failed';117 };118 119 const getForcefulSuffix = (isForcefullyTerminated, forceKillAfterDelay) => isForcefullyTerminated120 ? ` and was forcefully terminated after ${forceKillAfterDelay} milliseconds`23 unmodified lines144 if (typeof messageItem === 'string') {145 return messageItem;146 }147 152- if (isUint8Array(messageItem)) {153- return uint8ArrayToString(messageItem);154- }155-156- return '';148+ return isUint8Array(messageItem) ? uint8ArrayToString(messageItem) : '';149 };modified:lib/return/reject.js+1 added-1 removed
3 unmodified lines4 // Also print the final log line with `verbose`.5 export const handleResult = (result, verboseInfo, {reject}) => {6 logResult(result, verboseInfo);7 8- if (result.failed && reject) {8+ if (reject && result.failed) {9 throw result;10 }11 12 return result;1 unmodified linemodified:lib/stdio/direction.js+12 added-9 removed
8 unmodified lines9 // 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.13-export const getStreamDirection = (stdioItems, fdNumber, optionName) => {14- const directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber));13+export const getStreamDirection = ({stdioItems, isStdioArray, fdNumber, optionName}) => {14+ const directions = stdioItems.map(stdioItem => getStdioItemDirection(stdioItem, fdNumber, isStdioArray));15 16 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 }19 20 return directions.find(Boolean) ?? DEFAULT_DIRECTION;21 };22 23-const getStdioItemDirection = (stdioItem, fdNumber) => {23+const getStdioItemDirection = (stdioItem, fdNumber, isStdioArray) => {24 const knownDirection = KNOWN_DIRECTIONS[fdNumber];25 const direction = getRequestedDirection(stdioItem);26 if (knownDirection === undefined) {27 return direction;28 }29 30- validateKnownDirection(stdioItem, knownDirection);30+ validateKnownDirection(stdioItem, knownDirection, isStdioArray);31 return knownDirection;32 };33 34 // `direction` is set when the user explicitly requests it, e.g. `{value: 'pipe', input: true}`.12 unmodified lines47 // `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.51-const validateKnownDirection = ({type, value, optionName}, knownDirection) => {52- if (!STREAM_TYPES.has(type)) {52+const validateKnownDirection = ({type, value, optionName}, knownDirection, isStdioArray) => {53+ if (!STREAM_TYPES.has(type) || (!isStdioArray && getStandardStreamDirection(value) !== undefined)) {54 return;55 }56 57 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 }61+62+ 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 };65 66 const STREAM_TYPES = new Set(['native', 'nodeStream', 'webStream']);67 53 unmodified linesmodified:lib/stdio/duplicate.js+2 added-2 removed
1-import {resolve} from 'node:path';1+import path from 'node:path';2 import {fileURLToPath} from 'node:url';3 import {4 SPECIAL_DUPLICATE_TYPES_SYNC,5 SPECIAL_DUPLICATE_TYPES,5 unmodified lines11 const isFileType = type => SPECIAL_DUPLICATE_TYPES_SYNC.has(type);12 13 // The file that a `filePath` or `fileUrl` stdio item targets, as an absolute path14 export const getFileTarget = ({type, value}) => type === 'filePath'15- ? resolve(value.file)15+ ? path.resolve(value.file)16 : fileURLToPath(value);17 18 // Duplicates in the same file descriptor is most likely an error.19 // However, this can be useful with generators.110 unmodified linesmodified:lib/stdio/handle.js+7 added-2 removed
42 unmodified lines43 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 lines147 }148 };149 150 // `node:child_process` converts file descriptors to a 32-bit signed integer, and aborts the process when it cannot146-const MAX_FILE_DESCRIPTOR = 2 ** 31 - 1;151+const MAX_FILE_DESCRIPTOR = (2 ** 31) - 1;152 153 const validateFileStdio = ({type, value, optionName}) => {154 if (isRegularUrl(value)) {155 throw new TypeError(`The \`${optionName}: URL\` option must use the \`file:\` scheme.108 unmodified linesmodified:lib/stdio/native.js+1 added-5 removed
82 unmodified lines83 if (typeof value === 'number') {84 return {type: 'nodeStream', value: getStandardStream(value, value, optionName), optionName};85 }86 87- if (isNodeStream(value, {checkOpen: false})) {88- return {type: 'nodeStream', value, optionName};89- }90-91- return stdioItem;87+ return isNodeStream(value, {checkOpen: false}) ? {type: 'nodeStream', value, optionName} : stdioItem;88 };89 90 // 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 linesmodified:lib/stdio/stdio-option.js+2 added-14 removed
20 unmodified lines21 throw new Error('The `ipc: true` option must be used instead of `stdio: \'ipc\'`.');22 }23 };24 25-const hasIpcStdioOption = stdioOption => {26- if (Array.isArray(stdioOption)) {27- return stdioOption.some(item => hasIpcStdioItem(item));28- }25+const hasIpcStdioOption = stdioOption => Array.isArray(stdioOption) ? stdioOption.some(item => hasIpcStdioItem(item)) : hasIpcStdioItem(stdioOption);26 30- return hasIpcStdioItem(stdioOption);31-};27+const hasIpcStdioItem = stdioOption => isStdioValueObject(stdioOption) ? stdioOption.value === 'ipc' : stdioOption === 'ipc';28 33-const hasIpcStdioItem = stdioOption => {34- if (isStdioValueObject(stdioOption)) {35- return stdioOption.value === 'ipc';36- }37-38- return stdioOption === 'ipc';39-};40-29 const getStdioArray = (stdio, options) => {30 if (stdio === undefined) {31 return STANDARD_STREAMS_ALIASES.map(alias => options[alias]);32 }58 unmodified linesmodified:lib/stdio/type.js+2 added-10 removed
42 unmodified lines43 if (isTransformStream(value)) {44 return getTransformStreamType({transform: value}, optionName);45 }46 47- if (isTransformOptions(value)) {48- return getTransformObjectType(value, optionName);49- }50-51- return 'native';47+ return isTransformOptions(value) ? getTransformObjectType(value, optionName) : 'native';48 };49 50 const getTransformObjectType = (value, optionName) => {51 if (isDuplexStream(value.transform, {checkOpen: false})) {52 return getDuplexType(value, optionName);53 }54 59- if (isTransformStream(value.transform)) {60- return getTransformStreamType(value, optionName);61- }62-63- return getGeneratorObjectType(value, optionName);55+ return isTransformStream(value.transform) ? getTransformStreamType(value, optionName) : getGeneratorObjectType(value, optionName);56 };57 58 const getDuplexType = (value, optionName) => {59 validateNonGeneratorType(value, optionName, 'Duplex stream');114 unmodified linesmodified:lib/terminate/kill-descendants.js+16 added-17 removed
7 unmodified lines8 // 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.12-export const getSpawnOptions = options => options.killDescendants && !isWindows12+export const getSpawnOptions = options => !isWindows && options.killDescendants13 ? {...options, detached: true}14 : options;15 16-/*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`.19-So, like `ChildProcess.prototype.kill()` does for a subprocess which already exited, nothing is signaled and `false` is returned.20-*/21-16 // 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.24-export const getKillFunction = (subprocess, {killDescendants}, {signal: controllerSignal}) => {18+export 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 }28 29 const killDescendantsFunction = isWindows ? killDescendantsWindows : killDescendantsUnix;31- return killDescendantsFunction.bind(undefined, subprocess, controllerSignal);30+ return killDescendantsFunction.bind(undefined, subprocess);31 };32 33 /*35-Unlike `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.36-On 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.34+Unlike `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.35+On 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.36 On 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 */39-const isAbandoned = (subprocess, controllerSignal) => subprocess.pid === undefined40- || (hasExited(subprocess) && (isWindows || controllerSignal.aborted));38+const isAbandoned = subprocess => subprocess.pid === undefined39+ || (isWindows && hasExited(subprocess));40 41 const hasExited = ({exitCode, signalCode}) => exitCode !== null || signalCode !== null;42 43 // 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.46-const killDescendantsUnix = (subprocess, controllerSignal, signal) => {47- if (isAbandoned(subprocess, controllerSignal)) {45+const killDescendantsUnix = (subprocess, signal) => {46+ if (isAbandoned(subprocess)) {47 return false;48 }49 50 try {9 unmodified lines60 // 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).65-const killDescendantsWindows = (subprocess, controllerSignal, signal) => {66- if (isAbandoned(subprocess, controllerSignal)) {64+const killDescendantsWindows = (subprocess, signal) => {65+ if (isAbandoned(subprocess)) {66 return false;67 }68 69 const taskkillFile = getTaskkillFile();26 unmodified linesadded: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.3+export const copyOptions = (options = {}) => {4+ if (options === null) {5+ throw new TypeError('The options must be an object, not `null`.');6+ }7+8+ return {__proto__: null, ...options};9+};modified:lib/utils/uint-array.js+1 added-7 removed
33 unmodified lines34 const finalString = decoder.end();35 return finalString === '' ? strings : [...strings, finalString];36 };37 38-export const joinToUint8Array = uint8ArraysOrStrings => {39- if (uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0])) {40- return uint8ArraysOrStrings[0];41- }38+export const joinToUint8Array = uint8ArraysOrStrings => uint8ArraysOrStrings.length === 1 && isUint8Array(uint8ArraysOrStrings[0]) ? uint8ArraysOrStrings[0] : concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));39 43- return concatUint8Arrays(stringsToUint8Arrays(uint8ArraysOrStrings));44-};45-40 const stringsToUint8Arrays = uint8ArraysOrStrings => uint8ArraysOrStrings.map(uint8ArrayOrString => typeof uint8ArrayOrString === 'string'41 ? stringToUint8Array(uint8ArrayOrString)42 : uint8ArrayOrString);43 20 unmodified linesmodified:lib/verbose/output.js+2 added-2 removed
44 unmodified lines45 // - `.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.51-const isPipingStream = stream => stream._readableState.pipes.some(pipe => !isAllStream(pipe));51+const isPipingStream = stream => stream._readableState.pipes.some(pipe => !isAllStream(pipe) || isPipingStream(pipe));52 53 // When `verbose` is `full`, print stdout|stderr54 const logLine = (line, fdNumber, verboseInfo) => {55 const verboseMessage = serializeVerboseMessage(line);7 unmodified linesmodified:test/arguments/command-resolution.js+128 added-126 removed
1+import assert from 'node:assert/strict';2+import path from 'node:path';3+import process from 'node:process';4+import test from 'node:test';5 import {6 cp,7 mkdir,8 unlink,9 writeFile,10 } from 'node:fs/promises';7-import path from 'node:path';8-import process from 'node:process';9-import test from 'ava';11+import {assertThrows, assertRejects} from '../helpers/assert.js';12 import {execa, execaSync} from '../../index.js';13 import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';14 15 setFixtureDirectory();8 unmodified lines24 // back byte-identical. This exercises the escaping logic on whichever OS runs the25 // test, so Windows escaping is genuinely validated on CI.26 27 // `echo.js` prints `process.argv.slice(2).join('\n')`26-const testRoundtrip = async (t, commandArguments) => {28+const testRoundtrip = async commandArguments => {29 const expectedStdout = commandArguments.map(String).join('\n');30 31 const {stdout} = await execa('echo.js', commandArguments);30- t.is(stdout, expectedStdout);32+ assert.equal(stdout, expectedStdout);33 34 const {stdout: stdoutSync} = execaSync('echo.js', commandArguments);33- t.is(stdoutSync, expectedStdout);35+ assert.equal(stdoutSync, expectedStdout);36 };37 36-test('Empty arguments and arguments with spaces', testRoundtrip, ['foo', '', 'bar', 'André Cruz']);37-test('Non-string arguments are coerced', testRoundtrip, [1234]);38-test('Arguments with shell special characters', testRoundtrip, [38+test('Empty arguments and arguments with spaces', () => testRoundtrip(['foo', '', 'bar', 'André Cruz']));39+test('Non-string arguments are coerced', () => testRoundtrip([1234]));40+test('Arguments with shell special characters', () => testRoundtrip([41 'foo',42 '()',43 'foo',44 '[]',23 unmodified lines68 '\\"',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.72-test('Arguments with backslashes', testRoundtrip, ['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']);73-test('Arguments with backslashes and double quotes', testRoundtrip, ['a\\"b', '\\"', 'a"\\', '\\\\"', '"\\\\"']);74+test('Arguments with backslashes', () => testRoundtrip(['a\\b', 'a\\\\b', '\\', '\\\\', 'a\\', 'trailing\\']));75+test('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.75-test('Arguments combining backslashes, quotes and metacharacters', testRoundtrip, ['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']);76-test('Arguments with tabs and whitespace', testRoundtrip, ['a\tb', '\t', ' spaces ', ' ']);77+test('Arguments combining backslashes, quotes and metacharacters', () => testRoundtrip(['a\\"&b', '\\"()\\', 'c\\\\"|d', '%x%\\', '">&<"']));78+test('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.78-test('Arguments that are empty or whitespace-only', testRoundtrip, ['', '', 'a', '', ' ', '\t', '']);79-test('Arguments that look like flags', testRoundtrip, ['-e', '--foo=bar', '--', '-']);80-test('Arguments with Unicode characters', testRoundtrip, ['café', '🎉', '日本語', 'naïve']);80+test('Arguments that are empty or whitespace-only', () => testRoundtrip(['', '', 'a', '', ' ', '\t', '']));81+test('Arguments that look like flags', () => testRoundtrip(['-e', '--foo=bar', '--', '-']));82+test('Arguments with Unicode characters', () => testRoundtrip(['café', '🎉', '日本語', 'naïve']));83 // eslint-disable-next-line no-template-curly-in-string82-test('Arguments with shell variable syntax', testRoundtrip, ['$HOME', '${x}', '~', 'a=b,c', '`whoami`']);84+test('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.84-test('Very long arguments', testRoundtrip, ['a'.repeat(10_000), `${'b'.repeat(1000)}\\"${'c'.repeat(1000)}`]);86+test('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.89-test('Arguments with long runs of backslashes before quotes', testRoundtrip, [91+test('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.100 const backslashRunArguments = [101 ...Array.from({length: 6}, (_, index) => `${'\\'.repeat(index + 1)}"x`),102 ...Array.from({length: 6}, (_, index) => `end${'\\'.repeat(index + 1)}`),103 ];102-test('Arguments with backslash runs of every length', testRoundtrip, backslashRunArguments);104+test('Arguments with backslash runs of every length', () => testRoundtrip(backslashRunArguments));105 // Consecutive double quotes must each be escaped independently, not collapsed nor paired.104-test('Arguments with consecutive double quotes', testRoundtrip, ['""', '"""', 'a""b', '""""']);106+test('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.108-test('Line breaks are kept within a single argument for executables', async t => {110+test('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);114 115 const {stdout: stdoutSync} = execaSync('echo-argv.js', commandArguments);114- t.deepEqual(JSON.parse(stdoutSync), commandArguments);116+ assert.deepEqual(JSON.parse(stdoutSync), commandArguments);117 });118 119 // A command can be resolved from different kinds of file paths. Forward slashes120 // work even on Windows, where they are normalized to backslashes.119-const testResolvesCommand = async (t, file, options) => {121+const testResolvesCommand = async (file, options) => {122 const {stdout} = await execa(file, ['foo'], options);121- t.is(stdout, 'foo');123+ assert.equal(stdout, 'foo');124 125 const {stdout: stdoutSync} = execaSync(file, ['foo'], options);124- t.is(stdoutSync, 'foo');126+ assert.equal(stdoutSync, 'foo');127 };128 127-test('Runs a command given as an absolute path', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'echo.js'));128-test('Runs a command given as a relative path with a custom cwd', testResolvesCommand, './echo.js', {cwd: FIXTURES_DIRECTORY});129-test('Runs a command given as a relative POSIX-style subpath', testResolvesCommand, 'test/fixtures/echo.js');130-test('Runs a command whose path contains a space', testResolvesCommand, 'command with space.js');131-test('Runs a command whose absolute path contains a space', testResolvesCommand, path.join(FIXTURES_DIRECTORY, 'command with space.js'));129+test('Runs a command given as an absolute path', () => testResolvesCommand(path.join(FIXTURES_DIRECTORY, 'echo.js')));130+test('Runs a command given as a relative path with a custom cwd', () => testResolvesCommand('./echo.js', {cwd: FIXTURES_DIRECTORY}));131+test('Runs a command given as a relative POSIX-style subpath', () => testResolvesCommand('test/fixtures/echo.js'));132+test('Runs a command whose path contains a space', () => testResolvesCommand('command with space.js'));133+test('Runs a command whose absolute path contains a space', () => testResolvesCommand(path.join(FIXTURES_DIRECTORY, 'command with space.js')));134 135 // 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.136-test('Runs a shebang script without specifying its interpreter', async t => {138+test('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');141 142 const {stdout: stdoutSync} = execaSync('echo.js', ['foo']);141- t.is(stdoutSync, 'foo');143+ assert.equal(stdoutSync, 'foo');144 });145 146 // 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.147-test('Runs a shebang script with a space after the "#!"', async t => {149+test('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');152 153 const {stdout: stdoutSync} = execaSync('echo-space-shebang.js', ['foo']);152- t.is(stdoutSync, 'foo');154+ assert.equal(stdoutSync, 'foo');155 });156 157 /*158 Windows does not support shebangs natively, so Execa parses them itself, by reading the file's first bytes into a fixed-size buffer.4 unmodified lines163 if (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));168 169 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 }174 175 // 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).175-const testNoMutation = async (t, options) => {177+const testNoMutation = async options => {178 const commandArguments = ['foo', 'bar'];179 const optionsCopy = {...options};180 181 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);184 185 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 };189 188-test('Does not mutate arguments nor options', testNoMutation, {});189-test('Does not mutate arguments nor options with a shell', testNoMutation, {shell: true});190+test('Does not mutate arguments nor options', () => testNoMutation({}));191+test('Does not mutate arguments nor options with a shell', () => testNoMutation({shell: true}));192 193 if (isWindows) {194 const nodeOnlyOptions = {195 extendEnv: false,3 unmodified lines199 },200 };201 202 // 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 });207 208 test('Uses PATHEXT extension order for direct executables', async t => {209 const binaryDirectory = path.join(FIXTURES_DIRECTORY, 'node_modules', '.bin');4 unmodified lines214 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 lines229 };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);235 236 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 });241 240- 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 lines252 253 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 lines271 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());276 277 const {stdout: currentDirectoryStdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);276- t.is(currentDirectoryStdoutSync.toLowerCase(), currentDirectoryExecutable.toLowerCase());278+ assert.equal(currentDirectoryStdoutSync.toLowerCase(), currentDirectoryExecutable.toLowerCase());279 280 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());283 284 const {stdout: stdoutSync} = execaSync(command, ['--print', 'process.execPath'], options);283- t.is(stdoutSync.toLowerCase(), pathExecutable.toLowerCase());285+ assert.equal(stdoutSync.toLowerCase(), pathExecutable.toLowerCase());286 });287 286- 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 lines298 299 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 lines318 [environmentName]: '',319 },320 };321 const {stdout} = await execa(command, options);320- t.is(stdout, 'PATH');322+ assert.equal(stdout, 'PATH');323 324 const {stdout: stdoutSync} = execaSync(command, options);323- t.is(stdoutSync, 'PATH');325+ assert.equal(stdoutSync, 'PATH');326 327 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');331 332 const {stdout: parentEnvironmentStdoutSync} = execaSync(command, options);331- t.is(parentEnvironmentStdoutSync, 'PATH');333+ assert.equal(parentEnvironmentStdoutSync, 'PATH');334 });335 336 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 lines351 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 });358 359 // 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 });365 366 /*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 lines374 await cp(path.join(FIXTURES_DIRECTORY, 'echo-cmd-shim.cmd'), shimPath);375 return shimPath;376 };377 376- 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);383 384 const {stdout: stdoutSync} = execaSync(shimPath, [commandArgument]);383- t.is(stdoutSync, commandArgument);385+ assert.equal(stdoutSync, commandArgument);386 });387 386- 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);393 394 const {stdout: stdoutSync} = execaSync(command, [commandArgument], nodeOnlyOptions);393- t.is(stdoutSync, commandArgument);395+ assert.equal(stdoutSync, commandArgument);396 });397 396- 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 });402 401- 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 lines416 };417 418 try {419 const {stdout} = await execa('echo-cmd-shim', [commandArgument], options);418- t.is(stdout, commandArgument);420+ assert.equal(stdout, commandArgument);421 422 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 lines436 // 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.439 if (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);443 444 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', [commandArgument]);443- t.is(stdoutSync, commandArgument);445+ assert.equal(stdoutSync, commandArgument);446 };447 448 // 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\\'));468 469 // 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');475 476 const {stdout} = await execa('echo-shim.cmd', commandArguments);475- t.is(stdout, expectedStdout);477+ assert.equal(stdout, expectedStdout);478 479 const {stdout: stdoutSync} = execaSync('echo-shim.cmd', commandArguments);478- t.is(stdoutSync, expectedStdout);480+ assert.equal(stdoutSync, expectedStdout);481 };482 483 // 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']));496 497 /*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);504 505 const {stdout: stdoutSync} = execaSync('echo-shim.bat', [commandArgument]);504- t.is(stdoutSync, commandArgument);506+ assert.equal(stdoutSync, commandArgument);507 };508 509 // 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');521 522 const {stdout} = await execa('echo-shim.bat', commandArguments);521- t.is(stdout, expectedStdout);523+ assert.equal(stdout, expectedStdout);524 525 const {stdout: stdoutSync} = execaSync('echo-shim.bat', commandArguments);524- t.is(stdoutSync, expectedStdout);526+ assert.equal(stdoutSync, expectedStdout);527 });528 529 // `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 });535 536 // 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 });541 542 // 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
1+import assert from 'node:assert/strict';2 import {mkdir, rmdir} from 'node:fs/promises';3 import path from 'node:path';4 import process from 'node:process';5 import {pathToFileURL, fileURLToPath} from 'node:url';6+import test from 'node:test';7 import tempfile from 'tempfile';6-import test from 'ava';8+import {assertThrows} from '../helpers/assert.js';9 import {execa, execaSync} from '../../index.js';10 import {FIXTURES_DIRECTORY, setFixtureDirectory} from '../helpers/fixtures-directory.js';11 import {majorNodeVersion} from '../helpers/node-version.js';12 13 setFixtureDirectory();14 15 const isWindows = process.platform === 'win32';16 15-const testOptionCwdString = async (t, execaMethod) => {17+const 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 };22 21-test('The "cwd" option can be a string', testOptionCwdString, execa);22-test('The "cwd" option can be a string - sync', testOptionCwdString, execaSync);23+test('The "cwd" option can be a string', () => testOptionCwdString(execa));24+test('The "cwd" option can be a string - sync', () => testOptionCwdString(execaSync));25 24-const testOptionCwdUrl = async (t, execaMethod) => {26+const 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 };32 31-test('The "cwd" option can be a URL', testOptionCwdUrl, execa);32-test('The "cwd" option can be a URL - sync', testOptionCwdUrl, execaSync);33+test('The "cwd" option can be a URL', () => testOptionCwdUrl(execa));34+test('The "cwd" option can be a URL - sync', () => testOptionCwdUrl(execaSync));35 34-const testOptionCwdInvalid = (t, execaMethod) => {35- t.throws(() => {36+const 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 };41 40-test('The "cwd" option cannot be an invalid type', testOptionCwdInvalid, execa);41-test('The "cwd" option cannot be an invalid type - sync', testOptionCwdInvalid, execaSync);42+test('The "cwd" option cannot be an invalid type', () => testOptionCwdInvalid(execa));43+test('The "cwd" option cannot be an invalid type - sync', () => testOptionCwdInvalid(execaSync));44 43-const testErrorCwdDefault = async (t, execaMethod) => {45+const testErrorCwdDefault = async execaMethod => {46 const {cwd} = await execaMethod('empty.js');45- t.is(cwd, process.cwd());47+ assert.equal(cwd, process.cwd());48 };49 48-test('The "cwd" option defaults to process.cwd()', testErrorCwdDefault, execa);49-test('The "cwd" option defaults to process.cwd() - sync', testErrorCwdDefault, execaSync);50+test('The "cwd" option defaults to process.cwd()', () => testErrorCwdDefault(execa));51+test('The "cwd" option defaults to process.cwd() - sync', () => testErrorCwdDefault(execaSync));52 53 // Windows does not allow removing a directory used as `cwd` of a running subprocess54 if (!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 });61 62 const filePath = tempfile();4 unmodified lines67 68 const testCwdPreSpawn = async (t, execaMethod) => {69 await chdirToMissingDirectory(t);70 69- t.throws(() => {71+ assertThrows(() => {72 execaMethod('empty.js');73 }, {message: /The current directory does not exist/});74 };75 74- 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));78 79 // 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);83 84 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 };89 88- 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));92 93 // The `cwd` option is valid, so the error message must not mention it at all94 const testCwdMissingValidOption = async (t, execaMethod) => {95 await chdirToMissingDirectory(t);96 97 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 };100 99- 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 }104 105 const cwdNotExisting = {cwd: 'does_not_exist', expectedCode: 'ENOENT', expectedMessage: 'The "cwd" option is invalid'};106 const 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.0108 const cwdNotDirectory = {cwd: fileURLToPath(import.meta.url), expectedCode: isWindows ? 'ENOENT' : 'ENOTDIR', expectedMessage: 'The "cwd" option is not a directory'};109 108-const testCwdPostSpawn = async (t, {cwd, expectedCode, expectedMessage}, execaMethod) => {110+const 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 };117 116-test('The "cwd" option must be an existing file', testCwdPostSpawn, cwdNotExisting, execa);117-test('The "cwd" option must be an existing file - sync', testCwdPostSpawn, cwdNotExisting, execaSync);118-test('The "cwd" option must not be too long', testCwdPostSpawn, cwdTooLong, execa);119-test('The "cwd" option must not be too long - sync', testCwdPostSpawn, cwdTooLong, execaSync);120-test('The "cwd" option must be a directory', testCwdPostSpawn, cwdNotDirectory, execa);121-test('The "cwd" option must be a directory - sync', testCwdPostSpawn, cwdNotDirectory, execaSync);118+test('The "cwd" option must be an existing file', () => testCwdPostSpawn(cwdNotExisting, execa));119+test('The "cwd" option must be an existing file - sync', () => testCwdPostSpawn(cwdNotExisting, execaSync));120+test('The "cwd" option must not be too long', () => testCwdPostSpawn(cwdTooLong, execa));121+test('The "cwd" option must not be too long - sync', () => testCwdPostSpawn(cwdTooLong, execaSync));122+test('The "cwd" option must be a directory', () => testCwdPostSpawn(cwdNotDirectory, execa));123+test('The "cwd" option must be a directory - sync', () => testCwdPostSpawn(cwdNotDirectory, execaSync));124 125 const successProperties = {fixtureName: 'empty.js', expectedFailed: false};126 const errorProperties = {fixtureName: 'fail.js', expectedFailed: true};127 126-const testErrorCwd = async (t, execaMethod, {fixtureName, expectedFailed}) => {128+const 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 };133 132-test('result.cwd is defined', testErrorCwd, execa, successProperties);133-test('result.cwd is defined - sync', testErrorCwd, execaSync, successProperties);134-test('error.cwd is defined', testErrorCwd, execa, errorProperties);135-test('error.cwd is defined - sync', testErrorCwd, execaSync, errorProperties);134+test('result.cwd is defined', () => testErrorCwd(execa, successProperties));135+test('result.cwd is defined - sync', () => testErrorCwd(execaSync, successProperties));136+test('error.cwd is defined', () => testErrorCwd(execa, errorProperties));137+test('error.cwd is defined - sync', () => testErrorCwd(execaSync, errorProperties));modified:test/arguments/encoding-option.js+35 added-33 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 7 setFixtureDirectory();8 7-const testInvalidEncoding = (t, encoding, message, execaMethod) => {8- const error = t.throws(() => {9+const 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 };15 16 const UNKNOWN_ENCODING_MESSAGE = 'Please rename it to one of';17 const getCorrectEncodingMessage = correctEncoding => `Please rename it to "${correctEncoding}"`;18 17-test('cannot pass unknown encodings', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execa);18-test('cannot pass unknown encodings, sync', testInvalidEncoding, 'unknown', UNKNOWN_ENCODING_MESSAGE, execaSync);19-test('cannot pass empty encodings', testInvalidEncoding, '', UNKNOWN_ENCODING_MESSAGE, execa);20-test('cannot pass encoding: false', testInvalidEncoding, false, UNKNOWN_ENCODING_MESSAGE, execa);21-test('cannot pass encoding: Symbol', testInvalidEncoding, Symbol('test'), UNKNOWN_ENCODING_MESSAGE, execa);22-test('cannot pass encoding: null', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execa);23-test('cannot pass encoding: null, sync', testInvalidEncoding, null, getCorrectEncodingMessage('buffer'), execaSync);19+test('cannot pass unknown encodings', () => testInvalidEncoding('unknown', UNKNOWN_ENCODING_MESSAGE, execa));20+test('cannot pass unknown encodings, sync', () => testInvalidEncoding('unknown', UNKNOWN_ENCODING_MESSAGE, execaSync));21+test('cannot pass empty encodings', () => testInvalidEncoding('', UNKNOWN_ENCODING_MESSAGE, execa));22+test('cannot pass encoding: false', () => testInvalidEncoding(false, UNKNOWN_ENCODING_MESSAGE, execa));23+test('cannot pass encoding: Symbol', () => testInvalidEncoding(Symbol('test'), UNKNOWN_ENCODING_MESSAGE, execa));24+test('cannot pass encoding: null', () => testInvalidEncoding(null, getCorrectEncodingMessage('buffer'), execa));25+test('cannot pass encoding: null, sync', () => testInvalidEncoding(null, getCorrectEncodingMessage('buffer'), execaSync));26 /* eslint-disable unicorn/text-encoding-identifier-case -- intentionally testing invalid encoding casing */25-test('cannot pass encoding: utf-8', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execa);26-test('cannot pass encoding: utf-8, sync', testInvalidEncoding, 'utf-8', getCorrectEncodingMessage('utf8'), execaSync);27-test('cannot pass encoding: UTF-8', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execa);28-test('cannot pass encoding: UTF-8, sync', testInvalidEncoding, 'UTF-8', getCorrectEncodingMessage('utf8'), execaSync);29-test('cannot pass encoding: UTF8', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execa);30-test('cannot pass encoding: UTF8, sync', testInvalidEncoding, 'UTF8', getCorrectEncodingMessage('utf8'), execaSync);27+test('cannot pass encoding: utf-8', () => testInvalidEncoding('utf-8', getCorrectEncodingMessage('utf8'), execa));28+test('cannot pass encoding: utf-8, sync', () => testInvalidEncoding('utf-8', getCorrectEncodingMessage('utf8'), execaSync));29+test('cannot pass encoding: UTF-8', () => testInvalidEncoding('UTF-8', getCorrectEncodingMessage('utf8'), execa));30+test('cannot pass encoding: UTF-8, sync', () => testInvalidEncoding('UTF-8', getCorrectEncodingMessage('utf8'), execaSync));31+test('cannot pass encoding: UTF8', () => testInvalidEncoding('UTF8', getCorrectEncodingMessage('utf8'), execa));32+test('cannot pass encoding: UTF8, sync', () => testInvalidEncoding('UTF8', getCorrectEncodingMessage('utf8'), execaSync));33 /* eslint-enable unicorn/text-encoding-identifier-case */32-test('cannot pass encoding: utf-16le', testInvalidEncoding, 'utf-16le', getCorrectEncodingMessage('utf16le'), execa);33-test('cannot pass encoding: UTF-16LE', testInvalidEncoding, 'UTF-16LE', getCorrectEncodingMessage('utf16le'), execa);34-test('cannot pass encoding: UTF16LE', testInvalidEncoding, 'UTF16LE', getCorrectEncodingMessage('utf16le'), execa);35-test('cannot pass encoding: ucs2', testInvalidEncoding, 'ucs2', getCorrectEncodingMessage('utf16le'), execa);36-test('cannot pass encoding: UCS2', testInvalidEncoding, 'UCS2', getCorrectEncodingMessage('utf16le'), execa);37-test('cannot pass encoding: ucs-2', testInvalidEncoding, 'ucs-2', getCorrectEncodingMessage('utf16le'), execa);38-test('cannot pass encoding: UCS-2', testInvalidEncoding, 'UCS-2', getCorrectEncodingMessage('utf16le'), execa);39-test('cannot pass encoding: binary', testInvalidEncoding, 'binary', getCorrectEncodingMessage('latin1'), execa);34+test('cannot pass encoding: utf-16le', () => testInvalidEncoding('utf-16le', getCorrectEncodingMessage('utf16le'), execa));35+test('cannot pass encoding: UTF-16LE', () => testInvalidEncoding('UTF-16LE', getCorrectEncodingMessage('utf16le'), execa));36+test('cannot pass encoding: UTF16LE', () => testInvalidEncoding('UTF16LE', getCorrectEncodingMessage('utf16le'), execa));37+test('cannot pass encoding: ucs2', () => testInvalidEncoding('ucs2', getCorrectEncodingMessage('utf16le'), execa));38+test('cannot pass encoding: UCS2', () => testInvalidEncoding('UCS2', getCorrectEncodingMessage('utf16le'), execa));39+test('cannot pass encoding: ucs-2', () => testInvalidEncoding('ucs-2', getCorrectEncodingMessage('utf16le'), execa));40+test('cannot pass encoding: UCS-2', () => testInvalidEncoding('UCS-2', getCorrectEncodingMessage('utf16le'), execa));41+test('cannot pass encoding: binary', () => testInvalidEncoding('binary', getCorrectEncodingMessage('latin1'), execa));42 41-test('cannot pass encoding: constructor', testInvalidEncoding, 'constructor', UNKNOWN_ENCODING_MESSAGE, execa);42-test('cannot pass encoding: constructor, sync', testInvalidEncoding, 'constructor', UNKNOWN_ENCODING_MESSAGE, execaSync);43-test('cannot pass encoding: __proto__', testInvalidEncoding, '__proto__', UNKNOWN_ENCODING_MESSAGE, execa);44-test('cannot pass encoding: __proto__, sync', testInvalidEncoding, '__proto__', UNKNOWN_ENCODING_MESSAGE, execaSync);45-test('cannot pass encoding: CONSTRUCTOR', testInvalidEncoding, 'CONSTRUCTOR', UNKNOWN_ENCODING_MESSAGE, execa);46-test('cannot pass encoding: toString', testInvalidEncoding, 'toString', UNKNOWN_ENCODING_MESSAGE, execa);47-test('cannot pass encoding: valueOf', testInvalidEncoding, 'valueOf', UNKNOWN_ENCODING_MESSAGE, execa);48-test('cannot pass encoding: hasOwnProperty', testInvalidEncoding, 'hasOwnProperty', UNKNOWN_ENCODING_MESSAGE, execa);43+test('cannot pass encoding: constructor', () => testInvalidEncoding('constructor', UNKNOWN_ENCODING_MESSAGE, execa));44+test('cannot pass encoding: constructor, sync', () => testInvalidEncoding('constructor', UNKNOWN_ENCODING_MESSAGE, execaSync));45+test('cannot pass encoding: __proto__', () => testInvalidEncoding('__proto__', UNKNOWN_ENCODING_MESSAGE, execa));46+test('cannot pass encoding: __proto__, sync', () => testInvalidEncoding('__proto__', UNKNOWN_ENCODING_MESSAGE, execaSync));47+test('cannot pass encoding: CONSTRUCTOR', () => testInvalidEncoding('CONSTRUCTOR', UNKNOWN_ENCODING_MESSAGE, execa));48+test('cannot pass encoding: toString', () => testInvalidEncoding('toString', UNKNOWN_ENCODING_MESSAGE, execa));49+test('cannot pass encoding: valueOf', () => testInvalidEncoding('valueOf', UNKNOWN_ENCODING_MESSAGE, execa));50+test('cannot pass encoding: hasOwnProperty', () => testInvalidEncoding('hasOwnProperty', UNKNOWN_ENCODING_MESSAGE, execa));modified:test/arguments/env.js+26 added-19 removed
1+import assert from 'node:assert/strict';2 import path from 'node:path';3 import process from 'node:process';3-import test from 'ava';4+import test from 'node:test';5 import {execa, execaSync} from '../../index.js';6 import {setFixtureDirectory, PATH_KEY, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';7 8 setFixtureDirectory();9 process.env.FOO = 'foo';10 11 const isWindows = process.platform === 'win32';12 12-test('use environment variables by default', async t => {13+test('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 });17 17-test('extend environment variables by default', async t => {18+test('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 });22 22-test('do not extend environment with `extendEnv: false`', async t => {23+test('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 });27 28 // `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`.30 const environmentFile = path.join(FIXTURES_DIRECTORY, 'environment.js');31 31-const testNoEnvironment = async (t, execaMethod, options) => {32+const 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 };36 36-test('do not use process.env with `extendEnv: false` and no `env`', testNoEnvironment, execa, {});37-test('do not use process.env with `extendEnv: false` and no `env`, sync', testNoEnvironment, execaSync, {});38-test('do not use process.env with `extendEnv: false` and `env: {}`', testNoEnvironment, execa, {env: {}});39-test('do not use process.env with `extendEnv: false`, no `env` and `preferLocal`', testNoEnvironment, execa, {preferLocal: true});37+test('do not use process.env with `extendEnv: false` and no `env`', () => testNoEnvironment(execa, {}));38+test('do not use process.env with `extendEnv: false` and no `env`, sync', () => testNoEnvironment(execaSync, {}));39+test('do not use process.env with `extendEnv: false` and `env: {}`', () => testNoEnvironment(execa, {env: {}}));40+test('do not use process.env with `extendEnv: false`, no `env` and `preferLocal`', () => testNoEnvironment(execa, {preferLocal: true}));41 42+// `preferLocal` adds directories to `process.env.PATH` when `env` has no `PATH`, so system commands still resolve43+test('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+});47+48 // The `env` option is kept on a null-prototype object, so the properties it inherits are not passed to the subprocess42-const testInheritedEnv = async (t, execaMethod) => {49+const 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 };54 48-test('The "env" option does not pass inherited properties', testInheritedEnv, execa);49-test('The "env" option does not pass inherited properties, sync', testInheritedEnv, execaSync);55+test('The "env" option does not pass inherited properties', () => testInheritedEnv(execa));56+test('The "env" option does not pass inherited properties, sync', () => testInheritedEnv(execaSync));57 51-test('use extend environment with `extendEnv: true` and `shell: true`', async t => {58+test('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
1+import assert from 'node:assert/strict';2 import {platform} from 'node:process';2-import test from 'ava';3+import test from 'node:test';4+import {assertThrows, assertRejects, assertLike} from '../helpers/assert.js';5 import {execa, execaSync} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 8 setFixtureDirectory();9 10 const isWindows = platform === 'win32';11 10-const testResultCommand = async (t, expected, ...commandArguments) => {11- const {command: failCommand} = await t.throwsAsync(execa('fail.js', commandArguments));12- t.is(failCommand, `fail.js${expected}`);12+const testResultCommand = async (expected, ...commandArguments) => {13+ const {command: failCommand} = await assertRejects(execa('fail.js', commandArguments));14+ assert.equal(failCommand, `fail.js${expected}`);15 16 const {command} = await execa('noop.js', commandArguments);15- t.is(command, `noop.js${expected}`);17+ assert.equal(command, `noop.js${expected}`);18 };19 18-testResultCommand.title = (message, expected) => `result.command is: ${JSON.stringify(expected)}`;20+test('result.command is: " foo bar"', () => testResultCommand(' foo bar', 'foo', 'bar'));21+test('result.command is: " baz quz"', () => testResultCommand(' baz quz', 'baz', 'quz'));22+test('result.command is: ""', () => testResultCommand(''));23 20-test(testResultCommand, ' foo bar', 'foo', 'bar');21-test(testResultCommand, ' baz quz', 'baz', 'quz');22-test(testResultCommand, '');23-24 // eslint-disable-next-line max-params25-const testEscapedCommand = async (t, commandArguments, expectedUnix, expectedWindows, expectedUnixNoIcu = expectedUnix, expectedWindowsNoIcu = expectedWindows) => {25+const 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);30 31- 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 );35 36- t.like(t.throws(() => {36+ assertLike(assertThrows(() => {37 execaSync('fail.js', commandArguments);38 }), {escapedCommand: `fail.js ${expected}`});39 40- t.like(40+ assertLike(41 await execa('noop.js', commandArguments),42 {escapedCommand: `noop.js ${expected}`},43 );44 45- t.like(45+ assertLike(46 execaSync('noop.js', commandArguments),47 {escapedCommand: `noop.js ${expected}`},48 );49 };50 51-test('result.escapedCommand - foo bar', testEscapedCommand, ['foo', 'bar'], 'foo bar', 'foo bar');52-test('result.escapedCommand - foo\\ bar', testEscapedCommand, ['foo bar'], '\'foo bar\'', '"foo bar"');53-test('result.escapedCommand - "foo"', testEscapedCommand, ['"foo"'], '\'"foo"\'', '"""foo"""');54-test('result.escapedCommand - \'foo\'', testEscapedCommand, ['\'foo\''], '\'\'\\\'\'foo\'\\\'\'\'', '"\'foo\'"');55-test('result.escapedCommand - "0"', testEscapedCommand, ['0'], '0', '0');56-test('result.escapedCommand - 0', testEscapedCommand, [0], '0', '0');57-test('result.escapedCommand - *', testEscapedCommand, ['*'], '\'*\'', '"*"');58-test('result.escapedCommand - .', testEscapedCommand, ['.'], '.', '.');59-test('result.escapedCommand - -', testEscapedCommand, ['-'], '-', '-');60-test('result.escapedCommand - _', testEscapedCommand, ['_'], '_', '_');61-test('result.escapedCommand - /', testEscapedCommand, ['/'], '/', '/');62-test('result.escapedCommand - ,', testEscapedCommand, [','], '\',\'', '","');63-test('result.escapedCommand - :', testEscapedCommand, [':'], '\':\'', '":"');64-test('result.escapedCommand - ;', testEscapedCommand, [';'], '\';\'', '";"');65-test('result.escapedCommand - ~', testEscapedCommand, ['~'], '\'~\'', '"~"');66-test('result.escapedCommand - %', testEscapedCommand, ['%'], '\'%\'', '"%"');67-test('result.escapedCommand - $', testEscapedCommand, ['$'], '\'$\'', '"$"');68-test('result.escapedCommand - !', testEscapedCommand, ['!'], '\'!\'', '"!"');69-test('result.escapedCommand - ?', testEscapedCommand, ['?'], '\'?\'', '"?"');70-test('result.escapedCommand - #', testEscapedCommand, ['#'], '\'#\'', '"#"');71-test('result.escapedCommand - &', testEscapedCommand, ['&'], '\'&\'', '"&"');72-test('result.escapedCommand - =', testEscapedCommand, ['='], '\'=\'', '"="');73-test('result.escapedCommand - @', testEscapedCommand, ['@'], '\'@\'', '"@"');74-test('result.escapedCommand - ^', testEscapedCommand, ['^'], '\'^\'', '"^"');75-test('result.escapedCommand - `', testEscapedCommand, ['`'], '\'`\'', '"`"');76-test('result.escapedCommand - |', testEscapedCommand, ['|'], '\'|\'', '"|"');77-test('result.escapedCommand - +', testEscapedCommand, ['+'], '\'+\'', '"+"');78-test('result.escapedCommand - \\', testEscapedCommand, ['\\'], '\'\\\'', '"\\"');79-test('result.escapedCommand - ()', testEscapedCommand, ['()'], '\'()\'', '"()"');80-test('result.escapedCommand - {}', testEscapedCommand, ['{}'], '\'{}\'', '"{}"');81-test('result.escapedCommand - []', testEscapedCommand, ['[]'], '\'[]\'', '"[]"');82-test('result.escapedCommand - <>', testEscapedCommand, ['<>'], '\'<>\'', '"<>"');83-test('result.escapedCommand - ã', testEscapedCommand, ['ã'], '\'ã\'', '"ã"');84-test('result.escapedCommand - \\a', testEscapedCommand, ['\u{7}'], '\'\\u0007\'', '"\\u0007"');85-test('result.escapedCommand - \\b', testEscapedCommand, ['\b'], '\'\\b\'', '"\\b"');86-test('result.escapedCommand - \\e', testEscapedCommand, ['\u{1B}'], '\'\\u001b\'', '"\\u001b"');87-test('result.escapedCommand - \\f', testEscapedCommand, ['\f'], '\'\\f\'', '"\\f"');88-test('result.escapedCommand - \\n', testEscapedCommand, ['\n'], '\'\\n\'', '"\\n"');89-test('result.escapedCommand - \\r\\n', testEscapedCommand, ['\r\n'], '\'\\r\\n\'', '"\\r\\n"');90-test('result.escapedCommand - \\t', testEscapedCommand, ['\t'], '\'\\t\'', '"\\t"');91-test('result.escapedCommand - \\v', testEscapedCommand, ['\v'], '\'\\u000b\'', '"\\u000b"');92-test('result.escapedCommand - \\x01', testEscapedCommand, ['\u{1}'], '\'\\u0001\'', '"\\u0001"');93-test('result.escapedCommand - \\x7f', testEscapedCommand, ['\u{7F}'], '\'\\u007f\'', '"\\u007f"');94-test('result.escapedCommand - \\u0085', testEscapedCommand, ['\u{85}'], '\'\\u0085\'', '"\\u0085"');95-test('result.escapedCommand - \\u2000', testEscapedCommand, ['\u{2000}'], '\'\\u2000\'', '"\\u2000"');96-test('result.escapedCommand - \\u200E', testEscapedCommand, ['\u{200E}'], '\'\\u200e\'', '"\\u200e"', '\'\u{200E}\'', '"\u{200E}"');97-test('result.escapedCommand - \\u2028', testEscapedCommand, ['\u{2028}'], '\'\\u2028\'', '"\\u2028"');98-test('result.escapedCommand - \\u2029', testEscapedCommand, ['\u{2029}'], '\'\\u2029\'', '"\\u2029"');99-test('result.escapedCommand - \\u5555', testEscapedCommand, ['\u{5555}'], '\'\u{5555}\'', '"\u{5555}"');100-test('result.escapedCommand - \\uD800', testEscapedCommand, ['\u{D800}'], '\'\\ud800\'', '"\\ud800"', '\'\u{D800}\'', '"\u{D800}"');101-test('result.escapedCommand - \\uE000', testEscapedCommand, ['\u{E000}'], '\'\\ue000\'', '"\\ue000"', '\'\u{E000}\'', '"\u{E000}"');102-test('result.escapedCommand - \\U1D172', testEscapedCommand, ['\u{1D172}'], '\'\u{1D172}\'', '"\u{1D172}"');103-test('result.escapedCommand - \\U1D173', testEscapedCommand, ['\u{1D173}'], '\'\\U1d173\'', '"\\U1d173"', '\'\u{1D173}\'', '"\u{1D173}"');104-test('result.escapedCommand - \\U10FFFD', testEscapedCommand, ['\u{10FFFD}'], '\'\\U10fffd\'', '"\\U10fffd"', '\'\u{10FFFD}\'', '"\u{10FFFD}"');51+test('result.escapedCommand - foo bar', () => testEscapedCommand(['foo', 'bar'], 'foo bar', 'foo bar'));52+test('result.escapedCommand - foo\\ bar', () => testEscapedCommand(['foo bar'], '\'foo bar\'', '"foo bar"'));53+test('result.escapedCommand - "foo"', () => testEscapedCommand(['"foo"'], '\'"foo"\'', '"""foo"""'));54+test('result.escapedCommand - \'foo\'', () => testEscapedCommand(['\'foo\''], '\'\'\\\'\'foo\'\\\'\'\'', '"\'foo\'"'));55+test('result.escapedCommand - "0"', () => testEscapedCommand(['0'], '0', '0'));56+test('result.escapedCommand - 0', () => testEscapedCommand([0], '0', '0'));57+test('result.escapedCommand - *', () => testEscapedCommand(['*'], '\'*\'', '"*"'));58+test('result.escapedCommand - .', () => testEscapedCommand(['.'], '.', '.'));59+test('result.escapedCommand - -', () => testEscapedCommand(['-'], '-', '-'));60+test('result.escapedCommand - _', () => testEscapedCommand(['_'], '_', '_'));61+test('result.escapedCommand - /', () => testEscapedCommand(['/'], '/', '/'));62+test('result.escapedCommand - ,', () => testEscapedCommand([','], '\',\'', '","'));63+test('result.escapedCommand - :', () => testEscapedCommand([':'], '\':\'', '":"'));64+test('result.escapedCommand - ;', () => testEscapedCommand([';'], '\';\'', '";"'));65+test('result.escapedCommand - ~', () => testEscapedCommand(['~'], '\'~\'', '"~"'));66+test('result.escapedCommand - %', () => testEscapedCommand(['%'], '\'%\'', '"%"'));67+test('result.escapedCommand - $', () => testEscapedCommand(['$'], '\'$\'', '"$"'));68+test('result.escapedCommand - !', () => testEscapedCommand(['!'], '\'!\'', '"!"'));69+test('result.escapedCommand - ?', () => testEscapedCommand(['?'], '\'?\'', '"?"'));70+test('result.escapedCommand - #', () => testEscapedCommand(['#'], '\'#\'', '"#"'));71+test('result.escapedCommand - &', () => testEscapedCommand(['&'], '\'&\'', '"&"'));72+test('result.escapedCommand - =', () => testEscapedCommand(['='], '\'=\'', '"="'));73+test('result.escapedCommand - @', () => testEscapedCommand(['@'], '\'@\'', '"@"'));74+test('result.escapedCommand - ^', () => testEscapedCommand(['^'], '\'^\'', '"^"'));75+test('result.escapedCommand - `', () => testEscapedCommand(['`'], '\'`\'', '"`"'));76+test('result.escapedCommand - |', () => testEscapedCommand(['|'], '\'|\'', '"|"'));77+test('result.escapedCommand - +', () => testEscapedCommand(['+'], '\'+\'', '"+"'));78+test('result.escapedCommand - \\', () => testEscapedCommand(['\\'], '\'\\\'', '"\\"'));79+test('result.escapedCommand - ()', () => testEscapedCommand(['()'], '\'()\'', '"()"'));80+test('result.escapedCommand - {}', () => testEscapedCommand(['{}'], '\'{}\'', '"{}"'));81+test('result.escapedCommand - []', () => testEscapedCommand(['[]'], '\'[]\'', '"[]"'));82+test('result.escapedCommand - <>', () => testEscapedCommand(['<>'], '\'<>\'', '"<>"'));83+test('result.escapedCommand - ã', () => testEscapedCommand(['ã'], '\'ã\'', '"ã"'));84+test('result.escapedCommand - \\a', () => testEscapedCommand(['\u{7}'], '\'\\u0007\'', '"\\u0007"'));85+test('result.escapedCommand - \\b', () => testEscapedCommand(['\b'], '\'\\b\'', '"\\b"'));86+test('result.escapedCommand - \\e', () => testEscapedCommand(['\u{1B}'], '\'\\u001b\'', '"\\u001b"'));87+test('result.escapedCommand - \\f', () => testEscapedCommand(['\f'], '\'\\f\'', '"\\f"'));88+test('result.escapedCommand - \\n', () => testEscapedCommand(['\n'], '\'\\n\'', '"\\n"'));89+test('result.escapedCommand - \\r\\n', () => testEscapedCommand(['\r\n'], '\'\\r\\n\'', '"\\r\\n"'));90+test('result.escapedCommand - \\t', () => testEscapedCommand(['\t'], '\'\\t\'', '"\\t"'));91+test('result.escapedCommand - \\v', () => testEscapedCommand(['\v'], '\'\\u000b\'', '"\\u000b"'));92+test('result.escapedCommand - \\x01', () => testEscapedCommand(['\u{1}'], '\'\\u0001\'', '"\\u0001"'));93+test('result.escapedCommand - \\x7f', () => testEscapedCommand(['\u{7F}'], '\'\\u007f\'', '"\\u007f"'));94+test('result.escapedCommand - \\u0085', () => testEscapedCommand(['\u{85}'], '\'\\u0085\'', '"\\u0085"'));95+test('result.escapedCommand - \\u2000', () => testEscapedCommand(['\u{2000}'], '\'\\u2000\'', '"\\u2000"'));96+test('result.escapedCommand - \\u200E', () => testEscapedCommand(['\u{200E}'], '\'\\u200e\'', '"\\u200e"', '\'\u{200E}\'', '"\u{200E}"'));97+test('result.escapedCommand - \\u2028', () => testEscapedCommand(['\u{2028}'], '\'\\u2028\'', '"\\u2028"'));98+test('result.escapedCommand - \\u2029', () => testEscapedCommand(['\u{2029}'], '\'\\u2029\'', '"\\u2029"'));99+test('result.escapedCommand - \\u5555', () => testEscapedCommand(['\u{5555}'], '\'\u{5555}\'', '"\u{5555}"'));100+test('result.escapedCommand - \\uD800', () => testEscapedCommand(['\u{D800}'], '\'\\ud800\'', '"\\ud800"', '\'\u{D800}\'', '"\u{D800}"'));101+test('result.escapedCommand - \\uE000', () => testEscapedCommand(['\u{E000}'], '\'\\ue000\'', '"\\ue000"', '\'\u{E000}\'', '"\u{E000}"'));102+test('result.escapedCommand - \\U1D172', () => testEscapedCommand(['\u{1D172}'], '\'\u{1D172}\'', '"\u{1D172}"'));103+test('result.escapedCommand - \\U1D173', () => testEscapedCommand(['\u{1D173}'], '\'\\U1d173\'', '"\\U1d173"', '\'\u{1D173}\'', '"\u{1D173}"'));104+test('result.escapedCommand - \\U10FFFD', () => testEscapedCommand(['\u{10FFFD}'], '\'\\U10fffd\'', '"\\U10fffd"', '\'\u{10FFFD}\'', '"\u{10FFFD}"'));105 106 /*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.108 Control characters are excluded, since those are intentionally escaped with a Bash-specific notation instead.109 */110 if (!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 };116 117- 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+ ];133 119- 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
1+import assert from 'node:assert/strict';2 import {PassThrough} from 'node:stream';3 import {spawn} from 'node:child_process';4 import process from 'node:process';4-import test from 'ava';5+import test from 'node:test';6+import {assertThrows} from '../helpers/assert.js';7 import {execa} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 import {fullStdio, getStdio} from '../helpers/stdio.js';10 import {getEarlyErrorSubprocess} from '../helpers/early-error.js';4 unmodified lines15 const getMessage = message => Array.isArray(message)16 ? `"${message[0]}: ${message[1]}" option is incompatible`17 : message;18 17-const testPipeError = async (t, {19+const testPipeError = async ({20 message,21 sourceOptions = {},22 destinationOptions = {},23 getSource = () => execa('empty.js', sourceOptions),3 unmodified lines27 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 };33 32-const testNodeStream = async (t, {34+const 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 };57 58-const assertNodeStream = ({t, message, getSource, from, to, methodName}) => {59- const error = t.throws(() => {58+const 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 };64 65-const testIterable = async (t, {65+const 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 };76 77-test('Must set "all" option to "true" to use .pipe("all")', testPipeError, {77+test('Must set "all" option to "true" to use .pipe("all")', () => testPipeError({78 from: 'all',79 message: '"all" option must be true',80-});81-test('Must set "all" option to "true" to use .duplex("all")', testNodeStream, {80+}));81+test('Must set "all" option to "true" to use .duplex("all")', () => testNodeStream({82 from: 'all',83 message: '"all" option must be true',84-});85-test('Must set "all" option to "true" to use .iterable("all")', testIterable, {84+}));85+test('Must set "all" option to "true" to use .iterable("all")', () => testIterable({86 from: 'all',87 message: '"all" option must be true',88-});89-test('.pipe() cannot pipe to non-subprocesses', testPipeError, {88+}));89+test('.pipe() cannot pipe to non-subprocesses', () => testPipeError({90 getDestination: () => new PassThrough(),91 message: 'an Execa subprocess',92-});93-test('.pipe() cannot pipe to non-Execa subprocesses', testPipeError, {92+}));93+test('.pipe() cannot pipe to non-Execa subprocesses', () => testPipeError({94 getDestination: () => spawn('node', ['--version']),95 message: 'an Execa subprocess',96-});97-test('.pipe() "from" option cannot be "stdin"', testPipeError, {96+}));97+test('.pipe() "from" option cannot be "stdin"', () => testPipeError({98 from: 'stdin',99 message: '"from" must not be',100-});101-test('.duplex() "from" option cannot be "stdin"', testNodeStream, {100+}));101+test('.duplex() "from" option cannot be "stdin"', () => testNodeStream({102 from: 'stdin',103 message: '"from" must not be',104-});105-test('.iterable() "from" option cannot be "stdin"', testIterable, {104+}));105+test('.iterable() "from" option cannot be "stdin"', () => testIterable({106 from: 'stdin',107 message: '"from" must not be',108-});109-test('$.pipe() "from" option cannot be "stdin"', testPipeError, {108+}));109+test('$.pipe() "from" option cannot be "stdin"', () => testPipeError({110 from: 'stdin',111 isScript: true,112 message: '"from" must not be',113-});114-test('.pipe() "to" option cannot be "stdout"', testPipeError, {113+}));114+test('.pipe() "to" option cannot be "stdout"', () => testPipeError({115 to: 'stdout',116 message: '"to" must not be',117-});118-test('.duplex() "to" option cannot be "stdout"', testNodeStream, {117+}));118+test('.duplex() "to" option cannot be "stdout"', () => testNodeStream({119 to: 'stdout',120 message: '"to" must not be',121-});122-test('$.pipe() "to" option cannot be "stdout"', testPipeError, {121+}));122+test('$.pipe() "to" option cannot be "stdout"', () => testPipeError({123 to: 'stdout',124 isScript: true,125 message: '"to" must not be',126-});127-test('.pipe() "from" option cannot be any string', testPipeError, {126+}));127+test('.pipe() "from" option cannot be any string', () => testPipeError({128 from: 'other',129 message: 'must be "stdout", "stderr", "all"',130-});131-test('.duplex() "from" option cannot be any string', testNodeStream, {130+}));131+test('.duplex() "from" option cannot be any string', () => testNodeStream({132 from: 'other',133 message: 'must be "stdout", "stderr", "all"',134-});135-test('.iterable() "from" option cannot be any string', testIterable, {134+}));135+test('.iterable() "from" option cannot be any string', () => testIterable({136 from: 'other',137 message: 'must be "stdout", "stderr", "all"',138-});139-test('.pipe() "to" option cannot be any string', testPipeError, {138+}));139+test('.pipe() "to" option cannot be any string', () => testPipeError({140 to: 'other',141 message: 'must be "stdin"',142-});143-test('.duplex() "to" option cannot be any string', testNodeStream, {142+}));143+test('.duplex() "to" option cannot be any string', () => testNodeStream({144 to: 'other',145 message: 'must be "stdin"',146-});147-test('.pipe() "from" option cannot be a number without "fd"', testPipeError, {146+}));147+test('.pipe() "from" option cannot be a number without "fd"', () => testPipeError({148 from: '1',149 message: 'must be "stdout", "stderr", "all"',150-});151-test('.duplex() "from" option cannot be a number without "fd"', testNodeStream, {150+}));151+test('.duplex() "from" option cannot be a number without "fd"', () => testNodeStream({152 from: '1',153 message: 'must be "stdout", "stderr", "all"',154-});155-test('.iterable() "from" option cannot be a number without "fd"', testIterable, {154+}));155+test('.iterable() "from" option cannot be a number without "fd"', () => testIterable({156 from: '1',157 message: 'must be "stdout", "stderr", "all"',158-});159-test('.pipe() "to" option cannot be a number without "fd"', testPipeError, {158+}));159+test('.pipe() "to" option cannot be a number without "fd"', () => testPipeError({160 to: '0',161 message: 'must be "stdin"',162-});163-test('.duplex() "to" option cannot be a number without "fd"', testNodeStream, {162+}));163+test('.duplex() "to" option cannot be a number without "fd"', () => testNodeStream({164 to: '0',165 message: 'must be "stdin"',166-});167-test('.pipe() "from" option cannot be just "fd"', testPipeError, {166+}));167+test('.pipe() "from" option cannot be just "fd"', () => testPipeError({168 from: 'fd',169 message: 'must be "stdout", "stderr", "all"',170-});171-test('.duplex() "from" option cannot be just "fd"', testNodeStream, {170+}));171+test('.duplex() "from" option cannot be just "fd"', () => testNodeStream({172 from: 'fd',173 message: 'must be "stdout", "stderr", "all"',174-});175-test('.iterable() "from" option cannot be just "fd"', testIterable, {174+}));175+test('.iterable() "from" option cannot be just "fd"', () => testIterable({176 from: 'fd',177 message: 'must be "stdout", "stderr", "all"',178-});179-test('.pipe() "to" option cannot be just "fd"', testPipeError, {178+}));179+test('.pipe() "to" option cannot be just "fd"', () => testPipeError({180 to: 'fd',181 message: 'must be "stdin"',182-});183-test('.duplex() "to" option cannot be just "fd"', testNodeStream, {182+}));183+test('.duplex() "to" option cannot be just "fd"', () => testNodeStream({184 to: 'fd',185 message: 'must be "stdin"',186-});187-test('.pipe() "from" option cannot be a float', testPipeError, {186+}));187+test('.pipe() "from" option cannot be a float', () => testPipeError({188 from: 'fd1.5',189 message: 'must be "stdout", "stderr", "all"',190-});191-test('.duplex() "from" option cannot be a float', testNodeStream, {190+}));191+test('.duplex() "from" option cannot be a float', () => testNodeStream({192 from: 'fd1.5',193 message: 'must be "stdout", "stderr", "all"',194-});195-test('.iterable() "from" option cannot be a float', testIterable, {194+}));195+test('.iterable() "from" option cannot be a float', () => testIterable({196 from: 'fd1.5',197 message: 'must be "stdout", "stderr", "all"',198-});199-test('.pipe() "to" option cannot be a float', testPipeError, {198+}));199+test('.pipe() "to" option cannot be a float', () => testPipeError({200 to: 'fd1.5',201 message: 'must be "stdin"',202-});203-test('.duplex() "to" option cannot be a float', testNodeStream, {202+}));203+test('.duplex() "to" option cannot be a float', () => testNodeStream({204 to: 'fd1.5',205 message: 'must be "stdin"',206-});207-test('.pipe() "from" option cannot be a negative number', testPipeError, {206+}));207+test('.pipe() "from" option cannot be a negative number', () => testPipeError({208 from: 'fd-1',209 message: 'must be "stdout", "stderr", "all"',210-});211-test('.duplex() "from" option cannot be a negative number', testNodeStream, {210+}));211+test('.duplex() "from" option cannot be a negative number', () => testNodeStream({212 from: 'fd-1',213 message: 'must be "stdout", "stderr", "all"',214-});215-test('.iterable() "from" option cannot be a negative number', testIterable, {214+}));215+test('.iterable() "from" option cannot be a negative number', () => testIterable({216 from: 'fd-1',217 message: 'must be "stdout", "stderr", "all"',218-});219-test('.pipe() "to" option cannot be a negative number', testPipeError, {218+}));219+test('.pipe() "to" option cannot be a negative number', () => testPipeError({220 to: 'fd-1',221 message: 'must be "stdin"',222-});223-test('.duplex() "to" option cannot be a negative number', testNodeStream, {222+}));223+test('.duplex() "to" option cannot be a negative number', () => testNodeStream({224 to: 'fd-1',225 message: 'must be "stdin"',226-});227-test('.pipe() "from" option cannot be a non-existing file descriptor', testPipeError, {226+}));227+test('.pipe() "from" option cannot be a non-existing file descriptor', () => testPipeError({228 from: 'fd3',229 message: 'file descriptor does not exist',230-});231-test('.duplex() "from" cannot be a non-existing file descriptor', testNodeStream, {230+}));231+test('.duplex() "from" cannot be a non-existing file descriptor', () => testNodeStream({232 from: 'fd3',233 message: 'file descriptor does not exist',234-});235-test('.iterable() "from" cannot be a non-existing file descriptor', testIterable, {234+}));235+test('.iterable() "from" cannot be a non-existing file descriptor', () => testIterable({236 from: 'fd3',237 message: 'file descriptor does not exist',238-});239-test('.pipe() "to" option cannot be a non-existing file descriptor', testPipeError, {238+}));239+test('.pipe() "to" option cannot be a non-existing file descriptor', () => testPipeError({240 to: 'fd3',241 message: 'file descriptor does not exist',242-});243-test('.duplex() "to" cannot be a non-existing file descriptor', testNodeStream, {242+}));243+test('.duplex() "to" cannot be a non-existing file descriptor', () => testNodeStream({244 to: 'fd3',245 message: 'file descriptor does not exist',246-});247-test('.pipe() "from" option cannot be an input file descriptor', testPipeError, {246+}));247+test('.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-});252-test('.duplex() "from" option cannot be an input file descriptor', testNodeStream, {251+}));252+test('.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-});257-test('.iterable() "from" option cannot be an input file descriptor', testIterable, {256+}));257+test('.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-});262-test('.pipe() "to" option cannot be an output file descriptor', testPipeError, {261+}));262+test('.pipe() "to" option cannot be an output file descriptor', () => testPipeError({263 destinationOptions: fullStdio,264 to: 'fd3',265 message: 'must be a writable stream',266-});267-test('.duplex() "to" option cannot be an output file descriptor', testNodeStream, {266+}));267+test('.duplex() "to" option cannot be an output file descriptor', () => testNodeStream({268 sourceOptions: fullStdio,269 to: 'fd3',270 message: 'must be a writable stream',271-});272-test('.duplex() "to" option on an output file descriptor suggests the input-pipe syntax', testNodeStream, {271+}));272+test('.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-});277-test('.pipe() "to" option cannot be "all"', testPipeError, {276+}));277+test('.pipe() "to" option cannot be "all"', () => testPipeError({278 destinationOptions: fullStdio,279 to: 'all',280 message: 'must be a writable stream',281-});282-test('.duplex() "to" option cannot be "all"', testNodeStream, {281+}));282+test('.duplex() "to" option cannot be "all"', () => testNodeStream({283 sourceOptions: fullStdio,284 to: 'all',285 message: 'must be a writable stream',286-});287-test('Cannot set "stdout" option to "ignore" to use .pipe()', testPipeError, {286+}));287+test('Cannot set "stdout" option to "ignore" to use .pipe()', () => testPipeError({288 sourceOptions: {stdout: 'ignore'},289 message: ['stdout', '\'ignore\''],290-});291-test('Cannot set "stdout" option to "ignore" to use .duplex()', testNodeStream, {290+}));291+test('Cannot set "stdout" option to "ignore" to use .duplex()', () => testNodeStream({292 sourceOptions: {stdout: 'ignore'},293 message: ['stdout', '\'ignore\''],294-});295-test('Cannot set "stdout" option to "ignore" to use .iterable()', testIterable, {294+}));295+test('Cannot set "stdout" option to "ignore" to use .iterable()', () => testIterable({296 sourceOptions: {stdout: 'ignore'},297 message: ['stdout', '\'ignore\''],298-});299-test('Cannot set "stdin" option to "ignore" to use .pipe()', testPipeError, {298+}));299+test('Cannot set "stdin" option to "ignore" to use .pipe()', () => testPipeError({300 destinationOptions: {stdin: 'ignore'},301 message: ['stdin', '\'ignore\''],302-});303-test('Cannot set "stdin" option to "ignore" to use .duplex()', testNodeStream, {302+}));303+test('Cannot set "stdin" option to "ignore" to use .duplex()', () => testNodeStream({304 sourceOptions: {stdin: 'ignore'},305 message: ['stdin', '\'ignore\''],306 writable: true,307-});308-test('Cannot set "stdout" option to "ignore" to use .pipe(1)', testPipeError, {307+}));308+test('Cannot set "stdout" option to "ignore" to use .pipe(1)', () => testPipeError({309 sourceOptions: {stdout: 'ignore'},310 from: 'fd1',311 message: ['stdout', '\'ignore\''],312-});313-test('Cannot set "stdout" option to "ignore" to use .duplex(1)', testNodeStream, {312+}));313+test('Cannot set "stdout" option to "ignore" to use .duplex(1)', () => testNodeStream({314 sourceOptions: {stdout: 'ignore'},315 from: 'fd1',316 message: ['stdout', '\'ignore\''],317-});318-test('Cannot set "stdout" option to "ignore" to use .iterable(1)', testIterable, {317+}));318+test('Cannot set "stdout" option to "ignore" to use .iterable(1)', () => testIterable({319 sourceOptions: {stdout: 'ignore'},320 from: 'fd1',321 message: ['stdout', '\'ignore\''],322-});323-test('Cannot set "stdin" option to "ignore" to use .pipe(0)', testPipeError, {322+}));323+test('Cannot set "stdin" option to "ignore" to use .pipe(0)', () => testPipeError({324 destinationOptions: {stdin: 'ignore'},325 message: ['stdin', '\'ignore\''],326 to: 'fd0',327-});328-test('Cannot set "stdin" option to "ignore" to use .duplex(0)', testNodeStream, {327+}));328+test('Cannot set "stdin" option to "ignore" to use .duplex(0)', () => testNodeStream({329 sourceOptions: {stdin: 'ignore'},330 message: ['stdin', '\'ignore\''],331 to: 'fd0',332-});333-test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', testPipeError, {332+}));333+test('Cannot set "stdout" option to "ignore" to use .pipe("stdout")', () => testPipeError({334 sourceOptions: {stdout: 'ignore'},335 from: 'stdout',336 message: ['stdout', '\'ignore\''],337-});338-test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', testNodeStream, {337+}));338+test('Cannot set "stdout" option to "ignore" to use .duplex("stdout")', () => testNodeStream({339 sourceOptions: {stdout: 'ignore'},340 from: 'stdout',341 message: ['stdout', '\'ignore\''],342-});343-test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', testIterable, {342+}));343+test('Cannot set "stdout" option to "ignore" to use .iterable("stdout")', () => testIterable({344 sourceOptions: {stdout: 'ignore'},345 from: 'stdout',346 message: ['stdout', '\'ignore\''],347-});348-test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', testPipeError, {347+}));348+test('Cannot set "stdin" option to "ignore" to use .pipe("stdin")', () => testPipeError({349 destinationOptions: {stdin: 'ignore'},350 message: ['stdin', '\'ignore\''],351 to: 'stdin',352-});353-test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', testNodeStream, {352+}));353+test('Cannot set "stdin" option to "ignore" to use .duplex("stdin")', () => testNodeStream({354 sourceOptions: {stdin: 'ignore'},355 message: ['stdin', '\'ignore\''],356 to: 'stdin',357-});358-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', testPipeError, {357+}));358+test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe()', () => testPipeError({359 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},360 message: ['stdout', '\'ignore\''],361-});362-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', testNodeStream, {361+}));362+test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex()', () => testNodeStream({363 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},364 message: ['stdout', '\'ignore\''],365-});366-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', testIterable, {365+}));366+test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable()', () => testIterable({367 sourceOptions: {stdout: 'ignore', stderr: 'ignore'},368 message: ['stdout', '\'ignore\''],369-});370-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(1)', testPipeError, {369+}));370+test('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-});375-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(1)', testNodeStream, {374+}));375+test('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-});380-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(1)', testIterable, {379+}));380+test('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-});385-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stdout")', testPipeError, {384+}));385+test('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-});390-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stdout")', testNodeStream, {389+}));390+test('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-});395-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stdout")', testIterable, {394+}));395+test('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-});400-test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', testPipeError, {399+}));400+test('Cannot set "stdio[1]" option to "ignore" to use .pipe()', () => testPipeError({401 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},402 message: ['stdio[1]', '\'ignore\''],403-});404-test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', testNodeStream, {403+}));404+test('Cannot set "stdio[1]" option to "ignore" to use .duplex()', () => testNodeStream({405 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},406 message: ['stdio[1]', '\'ignore\''],407-});408-test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', testIterable, {407+}));408+test('Cannot set "stdio[1]" option to "ignore" to use .iterable()', () => testIterable({409 sourceOptions: {stdio: ['pipe', 'ignore', 'pipe']},410 message: ['stdio[1]', '\'ignore\''],411-});412-test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', testPipeError, {411+}));412+test('Cannot set "stdio[0]" option to "ignore" to use .pipe()', () => testPipeError({413 destinationOptions: {stdio: ['ignore', 'pipe', 'pipe']},414 message: ['stdio[0]', '\'ignore\''],415-});416-test('Cannot set "stdio[0]" option to "ignore" to use .duplex()', testNodeStream, {415+}));416+test('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-});421-test('Cannot set "stdio[1]" option to "ignore" to use .pipe(1)', testPipeError, {420+}));421+test('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-});426-test('Cannot set "stdio[1]" option to "ignore" to use .duplex(1)', testNodeStream, {425+}));426+test('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-});431-test('Cannot set "stdio[1]" option to "ignore" to use .iterable(1)', testIterable, {430+}));431+test('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-});436-test('Cannot set "stdio[0]" option to "ignore" to use .pipe(0)', testPipeError, {435+}));436+test('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-});441-test('Cannot set "stdio[0]" option to "ignore" to use .duplex(0)', testNodeStream, {440+}));441+test('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-});446-test('Cannot set "stdio[1]" option to "ignore" to use .pipe("stdout")', testPipeError, {445+}));446+test('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-});451-test('Cannot set "stdio[1]" option to "ignore" to use .duplex("stdout")', testNodeStream, {450+}));451+test('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-});456-test('Cannot set "stdio[1]" option to "ignore" to use .iterable("stdout")', testIterable, {455+}));456+test('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-});461-test('Cannot set "stdio[0]" option to "ignore" to use .pipe("stdin")', testPipeError, {460+}));461+test('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-});466-test('Cannot set "stdio[0]" option to "ignore" to use .duplex("stdin")', testNodeStream, {465+}));466+test('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-});471-test('Cannot set "stderr" option to "ignore" to use .pipe(2)', testPipeError, {470+}));471+test('Cannot set "stderr" option to "ignore" to use .pipe(2)', () => testPipeError({472 sourceOptions: {stderr: 'ignore'},473 from: 'fd2',474 message: ['stderr', '\'ignore\''],475-});476-test('Cannot set "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {475+}));476+test('Cannot set "stderr" option to "ignore" to use .duplex(2)', () => testNodeStream({477 sourceOptions: {stderr: 'ignore'},478 from: 'fd2',479 message: ['stderr', '\'ignore\''],480-});481-test('Cannot set "stderr" option to "ignore" to use .iterable(2)', testIterable, {480+}));481+test('Cannot set "stderr" option to "ignore" to use .iterable(2)', () => testIterable({482 sourceOptions: {stderr: 'ignore'},483 from: 'fd2',484 message: ['stderr', '\'ignore\''],485-});486-test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {485+}));486+test('Cannot set "stderr" option to "ignore" to use .pipe("stderr")', () => testPipeError({487 sourceOptions: {stderr: 'ignore'},488 from: 'stderr',489 message: ['stderr', '\'ignore\''],490-});491-test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {490+}));491+test('Cannot set "stderr" option to "ignore" to use .duplex("stderr")', () => testNodeStream({492 sourceOptions: {stderr: 'ignore'},493 from: 'stderr',494 message: ['stderr', '\'ignore\''],495-});496-test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {495+}));496+test('Cannot set "stderr" option to "ignore" to use .iterable("stderr")', () => testIterable({497 sourceOptions: {stderr: 'ignore'},498 from: 'stderr',499 message: ['stderr', '\'ignore\''],500-});501-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe(2)', testPipeError, {500+}));501+test('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-});506-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex(2)', testNodeStream, {505+}));506+test('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-});511-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable(2)', testIterable, {510+}));511+test('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-});516-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("stderr")', testPipeError, {515+}));516+test('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-});521-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("stderr")', testNodeStream, {520+}));521+test('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-});526-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("stderr")', testIterable, {525+}));526+test('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-});531-test('Cannot set "stdio[2]" option to "ignore" to use .pipe(2)', testPipeError, {530+}));531+test('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-});536-test('Cannot set "stdio[2]" option to "ignore" to use .duplex(2)', testNodeStream, {535+}));536+test('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-});541-test('Cannot set "stdio[2]" option to "ignore" to use .iterable(2)', testIterable, {540+}));541+test('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-});546-test('Cannot set "stdio[2]" option to "ignore" to use .pipe("stderr")', testPipeError, {545+}));546+test('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-});551-test('Cannot set "stdio[2]" option to "ignore" to use .duplex("stderr")', testNodeStream, {550+}));551+test('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-});556-test('Cannot set "stdio[2]" option to "ignore" to use .iterable("stderr")', testIterable, {555+}));556+test('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-});561-test('Cannot set "stdio[3]" option to "ignore" to use .pipe(3)', testPipeError, {560+}));561+test('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-});566-test('Cannot set "stdio[3]" option to "ignore" to use .duplex(3)', testNodeStream, {565+}));566+test('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-});571-test('Cannot set "stdio[3]" option to "ignore" to use .iterable(3)', testIterable, {570+}));571+test('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-});576-test('Cannot set "stdout" + "stderr" option to "ignore" to use .pipe("all")', testPipeError, {575+}));576+test('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-});581-test('Cannot set "stdout" + "stderr" option to "ignore" to use .duplex("all")', testNodeStream, {580+}));581+test('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-});586-test('Cannot set "stdout" + "stderr" option to "ignore" to use .iterable("all")', testIterable, {585+}));586+test('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-});591-test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .pipe("all")', testPipeError, {590+}));591+test('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-});596-test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .duplex("all")', testNodeStream, {595+}));596+test('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-});601-test('Cannot set "stdio[1]" + "stdio[2]" option to "ignore" to use .iterable("all")', testIterable, {600+}));601+test('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-});606-test('Cannot set "stdout" option to "inherit" to use .pipe()', testPipeError, {605+}));606+test('Cannot set "stdout" option to "inherit" to use .pipe()', () => testPipeError({607 sourceOptions: {stdout: 'inherit'},608 message: ['stdout', '\'inherit\''],609-});610-test('Cannot set "stdout" option to "inherit" to use .duplex()', testNodeStream, {609+}));610+test('Cannot set "stdout" option to "inherit" to use .duplex()', () => testNodeStream({611 sourceOptions: {stdout: 'inherit'},612 message: ['stdout', '\'inherit\''],613-});614-test('Cannot set "stdout" option to "inherit" to use .iterable()', testIterable, {613+}));614+test('Cannot set "stdout" option to "inherit" to use .iterable()', () => testIterable({615 sourceOptions: {stdout: 'inherit'},616 message: ['stdout', '\'inherit\''],617-});618-test('Cannot set "stdin" option to "inherit" to use .pipe()', testPipeError, {617+}));618+test('Cannot set "stdin" option to "inherit" to use .pipe()', () => testPipeError({619 destinationOptions: {stdin: 'inherit'},620 message: ['stdin', '\'inherit\''],621-});622-test('Cannot set "stdin" option to "inherit" to use .duplex()', testNodeStream, {621+}));622+test('Cannot set "stdin" option to "inherit" to use .duplex()', () => testNodeStream({623 sourceOptions: {stdin: 'inherit'},624 message: ['stdin', '\'inherit\''],625 writable: true,626-});627-test('Cannot set "stdout" option to file descriptors to use .pipe()', testPipeError, {626+}));627+test('Cannot set "stdout" option to file descriptors to use .pipe()', () => testPipeError({628 sourceOptions: {stdout: 1},629 message: ['stdout', '1'],630-});631-test('Cannot set "stdout" option to file descriptors to use .duplex()', testNodeStream, {630+}));631+test('Cannot set "stdout" option to file descriptors to use .duplex()', () => testNodeStream({632 sourceOptions: {stdout: 1},633 message: ['stdout', '1'],634-});635-test('Cannot set "stdout" option to file descriptors to use .iterable()', testIterable, {634+}));635+test('Cannot set "stdout" option to file descriptors to use .iterable()', () => testIterable({636 sourceOptions: {stdout: 1},637 message: ['stdout', '1'],638-});639-test('Cannot set "stdin" option to file descriptors to use .pipe()', testPipeError, {638+}));639+test('Cannot set "stdin" option to file descriptors to use .pipe()', () => testPipeError({640 destinationOptions: {stdin: 0},641 message: ['stdin', '0'],642-});643-test('Cannot set "stdin" option to file descriptors to use .duplex()', testNodeStream, {642+}));643+test('Cannot set "stdin" option to file descriptors to use .duplex()', () => testNodeStream({644 sourceOptions: {stdin: 0},645 message: ['stdin', '0'],646 writable: true,647-});648-test('Cannot set "stdout" option to Node.js streams to use .pipe()', testPipeError, {647+}));648+test('Cannot set "stdout" option to Node.js streams to use .pipe()', () => testPipeError({649 sourceOptions: {stdout: process.stdout},650 message: ['stdout', 'Stream'],651-});652-test('Cannot set "stdout" option to Node.js streams to use .duplex()', testNodeStream, {651+}));652+test('Cannot set "stdout" option to Node.js streams to use .duplex()', () => testNodeStream({653 sourceOptions: {stdout: process.stdout},654 message: ['stdout', 'Stream'],655-});656-test('Cannot set "stdout" option to Node.js streams to use .iterable()', testIterable, {655+}));656+test('Cannot set "stdout" option to Node.js streams to use .iterable()', () => testIterable({657 sourceOptions: {stdout: process.stdout},658 message: ['stdout', 'Stream'],659-});660-test('Cannot set "stdin" option to Node.js streams to use .pipe()', testPipeError, {659+}));660+test('Cannot set "stdin" option to Node.js streams to use .pipe()', () => testPipeError({661 destinationOptions: {stdin: process.stdin},662 message: ['stdin', 'Stream'],663-});664-test('Cannot set "stdin" option to Node.js streams to use .duplex()', testNodeStream, {663+}));664+test('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-});669-test('Cannot set "stdio[3]" option to Node.js Writable streams to use .pipe()', testPipeError, {668+}));669+test('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-});674-test('Cannot set "stdio[3]" option to Node.js Writable streams to use .duplex()', testNodeStream, {673+}));674+test('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-});679-test('Cannot set "stdio[3]" option to Node.js Writable streams to use .iterable()', testIterable, {678+}));679+test('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-});684-test('Cannot set "stdio[3]" option to Node.js Readable streams to use .pipe()', testPipeError, {683+}));684+test('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-});689-test('Cannot set "stdio[3]" option to Node.js Readable streams to use .duplex()', testNodeStream, {688+}));689+test('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+}));694 695-test('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',695+test('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 });702 705-test('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',703+test('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 });710 715-test('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',711+test('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
1+import assert from 'node:assert/strict';2 import {existsSync} from 'node:fs';3 import path from 'node:path';4 import process from 'node:process';5 import {pathToFileURL} from 'node:url';5-import test from 'ava';6+import test from 'node:test';7+import {assertRejects} from '../helpers/assert.js';8 import {execa, $} from '../../index.js';9 import {setFixtureDirectory, PATH_KEY} from '../helpers/fixtures-directory.js';10 11 setFixtureDirectory();12 process.env.FOO = 'foo';13 14 const isWindows = process.platform === 'win32';15 const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;14-const 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 it17+const C8_BINARY_NAMES = isWindows ? ['c8.cmd', 'c8.exe', 'c8.bat', 'c8.ps1', 'c8'] : ['c8'];18 19 const getPathWithoutCommand = commandNames => {20 const newPath = process.env[PATH_KEY]21 .split(path.delimiter)1 unmodified line23 .join(path.delimiter);24 return {[PATH_KEY]: newPath};25 };26 24-const pathWithoutAva = getPathWithoutCommand(AVA_BINARY_NAMES);27+const pathWithoutC8 = getPathWithoutCommand(C8_BINARY_NAMES);28 26-test('preferLocal: true', async t => {27- await t.notThrowsAsync(execa('ava', ['--version'], {preferLocal: true, env: pathWithoutAva}));29+test('preferLocal: true', async () => {30+ await assert.doesNotReject(execa('c8', ['--version'], {preferLocal: true, env: pathWithoutC8}));31 });32 30-test('preferLocal: false', async t => {31- await t.throwsAsync(execa('ava', ['--version'], {preferLocal: false, env: pathWithoutAva}), {message: ENOENT_REGEXP});33+test('preferLocal: false', async () => {34+ await assertRejects(execa('c8', ['--version'], {preferLocal: false, env: pathWithoutC8}), {message: ENOENT_REGEXP});35 });36 34-test('preferLocal: undefined', async t => {35- await t.throwsAsync(execa('ava', ['--version'], {env: pathWithoutAva}), {message: ENOENT_REGEXP});37+test('preferLocal: undefined', async () => {38+ await assertRejects(execa('c8', ['--version'], {env: pathWithoutC8}), {message: ENOENT_REGEXP});39 });40 38-test('preferLocal: undefined with $', async t => {39- await t.notThrowsAsync($('ava', ['--version'], {env: pathWithoutAva}));41+test('preferLocal: undefined with $', async () => {42+ await assert.doesNotReject($('c8', ['--version'], {env: pathWithoutC8}));43 });44 42-test('preferLocal: undefined with $.sync', t => {43- t.notThrows(() => $.sync('ava', ['--version'], {env: pathWithoutAva}));45+test('preferLocal: undefined with $.sync', () => {46+ assert.doesNotThrow(() => $.sync('c8', ['--version'], {env: pathWithoutC8}));47 });48 46-test('preferLocal: undefined with execa.pipe`...`', async t => {47- await t.throwsAsync(() => execa('node', ['--version']).pipe({env: pathWithoutAva})`ava --version`);49+test('preferLocal: undefined with execa.pipe`...`', async () => {50+ await assertRejects(() => execa('node', ['--version']).pipe({env: pathWithoutC8})`c8 --version`);51 });52 50-test('preferLocal: undefined with $.pipe`...`', async t => {51- await t.notThrows(() => $('node', ['--version']).pipe({env: pathWithoutAva})`ava --version`);53+test('preferLocal: undefined with $.pipe`...`', async () => {54+ await assert.doesNotThrow(() => $('node', ['--version']).pipe({env: pathWithoutC8})`c8 --version`);55 });56 54-test('preferLocal: undefined with execa.pipe()', async t => {55- await t.throwsAsync(() => execa('node', ['--version']).pipe('ava', ['--version'], {env: pathWithoutAva}));57+test('preferLocal: undefined with execa.pipe()', async () => {58+ await assertRejects(() => execa('node', ['--version']).pipe('c8', ['--version'], {env: pathWithoutC8}));59 });60 58-test('preferLocal: undefined with $.pipe()', async t => {59- await t.notThrows(() => $('node', ['--version']).pipe('ava', ['--version'], {env: pathWithoutAva}));61+test('preferLocal: undefined with $.pipe()', async () => {62+ await assert.doesNotThrow(() => $('node', ['--version']).pipe('c8', ['--version'], {env: pathWithoutC8}));63 });64 62-test('localDir option', async t => {65+test('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 });71 69-test('localDir option can be a URL', async t => {72+test('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
1+import assert from 'node:assert/strict';2 import path from 'node:path';3 import process from 'node:process';3-import test from 'ava';4-import {pathExists} from 'path-exists';4+import test from 'node:test';5+import {text} from 'node:stream/consumers';6 import tempfile from 'tempfile';7+import {pathExists} from 'path-exists';8 import {9 execa,10 execaSync,11 execaNode,12 $,13 } from '../../index.js';14+import {assertThrows} from '../helpers/assert.js';15 import {setFixtureDirectory, PATH_KEY, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';16 import {foobarString} from '../helpers/input.js';17 18 setFixtureDirectory();1 unmodified line20 21 /*22 A 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.23 Options are therefore always kept on null-prototype objects.21-Those tests are serial since they temporarily modify `Object.prototype`.24+Those tests must run one at a time since they temporarily modify `Object.prototype`.25 */26 const 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 lines41 const testPollutedPreferLocal = async (t, execaMethod) => {42 pollutePrototype(t, {preferLocal: true, localDir: POLLUTED_LOCAL_DIRECTORY});43 44 const {stdout} = await execaMethod('node', printPath);42- t.false(stdout.includes(pollutedBinaryDirectory));45+ assert.ok(!stdout.includes(pollutedBinaryDirectory));46 };47 45-test.serial('Polluted "preferLocal" and "localDir" are ignored', testPollutedPreferLocal, execa);46-test.serial('Polluted "preferLocal" and "localDir" are ignored, sync', testPollutedPreferLocal, execaSync);48+test('Polluted "preferLocal" and "localDir" are ignored', t => testPollutedPreferLocal(t, execa));49+test('Polluted "preferLocal" and "localDir" are ignored, sync', t => testPollutedPreferLocal(t, execaSync));50 51 // `$` sets `preferLocal: true` itself, so only `localDir` can be injected49-test.serial('Polluted "localDir" is ignored, $', async t => {52+test('Polluted "localDir" is ignored, $', async t => {53 pollutePrototype(t, {localDir: POLLUTED_LOCAL_DIRECTORY});54 55 const {stdout} = await $('node', printPath);53- t.false(stdout.includes(pollutedBinaryDirectory));56+ assert.ok(!stdout.includes(pollutedBinaryDirectory));57 });58 59 // The `stdout` option can redirect the output to an arbitrary file60 const testPollutedStdout = async (t, execaMethod) => {61 const filePath = tempfile();62 pollutePrototype(t, {stdout: {file: filePath}});63 64 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 };68 66-test.serial('Polluted "stdout" is ignored', testPollutedStdout, execa);67-test.serial('Polluted "stdout" is ignored, sync', testPollutedStdout, execaSync);69+test('Polluted "stdout" is ignored', t => testPollutedStdout(t, execa));70+test('Polluted "stdout" is ignored, sync', t => testPollutedStdout(t, execaSync));71 72 // The `stdin` option can feed the contents of an arbitrary file to the subprocess70-test.serial('Polluted "stdin" is ignored', async t => {73+test('Polluted "stdin" is ignored', async t => {74 pollutePrototype(t, {stdin: {file: 'noop.js'}});75 76 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 });81 82 // The `verbose` option can be a function, which Execa calls with each log line83 const testPollutedVerbose = async (t, execaMethod) => {4 unmodified lines88 },89 });90 91 await execaMethod('noop.js', [foobarString]);89- t.false(isVerboseCalled);92+ assert.equal(isVerboseCalled, false);93 };94 92-test.serial('Polluted "verbose" is ignored', testPollutedVerbose, execa);93-test.serial('Polluted "verbose" is ignored, sync', testPollutedVerbose, execaSync);94-test.serial('Polluted "verbose" is ignored, $', testPollutedVerbose, $);95+test('Polluted "verbose" is ignored', t => testPollutedVerbose(t, execa));96+test('Polluted "verbose" is ignored, sync', t => testPollutedVerbose(t, execaSync));97+test('Polluted "verbose" is ignored, $', t => testPollutedVerbose(t, $));98 // `execaNode()` resolves the file from the current directory, not from `PATH`96-test.serial('Polluted "verbose" is ignored, execaNode()', testPollutedVerbose, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments));97-test.serial('Polluted "verbose" is ignored, .pipe()', testPollutedVerbose, (file, commandArguments) => execa('empty.js').pipe(file, commandArguments));99+test('Polluted "verbose" is ignored, execaNode()', t => testPollutedVerbose(t, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments)));100+test('Polluted "verbose" is ignored, .pipe()', t => testPollutedVerbose(t, (file, commandArguments) => execa('empty.js').pipe(file, commandArguments)));101 99-test.serial('Polluted "extendEnv" is ignored', async t => {102+test('Polluted "extendEnv" is ignored', async t => {103 pollutePrototype(t, {extendEnv: false});104 105 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 });108 109 // `piped` is set by Execa itself, only when using `.pipe()`. It decides which icon the `verbose` option prints.110 const testPollutedPiped = async (t, execaMethod) => {4 unmodified lines115 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 };122 120-test.serial('Polluted "piped" is ignored', testPollutedPiped, execa);121-test.serial('Polluted "piped" is ignored, sync', testPollutedPiped, execaSync);123+test('Polluted "piped" is ignored', t => testPollutedPiped(t, execa));124+test('Polluted "piped" is ignored, sync', t => testPollutedPiped(t, execaSync));125 126 /*127 `mapArguments()` returns `{options, isSync}`, which are method-specific. Neither is a user-facing option.128 A polluted `options` would replace every option at once, and a polluted `isSync` would switch the execution mode.1 unmodified line130 const testPollutedMappedOptions = async (t, execaMethod) => {131 pollutePrototype(t, {options: {cwd: path.resolve('/')}});132 133 const {cwd} = await execaMethod('noop.js', [foobarString]);131- t.is(cwd, process.cwd());134+ assert.equal(cwd, process.cwd());135 };136 134-test.serial('Polluted "options" is ignored', testPollutedMappedOptions, execa);135-test.serial('Polluted "options" is ignored, sync', testPollutedMappedOptions, execaSync);137+test('Polluted "options" is ignored', t => testPollutedMappedOptions(t, execa));138+test('Polluted "options" is ignored, sync', t => testPollutedMappedOptions(t, execaSync));139 140 const testPollutedIsSync = async (t, execaMethod) => {141 pollutePrototype(t, {isSync: true});142 143 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 };148 146-test.serial('Polluted "isSync" is ignored', testPollutedIsSync, execa);147-test.serial('Polluted "isSync" is ignored, $', testPollutedIsSync, $);148-test.serial('Polluted "isSync" is ignored, execaNode()', testPollutedIsSync, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments));149+test('Polluted "isSync" is ignored', t => testPollutedIsSync(t, execa));150+test('Polluted "isSync" is ignored, $', t => testPollutedIsSync(t, $));151+test('Polluted "isSync" is ignored, execaNode()', t => testPollutedIsSync(t, (file, commandArguments) => execaNode(path.join(FIXTURES_DIRECTORY, file), commandArguments)));152 150-test.serial('Polluted "cancelSignal" is ignored', async t => {153+test('Polluted "cancelSignal" is ignored', async t => {154 pollutePrototype(t, {cancelSignal: {}});155 156 const {stdout} = await execa('noop.js', [foobarString]);154- t.is(stdout, foobarString);157+ assert.equal(stdout, foobarString);158 });159 160 // 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.158-test.serial('Polluted "stdout" is not interpolated in template expressions', t => {161+test('Polluted "stdout" is not interpolated in template expressions', t => {162 pollutePrototype(t, {stdout: foobarString});163 161- t.throws(() => $`noop.js ${{}}`, {message: /Unexpected "object" in template expression/});164+ assertThrows(() => $`noop.js ${{}}`, {message: /Unexpected "object" in template expression/});165 });166 167 // A result with `stdout: 'ignore'` has no own `stdout` property, so it must not read the polluted one165-test.serial('Polluted "stdout" is not read from template expression results', t => {168+test('Polluted "stdout" is not read from template expression results', t => {169 pollutePrototype(t, {stdout: foobarString});170 168- 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 });173 174 /*175 Unlike the options, `child_process` intentionally passes the inherited properties of the `env` option to the subprocess.2 unmodified lines178 const testPollutedEnvironment = async (t, execaMethod, options) => {179 pollutePrototype(t, {POLLUTED_VARIABLE: 'polluted'});180 181 const {stdout} = await execaMethod(process.execPath, ['-p', 'process.env.POLLUTED_VARIABLE'], options);179- t.is(stdout, 'undefined');182+ assert.equal(stdout, 'undefined');183 };184 182-test.serial('Polluted environment variables are ignored', testPollutedEnvironment, execa, {});183-test.serial('Polluted environment variables are ignored, sync', testPollutedEnvironment, execaSync, {});184-test.serial('Polluted environment variables are ignored, extendEnv false', testPollutedEnvironment, execa, {extendEnv: false});185-test.serial('Polluted environment variables are ignored, preferLocal', testPollutedEnvironment, execa, {preferLocal: true});185+test('Polluted environment variables are ignored', t => testPollutedEnvironment(t, execa, {}));186+test('Polluted environment variables are ignored, sync', t => testPollutedEnvironment(t, execaSync, {}));187+test('Polluted environment variables are ignored, extendEnv false', t => testPollutedEnvironment(t, execa, {extendEnv: false}));188+test('Polluted environment variables are ignored, preferLocal', t => testPollutedEnvironment(t, execa, {preferLocal: true}));189 190 const testPollutedPath = async (t, execaMethod) => {191 pollutePrototype(t, {[PATH_KEY]: POLLUTED_LOCAL_DIRECTORY});192 193 const {stdout} = await execaMethod(process.execPath, printPath, {extendEnv: false});191- t.is(stdout, 'undefined');194+ assert.equal(stdout, 'undefined');195 };196 194-test.serial('Polluted PATH is ignored', testPollutedPath, execa);195-test.serial('Polluted PATH is ignored, sync', testPollutedPath, execaSync);197+test('Polluted PATH is ignored', t => testPollutedPath(t, execa));198+test('Polluted PATH is ignored, sync', t => testPollutedPath(t, execaSync));199+200+// The options of `subprocess.pipe()`, `subprocess.readable()` and `subprocess.iterable()` must not be injected either, e.g. `from` can read another file descriptor instead201+const stdoutString = 'public';202+203+const testPollutedFrom = async (t, readOutput) => {204+ pollutePrototype(t, {from: 'stderr'});205+206+ const subprocess = execa('noop-both.js', [stdoutString, foobarString]);207+ assert.equal(await readOutput(subprocess), stdoutString);208+ await subprocess;209+};210+211+test('Polluted "from" is ignored, .pipe()', t => testPollutedFrom(t, async subprocess => {212+ const {stdout} = await subprocess.pipe(execa('stdin.js'));213+ return stdout;214+}));215+test('Polluted "from" is ignored, .pipe``', t => testPollutedFrom(t, async subprocess => {216+ const {stdout} = await subprocess.pipe`stdin.js`;217+ return stdout;218+}));219+test('Polluted "from" is ignored, .readable()', t => testPollutedFrom(t, async subprocess => {220+ const output = await text(subprocess.readable({}));221+ return output.trim();222+}));223+test('Polluted "from" is ignored, .iterable()', t => testPollutedFrom(t, async subprocess => {224+ const lines = await Array.fromAsync(subprocess.iterable({}));225+ return lines.join('');226+}));227+228+// The options of the IPC methods must not be injected either, e.g. `filter` can drop every message229+test('Polluted "filter" is ignored, .getOneMessage()', async t => {230+ pollutePrototype(t, {filter: () => false});231+232+ const subprocess = execa('ipc-send.js', {ipc: true});233+ assert.equal(await subprocess.getOneMessage(), foobarString);234+ await subprocess;235+});236+237+// The result of a successful subprocess has no `error` property, which must not be read from the prototype238+test('Polluted "error" is ignored', async t => {239+ pollutePrototype(t, {error: foobarString});240+241+ const {failed} = await execa('empty.js');242+ assert.equal(failed, false);243+});244+245+// An early error has a `failed` property, which must not be read from the prototype of `child_process.spawnSync()`'s result246+test('Polluted "failed" is ignored, sync', t => {247+ pollutePrototype(t, {failed: true});248+249+ const {stdout} = execaSync('noop.js', [foobarString]);250+ assert.equal(stdout, foobarString);251+});252+253+// A subprocess which failed to spawn has no output, which must not read its `error` from the prototype254+test('Polluted "error" is ignored, sync early error', t => {255+ pollutePrototype(t, {error: foobarString});256+257+ const {code} = execaSync('non-existent-command', {reject: false});258+ assert.equal(code, 'ENOENT');259+});modified:test/arguments/shell.js+8 added-7 removed
1+import assert from 'node:assert/strict';2 import process from 'node:process';3 import {pathToFileURL} from 'node:url';3-import test from 'ava';4+import test from 'node:test';5 import {whichCommand} from 'which-command';6 import {execa} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {identity} from '../helpers/stdio.js';2 unmodified lines11 process.env.FOO = 'foo';12 13 const isWindows = process.platform === 'win32';14 14-test('can use `options.shell: true`', async t => {15+test('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 });19 19-const testShellPath = async (t, mapPath) => {20+const 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 };26 26-test('can use `options.shell: string`', testShellPath, identity);27-test('can use `options.shell: file URL`', testShellPath, pathToFileURL);27+test('can use `options.shell: string`', () => testShellPath(identity));28+test('can use `options.shell: file URL`', () => testShellPath(pathToFileURL));modified:test/arguments/specific.js+29 added-29 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {foobarString} from '../helpers/input.js';6 7 setFixtureDirectory();8 8-// eslint-disable-next-line max-params9-const testPriorityOrder = async (t, buffer, bufferStdout, bufferStderr, execaMethod) => {9+const 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 };14 15-test('buffer: {stdout, fd1}', testPriorityOrder, {stdout: true, fd1: false}, true, true, execa);16-test('buffer: {stdout, all}', testPriorityOrder, {stdout: true, all: false}, true, false, execa);17-test('buffer: {fd1, all}', testPriorityOrder, {fd1: true, all: false}, true, false, execa);18-test('buffer: {stderr, fd2}', testPriorityOrder, {stderr: true, fd2: false}, true, true, execa);19-test('buffer: {stderr, all}', testPriorityOrder, {stderr: true, all: false}, false, true, execa);20-test('buffer: {fd2, all}', testPriorityOrder, {fd2: true, all: false}, false, true, execa);21-test('buffer: {fd1, stdout}', testPriorityOrder, {fd1: false, stdout: true}, true, true, execa);22-test('buffer: {all, stdout}', testPriorityOrder, {all: false, stdout: true}, true, false, execa);23-test('buffer: {all, fd1}', testPriorityOrder, {all: false, fd1: true}, true, false, execa);24-test('buffer: {fd2, stderr}', testPriorityOrder, {fd2: false, stderr: true}, true, true, execa);25-test('buffer: {all, stderr}', testPriorityOrder, {all: false, stderr: true}, false, true, execa);26-test('buffer: {all, fd2}', testPriorityOrder, {all: false, fd2: true}, false, true, execa);27-test('buffer: {stdout, fd1}, sync', testPriorityOrder, {stdout: true, fd1: false}, true, true, execaSync);28-test('buffer: {stdout, all}, sync', testPriorityOrder, {stdout: true, all: false}, true, false, execaSync);29-test('buffer: {fd1, all}, sync', testPriorityOrder, {fd1: true, all: false}, true, false, execaSync);30-test('buffer: {stderr, fd2}, sync', testPriorityOrder, {stderr: true, fd2: false}, true, true, execaSync);31-test('buffer: {stderr, all}, sync', testPriorityOrder, {stderr: true, all: false}, false, true, execaSync);32-test('buffer: {fd2, all}, sync', testPriorityOrder, {fd2: true, all: false}, false, true, execaSync);33-test('buffer: {fd1, stdout}, sync', testPriorityOrder, {fd1: false, stdout: true}, true, true, execaSync);34-test('buffer: {all, stdout}, sync', testPriorityOrder, {all: false, stdout: true}, true, false, execaSync);35-test('buffer: {all, fd1}, sync', testPriorityOrder, {all: false, fd1: true}, true, false, execaSync);36-test('buffer: {fd2, stderr}, sync', testPriorityOrder, {fd2: false, stderr: true}, true, true, execaSync);37-test('buffer: {all, stderr}, sync', testPriorityOrder, {all: false, stderr: true}, false, true, execaSync);38-test('buffer: {all, fd2}, sync', testPriorityOrder, {all: false, fd2: true}, false, true, execaSync);15+test('buffer: {stdout, fd1}', () => testPriorityOrder({stdout: true, fd1: false}, true, true, execa));16+test('buffer: {stdout, all}', () => testPriorityOrder({stdout: true, all: false}, true, false, execa));17+test('buffer: {fd1, all}', () => testPriorityOrder({fd1: true, all: false}, true, false, execa));18+test('buffer: {stderr, fd2}', () => testPriorityOrder({stderr: true, fd2: false}, true, true, execa));19+test('buffer: {stderr, all}', () => testPriorityOrder({stderr: true, all: false}, false, true, execa));20+test('buffer: {fd2, all}', () => testPriorityOrder({fd2: true, all: false}, false, true, execa));21+test('buffer: {fd1, stdout}', () => testPriorityOrder({fd1: false, stdout: true}, true, true, execa));22+test('buffer: {all, stdout}', () => testPriorityOrder({all: false, stdout: true}, true, false, execa));23+test('buffer: {all, fd1}', () => testPriorityOrder({all: false, fd1: true}, true, false, execa));24+test('buffer: {fd2, stderr}', () => testPriorityOrder({fd2: false, stderr: true}, true, true, execa));25+test('buffer: {all, stderr}', () => testPriorityOrder({all: false, stderr: true}, false, true, execa));26+test('buffer: {all, fd2}', () => testPriorityOrder({all: false, fd2: true}, false, true, execa));27+test('buffer: {stdout, fd1}, sync', () => testPriorityOrder({stdout: true, fd1: false}, true, true, execaSync));28+test('buffer: {stdout, all}, sync', () => testPriorityOrder({stdout: true, all: false}, true, false, execaSync));29+test('buffer: {fd1, all}, sync', () => testPriorityOrder({fd1: true, all: false}, true, false, execaSync));30+test('buffer: {stderr, fd2}, sync', () => testPriorityOrder({stderr: true, fd2: false}, true, true, execaSync));31+test('buffer: {stderr, all}, sync', () => testPriorityOrder({stderr: true, all: false}, false, true, execaSync));32+test('buffer: {fd2, all}, sync', () => testPriorityOrder({fd2: true, all: false}, false, true, execaSync));33+test('buffer: {fd1, stdout}, sync', () => testPriorityOrder({fd1: false, stdout: true}, true, true, execaSync));34+test('buffer: {all, stdout}, sync', () => testPriorityOrder({all: false, stdout: true}, true, false, execaSync));35+test('buffer: {all, fd1}, sync', () => testPriorityOrder({all: false, fd1: true}, true, false, execaSync));36+test('buffer: {fd2, stderr}, sync', () => testPriorityOrder({fd2: false, stderr: true}, true, true, execaSync));37+test('buffer: {all, stderr}, sync', () => testPriorityOrder({all: false, stderr: true}, false, true, execaSync));38+test('buffer: {all, fd2}, sync', () => testPriorityOrder({all: false, fd2: true}, false, true, execaSync));modified:test/convert/concurrent.js+114 added-114 removed
1+import assert from 'node:assert/strict';2 import {setTimeout} from 'node:timers/promises';2-import test from 'ava';3+import test from 'node:test';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString} from '../helpers/input.js';7 import {fullReadableStdio} from '../helpers/stdio.js';13 unmodified lines21 stream.end(foobarString);22 await setTimeout(0);23 };24 24-// eslint-disable-next-line max-params25-const endSameWritable = async (t, stream, secondStream, subprocess, fdNumber) => {25+const endSameWritable = async (stream, secondStream, subprocess, fdNumber) => {26 await endStream(stream);27- t.true(subprocess.stdio[fdNumber].writable);27+ assert.ok(subprocess.stdio[fdNumber].writable);28 29 await endStream(secondStream);30- t.false(subprocess.stdio[fdNumber].writable);30+ assert.ok(!subprocess.stdio[fdNumber].writable);31 };32 33 // eslint-disable-next-line max-params34-const endDifferentWritable = async (t, stream, secondStream, subprocess, fdNumber = 0, secondFdNumber = 3) => {34+const 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);38 39 await endStream(secondStream);40- t.false(subprocess.stdio[secondFdNumber].writable);40+ assert.ok(!subprocess.stdio[secondFdNumber].writable);41 };42 43-const testReadableTwice = async (t, fdNumber, from) => {43+const 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});47 48 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 };54 55-test('Can call .readable() twice on same file descriptor', testReadableTwice, 1);56-test('Can call .readable({from: "stderr"}) twice on same file descriptor', testReadableTwice, 2, 'stderr');55+test('Can call .readable() twice on same file descriptor', () => testReadableTwice(1));56+test('Can call .readable({from: "stderr"}) twice on same file descriptor', () => testReadableTwice(2, 'stderr'));57 58-const testWritableTwice = async (t, fdNumber, to, options) => {58+const 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});62 63 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 };70 71-test('Can call .writable() twice on same file descriptor', testWritableTwice, 0, undefined, {});72-test('Can call .writable({to: "fd3"}) twice on same file descriptor', testWritableTwice, 3, 'fd3', fullReadableStdio());71+test('Can call .writable() twice on same file descriptor', () => testWritableTwice(0, undefined, {}));72+test('Can call .writable({to: "fd3"}) twice on same file descriptor', () => testWritableTwice(3, 'fd3', fullReadableStdio()));73 74-const testDuplexTwice = async (t, fdNumber, to, options) => {74+const 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});78 79 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 };87 88-test('Can call .duplex() twice on same file descriptor', testDuplexTwice, 0, undefined, {});89-test('Can call .duplex({to: "fd3"}) twice on same file descriptor', testDuplexTwice, 3, 'fd3', fullReadableStdio());88+test('Can call .duplex() twice on same file descriptor', () => testDuplexTwice(0, undefined, {}));89+test('Can call .duplex({to: "fd3"}) twice on same file descriptor', () => testDuplexTwice(3, 'fd3', fullReadableStdio()));90 91-test('Can call .duplex() twice on same readable file descriptor but different writable one', async t => {91+test('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'});95 96 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 });104 105-test('Can call .readable() twice on different file descriptors', async t => {105+test('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'});109 110 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 });118 119-test('Can call .writable() twice on different file descriptors', async t => {119+test('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'});123 124 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 });131 132-test('Can call .duplex() twice on different file descriptors', async t => {132+test('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'});136 137 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 });145 146-test('Can call .readable() and .writable()', async t => {146+test('Can call .readable() and .writable()', async () => {147 const subprocess = getReadWriteSubprocess();148 const stream = subprocess.writable();149 const secondStream = subprocess.readable();150 stream.end(foobarString);151 152 await Promise.all([153 finishedStream(stream),154- assertStreamOutput(t, secondStream),154+ assertStreamOutput(secondStream),155 ]);156- await assertSubprocessOutput(t, subprocess);156+ await assertSubprocessOutput(subprocess);157 });158 159-test('Can call .writable() and .duplex()', async t => {159+test('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'});163 164 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 });172 173-test('Can call .readable() and .duplex()', async t => {173+test('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);178 179 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 });186 187-test('Can error one of two .readable() on same file descriptor', async t => {187+test('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);193 194 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 });200 201-test('Can error both .readable() on same file descriptor', async t => {201+test('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);208 209 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 });216 217-test('Can error one of two .readable() on different file descriptors', async t => {217+test('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);223 224 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 });232 233-test('Can error both .readable() on different file descriptors', async t => {233+test('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);240 241 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 });248 249-test('Can error one of two .writable() on same file descriptor', async t => {249+test('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);256 257 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 });263 264-test('Can error both .writable() on same file descriptor', async t => {264+test('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);271 272 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 });279 280-test('Can error one of two .writable() on different file descriptors', async t => {280+test('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);287 288 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 });296 297-test('Can error both .writable() on different file descriptors', async t => {297+test('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);304 305 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 });312 313-test('Can error one of two .duplex() on same file descriptor', async t => {313+test('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);320 321 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 });327 328-test('Can error both .duplex() on same file descriptor', async t => {328+test('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);335 336 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 });342 343-test('Can error one of two .duplex() on different file descriptors', async t => {343+test('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);350 351 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 });358 359-test('Can error both .duplex() on different file descriptors', async t => {359+test('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);366 367 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
1+import assert from 'node:assert/strict';2+import {pipeline} from 'node:stream/promises';3+import {text} from 'node:stream/consumers';4+import test from 'node:test';5 import {6 compose,7 Readable,8 Writable,9 PassThrough,10 } from 'node:stream';7-import {pipeline} from 'node:stream/promises';8-import {text} from 'node:stream/consumers';9-import test from 'ava';11+import {assertRejects, assertLike} from '../helpers/assert.js';12 import {execa} from '../../index.js';13 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';14 import {15 finishedStream,19 unmodified lines35 import {defaultHighWaterMark} from '../helpers/stream.js';36 37 setFixtureDirectory();38 37-test('.duplex() success', async t => {39+test('.duplex() success', async () => {40 const subprocess = getReadWriteSubprocess();41 const stream = subprocess.duplex();42 41- 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);47 48 stream.end(foobarString);49 48- await assertStreamOutput(t, stream);49- await assertSubprocessOutput(t, subprocess);50+ await assertStreamOutput(stream);51+ await assertSubprocessOutput(subprocess);52 });53 52-// eslint-disable-next-line max-params53-const testReadableDuplexDefault = async (t, fdNumber, from, options, hasResult) => {54+const 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);58 58- 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 };62 62-test('.duplex() can use stdout', testReadableDuplexDefault, 1, 'stdout', {}, true);63-test('.duplex() can use stderr', testReadableDuplexDefault, 2, 'stderr', {}, true);64-test('.duplex() can use output stdio[*]', testReadableDuplexDefault, 3, 'fd3', fullStdio, true);65-test('.duplex() uses stdout by default', testReadableDuplexDefault, 1, undefined, {}, true);66-test('.duplex() does not use stderr by default', testReadableDuplexDefault, 2, undefined, {}, false);67-test('.duplex() does not use stdio[*] by default', testReadableDuplexDefault, 3, undefined, fullStdio, false);68-test('.duplex() uses stdout even if stderr is "ignore"', testReadableDuplexDefault, 1, 'stdout', {stderr: 'ignore'}, true);69-test('.duplex() uses stderr even if stdout is "ignore"', testReadableDuplexDefault, 2, 'stderr', {stdout: 'ignore'}, true);70-test('.duplex() uses stdout if "all" is used', testReadableDuplexDefault, 1, 'all', {all: true}, true);71-test('.duplex() uses stderr if "all" is used', testReadableDuplexDefault, 2, 'all', {all: true}, true);63+test('.duplex() can use stdout', () => testReadableDuplexDefault(1, 'stdout', {}, true));64+test('.duplex() can use stderr', () => testReadableDuplexDefault(2, 'stderr', {}, true));65+test('.duplex() can use output stdio[*]', () => testReadableDuplexDefault(3, 'fd3', fullStdio, true));66+test('.duplex() uses stdout by default', () => testReadableDuplexDefault(1, undefined, {}, true));67+test('.duplex() does not use stderr by default', () => testReadableDuplexDefault(2, undefined, {}, false));68+test('.duplex() does not use stdio[*] by default', () => testReadableDuplexDefault(3, undefined, fullStdio, false));69+test('.duplex() uses stdout even if stderr is "ignore"', () => testReadableDuplexDefault(1, 'stdout', {stderr: 'ignore'}, true));70+test('.duplex() uses stderr even if stdout is "ignore"', () => testReadableDuplexDefault(2, 'stderr', {stdout: 'ignore'}, true));71+test('.duplex() uses stdout if "all" is used', () => testReadableDuplexDefault(1, 'all', {all: true}, true));72+test('.duplex() uses stderr if "all" is used', () => testReadableDuplexDefault(2, 'all', {all: true}, true));73 73-const testWritableDuplexDefault = async (t, fdNumber, to, options) => {74+const testWritableDuplexDefault = async (fdNumber, to, options) => {75 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], options);76 const stream = subprocess.duplex({to});77 78 stream.end(foobarString);79 79- await assertStreamOutput(t, stream, foobarString);80- await assertSubprocessOutput(t, subprocess);80+ await assertStreamOutput(stream, foobarString);81+ await assertSubprocessOutput(subprocess);82 };83 83-test('.duplex() can use stdin', testWritableDuplexDefault, 0, 'stdin', {});84-test('.duplex() can use input stdio[*]', testWritableDuplexDefault, 3, 'fd3', fullReadableStdio());85-test('.duplex() can use input stdio[*] with { value: "pipe", input: true }', testWritableDuplexDefault, 3, 'fd3', getStdio(3, {value: 'pipe', input: true}));86-test('.duplex() uses stdin by default', testWritableDuplexDefault, 0, undefined, {});84+test('.duplex() can use stdin', () => testWritableDuplexDefault(0, 'stdin', {}));85+test('.duplex() can use input stdio[*]', () => testWritableDuplexDefault(3, 'fd3', fullReadableStdio()));86+test('.duplex() can use input stdio[*] with { value: "pipe", input: true }', () => testWritableDuplexDefault(3, 'fd3', getStdio(3, {value: 'pipe', input: true})));87+test('.duplex() uses stdin by default', () => testWritableDuplexDefault(0, undefined, {}));88 88-test('.duplex() abort -> subprocess fail', async t => {89+test('.duplex() abort -> subprocess fail', async () => {90 const subprocess = getReadWriteSubprocess();91 const stream = subprocess.duplex();92 const textPromise = text(stream);93 94 stream.destroy();95 95- 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 });104 104-test('.duplex() error -> subprocess fail', async t => {105+test('.duplex() error -> subprocess fail', async () => {106 const subprocess = getReadWriteSubprocess();107 const stream = subprocess.duplex();108 109 const cause = new Error(foobarString);110 stream.destroy(cause);111 111- 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 });119 119-test('.duplex() can be used with Stream.pipeline()', async t => {120+test('.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 line126 await pipeline(inputStream, stream, outputStream);127 128 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 });133 133-test('.duplex() can error with Stream.pipeline()', async t => {134+test('.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();139 139- 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});143 144 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 });149 149-test('.duplex() can pipe to errored stream with Stream.pipeline()', async t => {150+test('.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 lines159 // 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));168 168- 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 });175 175-test('.duplex() can be piped to errored stream with Stream.pipeline()', async t => {176+test('.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();181 182 const cause = new Error('test');183 inputStream.destroy(cause);184 184- 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));187 187- 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 });193 193-test('.duplex() can be used with Stream.compose()', async t => {194+test('.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();199 199- await assertStreamOutput(t, compose(inputStream, stream, outputStream));200- await assertSubprocessOutput(t, subprocess);200+ await assertStreamOutput(compose(inputStream, stream, outputStream));201+ await assertSubprocessOutput(subprocess);202 });203 203-test('.duplex() has the right highWaterMark', async t => {204+test('.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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString} from '../helpers/input.js';7 import {fullStdio, assertEpipe} from '../helpers/stdio.js';16 unmodified lines24 25 return lines;26 };27 26-const errorArrayFromAsync = async (t, cause, asyncIterable, lines = []) => {28+const errorArrayFromAsync = async (cause, asyncIterable, lines = []) => {29 const {value} = await asyncIterable.next();30 lines.push(value);31 await asyncIterable.throw(cause);32 };33 32-const throwsAsync = async (t, asyncIterable, arrayFromAsyncMethod) => {34+const 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 };39 38-const 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);40+const assertStdoutAbort = (subprocess, error, cause) => {41+ assertProcessNormalExit(error, 1);42+ assertEpipe(error.stderr);43+ assertWritableAborted(subprocess.stdin);44+ assert.equal(subprocess.stderr.readableEnded, true);45 46 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 };52 51-const testSuccess = async (t, fdNumber, from, options = {}) => {53+const 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 };57 56-test('Uses stdout by default', testSuccess, 1, undefined);57-test('Can iterate successfully on stdout', testSuccess, 1, 'stdout');58-test('Can iterate successfully on stderr', testSuccess, 2, 'stderr');59-test('Can iterate successfully on stdio[*]', testSuccess, 3, 'fd3', fullStdio);58+test('Uses stdout by default', () => testSuccess(1, undefined));59+test('Can iterate successfully on stdout', () => testSuccess(1, 'stdout'));60+test('Can iterate successfully on stderr', () => testSuccess(2, 'stderr'));61+test('Can iterate successfully on stdio[*]', () => testSuccess(3, 'fd3', fullStdio));62 61-test('Can iterate successfully on all', async t => {63+test('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 });67 66-test('Can iterate using Symbol.asyncIterator', async t => {68+test('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 });72 71-const assertMultipleCalls = async (t, iterable, iterableTwo) => {72- t.not(iterable, iterableTwo);73+const 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 };80 79-test('Can be called multiple times', async t => {81+test('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 });87 86-test('Can be called on different file descriptors', async t => {88+test('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 });94 93-test('Wait for the subprocess exit', async t => {95+test('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 });101 100-test('Wait for the subprocess exit on iterator.return()', async t => {102+test('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 });108 107-test('Wait for the subprocess exit on iterator.throw()', async t => {109+test('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 });117 116-test('Abort stdout on iterator.return()', async t => {118+test('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 });125 124-test('Abort stdout on iterator.throw()', async t => {126+test('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 });134 133-test('Propagate subprocess failure', async t => {135+test('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 });141 140-const testStdoutError = async (t, destroyStdout, isAbort, cause) => {142+const 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 });147 146- 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 };153 152-test('Propagate stdout abort', testStdoutError, subprocessStdout => subprocessStdout.destroy(), true);153-test('Propagate stdout error', testStdoutError, (subprocessStdout, cause) => subprocessStdout.destroy(cause), false, new Error(foobarString));154-test('Propagate stdout "error" event', testStdoutError, (subprocessStdout, cause) => subprocessStdout.emit('error', cause), true, new Error(foobarString));154+test('Propagate stdout abort', () => testStdoutError(subprocessStdout => subprocessStdout.destroy(), true));155+test('Propagate stdout error', () => testStdoutError((subprocessStdout, cause) => subprocessStdout.destroy(cause), false, new Error(foobarString)));156+test('Propagate stdout "error" event', () => testStdoutError((subprocessStdout, cause) => subprocessStdout.emit('error', cause), true, new Error(foobarString)));modified:test/convert/readable.js+178 added-177 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3+import {pipeline} from 'node:stream/promises';4+import {text} from 'node:stream/consumers';5+import {setTimeout} from 'node:timers/promises';6+import test from 'node:test';7 import {8 compose,9 Readable,10 Writable,11 PassThrough,12 } from 'node:stream';8-import {pipeline} from 'node:stream/promises';9-import {text} from 'node:stream/consumers';10-import {setTimeout} from 'node:timers/promises';11-import test from 'ava';13+import {assertRejects, assertLike} from '../helpers/assert.js';14 import {execa} from '../../index.js';15 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';16 import {17 finishedStream,18 unmodified lines36 import {defaultHighWaterMark, defaultObjectHighWaterMark} from '../helpers/stream.js';37 38 setFixtureDirectory();39 38-test('.readable() success', async t => {40+test('.readable() success', async () => {41 const subprocess = getReadableSubprocess();42 const stream = subprocess.readable();43 42- 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);48 47- await assertStreamOutput(t, stream);48- await assertSubprocessOutput(t, subprocess);49+ await assertStreamOutput(stream);50+ await assertSubprocessOutput(subprocess);51 });52 51-// eslint-disable-next-line max-params52-const testReadableDefault = async (t, fdNumber, from, options, hasResult) => {53+const testReadableDefault = async (fdNumber, from, options, hasResult) => {54 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], options);55 const stream = subprocess.readable({from});56 56- 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 };60 60-test('.readable() can use stdout', testReadableDefault, 1, 'stdout', {}, true);61-test('.readable() can use stderr', testReadableDefault, 2, 'stderr', {}, true);62-test('.readable() can use stdio[*]', testReadableDefault, 3, 'fd3', fullStdio, true);63-test('.readable() uses stdout by default', testReadableDefault, 1, undefined, {}, true);64-test('.readable() does not use stderr by default', testReadableDefault, 2, undefined, {}, false);65-test('.readable() does not use stdio[*] by default', testReadableDefault, 3, undefined, fullStdio, false);66-test('.readable() uses stdout even if stderr is "ignore"', testReadableDefault, 1, 'stdout', {stderr: 'ignore'}, true);67-test('.readable() uses stderr even if stdout is "ignore"', testReadableDefault, 2, 'stderr', {stdout: 'ignore'}, true);68-test('.readable() uses stdout if "all" is used', testReadableDefault, 1, 'all', {all: true}, true);69-test('.readable() uses stderr if "all" is used', testReadableDefault, 2, 'all', {all: true}, true);61+test('.readable() can use stdout', () => testReadableDefault(1, 'stdout', {}, true));62+test('.readable() can use stderr', () => testReadableDefault(2, 'stderr', {}, true));63+test('.readable() can use stdio[*]', () => testReadableDefault(3, 'fd3', fullStdio, true));64+test('.readable() uses stdout by default', () => testReadableDefault(1, undefined, {}, true));65+test('.readable() does not use stderr by default', () => testReadableDefault(2, undefined, {}, false));66+test('.readable() does not use stdio[*] by default', () => testReadableDefault(3, undefined, fullStdio, false));67+test('.readable() uses stdout even if stderr is "ignore"', () => testReadableDefault(1, 'stdout', {stderr: 'ignore'}, true));68+test('.readable() uses stderr even if stdout is "ignore"', () => testReadableDefault(2, 'stderr', {stdout: 'ignore'}, true));69+test('.readable() uses stdout if "all" is used', () => testReadableDefault(1, 'all', {all: true}, true));70+test('.readable() uses stderr if "all" is used', () => testReadableDefault(2, 'all', {all: true}, true));71 71-const testBuffering = async (t, methodName) => {72+const testBuffering = async methodName => {73 const subprocess = execa('noop-stdin-fd.js', ['1'], {buffer: false});74 const stream = subprocess[methodName]();75 76 subprocess.stdin.write(foobarString);77 await once(subprocess.stdout, 'readable');78 subprocess.stdin.end();79 79- await assertStreamOutput(t, stream);80+ await assertStreamOutput(stream);81 };82 82-test('.readable() buffers until read', testBuffering, 'readable');83-test('.duplex() buffers until read', testBuffering, 'duplex');83+test('.readable() buffers until read', () => testBuffering('readable'));84+test('.duplex() buffers until read', () => testBuffering('duplex'));85 85-test('.readable() abort -> subprocess fail', async t => {86+test('.readable() abort -> subprocess fail', async () => {87 const subprocess = execa('noop-repeat.js');88 const stream = subprocess.readable();89 90 stream.destroy();91 91- 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 });100 100-test('.readable() error -> subprocess fail', async t => {101+test('.readable() error -> subprocess fail', async () => {102 const subprocess = execa('noop-repeat.js');103 const stream = subprocess.readable();104 105 const cause = new Error(foobarString);106 stream.destroy(cause);107 107- 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 });116 116-const testStdoutAbort = async (t, methodName) => {117+const testStdoutAbort = async methodName => {118 const subprocess = execa('ipc-echo.js', {ipc: true});119 const stream = subprocess[methodName]();120 121 subprocess.stdout.destroy();122 123 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 };135 135-test('subprocess.stdout abort + no more writes -> .readable() error + subprocess success', testStdoutAbort, 'readable');136-test('subprocess.stdout abort + no more writes -> .duplex() error + subprocess success', testStdoutAbort, 'duplex');136+test('subprocess.stdout abort + no more writes -> .readable() error + subprocess success', () => testStdoutAbort('readable'));137+test('subprocess.stdout abort + no more writes -> .duplex() error + subprocess success', () => testStdoutAbort('duplex'));138 138-const testStdoutError = async (t, methodName) => {139+const testStdoutError = async methodName => {140 const subprocess = execa('ipc-echo.js', {ipc: true});141 const stream = subprocess[methodName]();142 143 const cause = new Error(foobarString);144 subprocess.stdout.destroy(cause);145 146 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);157 157- await assertSubprocessError(t, subprocess, error);158+ await assertSubprocessError(subprocess, error);159 };160 160-test('subprocess.stdout error + no more writes -> .readable() error + subprocess fail', testStdoutError, 'readable');161-test('subprocess.stdout error + no more writes -> .duplex() error + subprocess fail', testStdoutError, 'duplex');161+test('subprocess.stdout error + no more writes -> .readable() error + subprocess fail', () => testStdoutError('readable'));162+test('subprocess.stdout error + no more writes -> .duplex() error + subprocess fail', () => testStdoutError('duplex'));163 163-const testStdinAbortWrites = async (t, methodName) => {164+const testStdinAbortWrites = async methodName => {165 const subprocess = getReadWriteSubprocess();166 const stream = subprocess[methodName]();167 168 subprocess.stdout.destroy();169 subprocess.stdin.end(foobarString);170 170- 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 };178 178-test('subprocess.stdout abort + more writes -> .readable() error + subprocess fail', testStdinAbortWrites, 'readable');179-test('subprocess.stdout abort + more writes -> .duplex() error + subprocess fail', testStdinAbortWrites, 'duplex');179+test('subprocess.stdout abort + more writes -> .readable() error + subprocess fail', () => testStdinAbortWrites('readable'));180+test('subprocess.stdout abort + more writes -> .duplex() error + subprocess fail', () => testStdinAbortWrites('duplex'));181 181-const testStdinErrorWrites = async (t, methodName) => {182+const testStdinErrorWrites = async methodName => {183 const subprocess = getReadWriteSubprocess();184 const stream = subprocess[methodName]();185 186 const cause = new Error(foobarString);187 subprocess.stdout.destroy(cause);188 subprocess.stdin.end(foobarString);189 189- 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 };197 197-test('subprocess.stdout error + more writes -> .readable() error + subprocess fail', testStdinErrorWrites, 'readable');198-test('subprocess.stdout error + more writes -> .duplex() error + subprocess fail', testStdinErrorWrites, 'duplex');198+test('subprocess.stdout error + more writes -> .readable() error + subprocess fail', () => testStdinErrorWrites('readable'));199+test('subprocess.stdout error + more writes -> .duplex() error + subprocess fail', () => testStdinErrorWrites('duplex'));200 200-test('.readable() can be used with Stream.pipeline()', async t => {201+test('.readable() can be used with Stream.pipeline()', async () => {202 const subprocess = getReadableSubprocess();203 const stream = subprocess.readable();204 const outputStream = new PassThrough();205 206 await pipeline(stream, outputStream);207 208 await finishedStream(stream);208- await assertStreamOutput(t, outputStream);209- await assertSubprocessOutput(t, subprocess);209+ await assertStreamOutput(outputStream);210+ await assertSubprocessOutput(subprocess);211 });212 212-test('.readable() can error with Stream.pipeline()', async t => {213+test('.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();217 217- 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});221 221- 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 });226 226-test('.readable() can pipe to errored stream with Stream.pipeline()', async t => {227+test('.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 lines234 235 // 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));242 242- 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 });248 248-test('.readable() can be used with Stream.compose()', async t => {249+test('.readable() can be used with Stream.compose()', async () => {250 const subprocess = getReadableSubprocess();251 const stream = subprocess.readable();252 const outputStream = new PassThrough();253 253- await assertStreamOutput(t, compose(stream, outputStream));254- await assertSubprocessOutput(t, subprocess);254+ await assertStreamOutput(compose(stream, outputStream));255+ await assertSubprocessOutput(subprocess);256 });257 257-test('.readable() works with objectMode', async t => {258+test('.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);263 263- await assertStreamChunks(t, stream, [foobarObject]);264- await assertSubprocessOutput(t, subprocess, [foobarObject]);264+ await assertStreamChunks(stream, [foobarObject]);265+ await assertSubprocessOutput(subprocess, [foobarObject]);266 });267 267-test('.duplex() works with objectMode and reads', async t => {268+test('.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);276 276- await assertStreamChunks(t, stream, [foobarObject]);277- await assertSubprocessOutput(t, subprocess, [foobarObject]);277+ await assertStreamChunks(stream, [foobarObject]);278+ await assertSubprocessOutput(subprocess, [foobarObject]);279 });280 280-test('.readable() works with default encoding', async t => {281+test('.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);285 285- await assertStreamChunks(t, stream, [foobarBuffer]);286- await assertSubprocessOutput(t, subprocess, foobarString);286+ await assertStreamChunks(stream, [foobarBuffer]);287+ await assertSubprocessOutput(subprocess, foobarString);288 });289 289-test('.duplex() works with default encoding', async t => {290+test('.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);295 295- await assertStreamChunks(t, stream, [foobarBuffer]);296- await assertSubprocessOutput(t, subprocess, foobarString);296+ await assertStreamChunks(stream, [foobarBuffer]);297+ await assertSubprocessOutput(subprocess, foobarString);298 });299 299-test('.readable() works with encoding "utf8"', async t => {300+test('.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');305 305- await assertStreamChunks(t, stream, [foobarString]);306- await assertSubprocessOutput(t, subprocess, foobarString);306+ await assertStreamChunks(stream, [foobarString]);307+ await assertSubprocessOutput(subprocess, foobarString);308 });309 309-test('.duplex() works with encoding "utf8"', async t => {310+test('.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);316 316- await assertStreamChunks(t, stream, [foobarString]);317- await assertSubprocessOutput(t, subprocess, foobarString);317+ await assertStreamChunks(stream, [foobarString]);318+ await assertSubprocessOutput(subprocess, foobarString);319 });320 320-test('.readable() has the right highWaterMark', async t => {321+test('.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 });327 327-test('.readable() can iterate over lines', async t => {328+test('.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}));331 332 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 });336 336-test('.readable() can wait for data', async t => {337+test('.readable() can wait for data', async () => {338 const subprocess = execa('noop.js', {stdout: getOutputsAsyncGenerator([foobarString, foobarString])(false, true)});339 const stream = subprocess.readable();340 340- 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);350 351 await finishedStream(stream);351- await assertSubprocessOutput(t, subprocess, `${foobarString}${foobarString}`);352+ await assertSubprocessOutput(subprocess, `${foobarString}${foobarString}`);353 });354 354-const testBufferData = async (t, methodName) => {355+const testBufferData = async methodName => {356 const chunk = '.'.repeat(defaultHighWaterMark).repeat(2);357 const subprocess = getReadWriteSubprocess();358 const stream = subprocess[methodName]();359 subprocess.stdin.end(chunk);360 360- await assertStreamOutput(t, stream, chunk);361- await assertSubprocessOutput(t, subprocess, chunk);361+ await assertStreamOutput(stream, chunk);362+ await assertSubprocessOutput(subprocess, chunk);363 };364 364-test('.readable() can buffer data', testBufferData, 'readable');365-test('.duplex() can buffer data', testBufferData, 'duplex');365+test('.readable() can buffer data', () => testBufferData('readable'));366+test('.duplex() can buffer data', () => testBufferData('duplex'));367 367-const assertDataEvents = async (t, stream, subprocess) => {368+const assertDataEvents = async (stream, subprocess) => {369 const [output] = await once(stream, 'data');369- t.is(output.toString(), foobarString);370+ assert.equal(output.toString(), foobarString);371 372 await finishedStream(stream);372- await assertSubprocessOutput(t, subprocess);373+ await assertSubprocessOutput(subprocess);374 };375 375-test('.readable() can be read with "data" events', async t => {376+test('.readable() can be read with "data" events', async () => {377 const subprocess = getReadableSubprocess();378 const stream = subprocess.readable();379 379- await assertDataEvents(t, stream, subprocess);380+ await assertDataEvents(stream, subprocess);381 });382 382-test('.duplex() can be read with "data" events', async t => {383+test('.duplex() can be read with "data" events', async () => {384 const subprocess = getReadWriteSubprocess();385 const stream = subprocess.duplex();386 stream.end(foobarString);387 387- await assertDataEvents(t, stream, subprocess);388+ await assertDataEvents(stream, subprocess);389 });390 390-const assertPause = async (t, stream, subprocess) => {391+const assertPause = async (stream, subprocess) => {392 const onceData = once(stream, 'data');393 stream.pause();394 394- 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);400 400- t.false(await Promise.race([onceData, false]));401+ assert.ok(!await Promise.race([onceData, false]));402 403 stream.resume();404 const [output] = await onceData;404- t.is(output.toString(), foobarString);405+ assert.equal(output.toString(), foobarString);406 407 await finishedStream(stream);407- await assertSubprocessOutput(t, subprocess);408+ await assertSubprocessOutput(subprocess);409 };410 410-test('.readable() can be paused', async t => {411+test('.readable() can be paused', async () => {412 const subprocess = getReadableSubprocess();413 const stream = subprocess.readable();414 414- await assertPause(t, stream, subprocess);415+ await assertPause(stream, subprocess);416 });417 417-test('.duplex() can be paused', async t => {418+test('.duplex() can be paused', async () => {419 const subprocess = getReadWriteSubprocess();420 const stream = subprocess.duplex();421 stream.end(foobarString);422 422- await assertPause(t, stream, subprocess);423+ await assertPause(stream, subprocess);424 });425 426 // This feature does not work on Node 18.427 // @todo: remove after dropping support for Node 18.428 if (majorNodeVersion >= 20) {428- const testHighWaterMark = async (t, methodName) => {429+ const testHighWaterMark = async methodName => {430 const subprocess = execa('stdin.js');431 const stream = subprocess[methodName]();432 433 let count = 0;5 unmodified lines439 }440 441 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 };448 448- 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 }452 452-const testBigOutput = async (t, methodName) => {453+const testBigOutput = async methodName => {454 const bigChunk = '.'.repeat(1e6);455 const subprocess = execa('stdin.js', {input: bigChunk});456 const stream = subprocess[methodName]();457 457- await assertStreamOutput(t, stream, bigChunk);458- await assertSubprocessOutput(t, subprocess, bigChunk);458+ await assertStreamOutput(stream, bigChunk);459+ await assertSubprocessOutput(subprocess, bigChunk);460 };461 461-test('.readable() with big output', testBigOutput, 'readable');462-test('.duplex() with big output', testBigOutput, 'duplex');462+test('.readable() with big output', () => testBigOutput('readable'));463+test('.duplex() with big output', () => testBigOutput('duplex'));modified:test/convert/shared.js+37 added-21 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects, assertThrows} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {7 finishedStream,5 unmodified lines13 import {foobarString} from '../helpers/input.js';14 15 setFixtureDirectory();16 15-const testSubprocessFail = async (t, methodName) => {17+const testSubprocessFail = async methodName => {18 const subprocess = getReadWriteSubprocess();19 const stream = subprocess[methodName]();20 21 const cause = new Error(foobarString);22 subprocess.kill(cause);23 22- 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);28 27- await assertSubprocessError(t, subprocess, error);29+ await assertSubprocessError(subprocess, error);30 };31 30-test('subprocess fail -> .readable() error', testSubprocessFail, 'readable');31-test('subprocess fail -> .writable() error', testSubprocessFail, 'writable');32-test('subprocess fail -> .duplex() error', testSubprocessFail, 'duplex');32+test('subprocess fail -> .readable() error', () => testSubprocessFail('readable'));33+test('subprocess fail -> .writable() error', () => testSubprocessFail('writable'));34+test('subprocess fail -> .duplex() error', () => testSubprocessFail('duplex'));35 34-const testErrorEvent = async (t, methodName) => {36+const 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 };43 42-test('.readable() requires listening to "error" event', testErrorEvent, 'readable');43-test('.writable() requires listening to "error" event', testErrorEvent, 'writable');44-test('.duplex() requires listening to "error" event', testErrorEvent, 'duplex');44+test('.readable() requires listening to "error" event', () => testErrorEvent('readable'));45+test('.writable() requires listening to "error" event', () => testErrorEvent('writable'));46+test('.duplex() requires listening to "error" event', () => testErrorEvent('duplex'));47 46-const testSubprocessError = async (t, methodName) => {48+const 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 };55 54-test('Do not need to await subprocess with .readable()', testSubprocessError, 'readable');55-test('Do not need to await subprocess with .writable()', testSubprocessError, 'writable');56-test('Do not need to await subprocess with .duplex()', testSubprocessError, 'duplex');56+test('Do not need to await subprocess with .readable()', () => testSubprocessError('readable'));57+test('Do not need to await subprocess with .writable()', () => testSubprocessError('writable'));58+test('Do not need to await subprocess with .duplex()', () => testSubprocessError('duplex'));59+60+const 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+};68+69+test('.readable() cannot use null options', () => testNullOptions('readable'));70+test('.writable() cannot use null options', () => testNullOptions('writable'));71+test('.duplex() cannot use null options', () => testNullOptions('duplex'));72+test('.iterable() cannot use null options', () => testNullOptions('iterable'));modified:test/convert/web.js+27 added-26 removed
1+import assert from 'node:assert/strict';2 import {ReadableStream, WritableStream} from 'node:stream/web';2-import test from 'ava';3+import test from 'node:test';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {7 assertStreamOutput,14 unmodified lines22 await writer.write(new TextEncoder().encode(input));23 await writer.close();24 };25 25-test('.readableStream() success', async t => {26+test('.readableStream() success', async () => {27 const subprocess = getReadableSubprocess();28 const stream = subprocess.readableStream();29 29- t.true(stream instanceof ReadableStream);30+ assert.ok(stream instanceof ReadableStream);31 31- await assertStreamOutput(t, stream);32- await assertSubprocessOutput(t, subprocess);32+ await assertStreamOutput(stream);33+ await assertSubprocessOutput(subprocess);34 });35 35-test('.readableStream() can use from', async t => {36+test('.readableStream() can use from', async () => {37 const subprocess = execa('noop-fd.js', ['2', foobarString]);38 const stream = subprocess.readableStream({from: 'stderr'});39 39- await assertStreamOutput(t, stream);40+ await assertStreamOutput(stream);41 });42 42-test('.writableStream() success', async t => {43+test('.writableStream() success', async () => {44 const subprocess = getWritableSubprocess();45 const stream = subprocess.writableStream();46 46- t.true(stream instanceof WritableStream);47+ assert.ok(stream instanceof WritableStream);48 49 await writeToStream(stream);49- await assertSubprocessOutput(t, subprocess, foobarString, 2);50+ await assertSubprocessOutput(subprocess, foobarString, 2);51 });52 52-test('.writableStream() can use to', async t => {53+test('.writableStream() can use to', async () => {54 const subprocess = execa('stdin-fd.js', ['0']);55 const stream = subprocess.writableStream({to: 'stdin'});56 57 await writeToStream(stream);57- await assertSubprocessOutput(t, subprocess);58+ await assertSubprocessOutput(subprocess);59 });60 60-test('.transformStream() success', async t => {61+test('.transformStream() success', async () => {62 const subprocess = getReadWriteSubprocess();63 const {readable, writable} = subprocess.transformStream();64 64- t.true(readable instanceof ReadableStream);65- t.true(writable instanceof WritableStream);65+ assert.ok(readable instanceof ReadableStream);66+ assert.ok(writable instanceof WritableStream);67 68 await writeToStream(writable);68- await assertStreamOutput(t, readable);69- await assertSubprocessOutput(t, subprocess);69+ await assertStreamOutput(readable);70+ await assertSubprocessOutput(subprocess);71 });72 72-test('subprocess fail -> .readableStream() error', async t => {73+test('subprocess fail -> .readableStream() error', async () => {74 const subprocess = getReadWriteSubprocess();75 const stream = subprocess.readableStream();76 77 const cause = new Error(foobarString);78 subprocess.kill(cause);79 79- await assertStreamReadError(t, stream, {cause});80- await assertSubprocessError(t, subprocess, {cause});80+ await assertStreamReadError(stream, {cause});81+ await assertSubprocessError(subprocess, {cause});82 });83 83-test('subprocess fail -> .writableStream() error', async t => {84+test('subprocess fail -> .writableStream() error', async () => {85 const subprocess = getReadWriteSubprocess();86 const stream = subprocess.writableStream();87 const writer = stream.getWriter();88 89 const cause = new Error(foobarString);90 subprocess.kill(cause);91 91- await assertPromiseError(t, writer.closed, {cause});92- await assertSubprocessError(t, subprocess, {cause});92+ await assertPromiseError(writer.closed, {cause});93+ await assertSubprocessError(subprocess, {cause});94 });95 95-test('subprocess fail -> .transformStream() error', async t => {96+test('subprocess fail -> .transformStream() error', async () => {97 const subprocess = getReadWriteSubprocess();98 const {readable} = subprocess.transformStream();99 100 const cause = new Error(foobarString);101 subprocess.kill(cause);102 102- 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
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {compose, Readable, Writable} from 'node:stream';4 import {pipeline} from 'node:stream/promises';5 import {text} from 'node:stream/consumers';6 import {setTimeout, scheduler} from 'node:timers/promises';7 import {promisify} from 'node:util';7-import test from 'ava';8+import test from 'node:test';9+import {assertRejects, assertLike} from '../helpers/assert.js';10 import {execa} from '../../index.js';11 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';12 import {13 finishedStream,23 unmodified lines37 import {defaultHighWaterMark, defaultObjectHighWaterMark} from '../helpers/stream.js';38 39 setFixtureDirectory();40 39-test('.writable() success', async t => {41+test('.writable() success', async () => {42 const subprocess = getWritableSubprocess();43 const stream = subprocess.writable();44 43- 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);49 50 stream.end(foobarString);51 52 await finishedStream(stream);51- await assertSubprocessOutput(t, subprocess, foobarString, 2);53+ await assertSubprocessOutput(subprocess, foobarString, 2);54 });55 54-const testWritableDefault = async (t, fdNumber, to, options) => {56+const testWritableDefault = async (fdNumber, to, options) => {57 const subprocess = execa('stdin-fd.js', [`${fdNumber}`], options);58 const stream = subprocess.writable({to});59 60 stream.end(foobarString);61 62 await finishedStream(stream);61- await assertSubprocessOutput(t, subprocess);63+ await assertSubprocessOutput(subprocess);64 };65 64-test('.writable() can use stdin', testWritableDefault, 0, 'stdin', {});65-test('.writable() can use stdio[*]', testWritableDefault, 3, 'fd3', fullReadableStdio());66-test('.writable() can use stdio[*] with { value: "pipe", input: true }', testWritableDefault, 3, 'fd3', getStdio(3, {value: 'pipe', input: true}));67-test('.writable() can use stdio[*] with [{ value: "pipe", input: true }, "pipe"]', testWritableDefault, 3, 'fd3', getStdio(3, [{value: 'pipe', input: true}, 'pipe']));68-test('.writable() uses stdin by default', testWritableDefault, 0, undefined, {});66+test('.writable() can use stdin', () => testWritableDefault(0, 'stdin', {}));67+test('.writable() can use stdio[*]', () => testWritableDefault(3, 'fd3', fullReadableStdio()));68+test('.writable() can use stdio[*] with { value: "pipe", input: true }', () => testWritableDefault(3, 'fd3', getStdio(3, {value: 'pipe', input: true})));69+test('.writable() can use stdio[*] with [{ value: "pipe", input: true }, "pipe"]', () => testWritableDefault(3, 'fd3', getStdio(3, [{value: 'pipe', input: true}, 'pipe'])));70+test('.writable() uses stdin by default', () => testWritableDefault(0, undefined, {}));71 70-test('.writable() hangs until ended', async t => {72+test('.writable() hangs until ended', async () => {73 const subprocess = getReadWriteSubprocess();74 const stream = subprocess.writable();75 76 stream.write(foobarString);77 await setTimeout(1e2);78 stream.end();79 80 await finishedStream(stream);79- await assertSubprocessOutput(t, subprocess);81+ await assertSubprocessOutput(subprocess);82 });83 82-test('.duplex() hangs until ended', async t => {84+test('.duplex() hangs until ended', async () => {85 const subprocess = getReadWriteSubprocess();86 const stream = subprocess.duplex();87 88 stream.write(foobarString);89 await setTimeout(1e2);90 stream.end();91 90- await assertStreamOutput(t, stream);91- await assertSubprocessOutput(t, subprocess);92+ await assertStreamOutput(stream);93+ await assertSubprocessOutput(subprocess);94 });95 94-const testEarlySuccess = async (t, methodName, hasWrites) => {96+const testEarlySuccess = async (methodName, hasWrites) => {97 const subprocess = hasWrites ? getReadableSubprocess() : execa('empty.js');98 const stream = subprocess[methodName]();99 98- 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 };107 106-test('subprocess early success with no writes -> .writable() abort', testEarlySuccess, 'writable', false);107-test('subprocess early success with no writes -> .duplex() abort', testEarlySuccess, 'duplex', false);108-test('subprocess early success with writes -> .writable() abort', testEarlySuccess, 'writable', true);109-test('subprocess early success with writes -> .duplex() abort', testEarlySuccess, 'duplex', true);108+test('subprocess early success with no writes -> .writable() abort', () => testEarlySuccess('writable', false));109+test('subprocess early success with no writes -> .duplex() abort', () => testEarlySuccess('duplex', false));110+test('subprocess early success with writes -> .writable() abort', () => testEarlySuccess('writable', true));111+test('subprocess early success with writes -> .duplex() abort', () => testEarlySuccess('duplex', true));112 111-test('.writable() abort -> subprocess fail', async t => {113+test('.writable() abort -> subprocess fail', async () => {114 const subprocess = getWritableSubprocess();115 const stream = subprocess.writable();116 117 stream.destroy();118 117- 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 });127 126-test('.writable() error -> subprocess fail', async t => {128+test('.writable() error -> subprocess fail', async () => {129 const subprocess = getWritableSubprocess();130 const stream = subprocess.writable();131 132 const cause = new Error(foobarString);133 stream.destroy(cause);134 133- 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 });142 141-test('.writable() EPIPE error -> subprocess success', async t => {143+test('.writable() EPIPE error -> subprocess success', async () => {144 const subprocess = getWritableSubprocess();145 const stream = subprocess.writable();146 147 const error = new Error(foobarString);148 error.code = 'EPIPE';149 stream.destroy(error);150 149- 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 });157 156-test('subprocess.stdin end -> .writable() end + subprocess success', async t => {158+test('subprocess.stdin end -> .writable() end + subprocess success', async () => {159 const subprocess = getReadWriteSubprocess();160 const stream = subprocess.writable();161 162 subprocess.stdin.end(foobarString);163 164 await finishedStream(stream);163- await assertSubprocessOutput(t, subprocess);165+ await assertSubprocessOutput(subprocess);166 });167 166-test('subprocess.stdin end -> .duplex() end + subprocess success', async t => {168+test('subprocess.stdin end -> .duplex() end + subprocess success', async () => {169 const subprocess = getReadWriteSubprocess();170 const stream = subprocess.duplex();171 172 subprocess.stdin.end(foobarString);173 172- await assertStreamOutput(t, stream);173- await assertSubprocessOutput(t, subprocess);174+ await assertStreamOutput(stream);175+ await assertSubprocessOutput(subprocess);176 });177 176-const testStdinAbort = async (t, methodName) => {178+const testStdinAbort = async methodName => {179 const subprocess = getReadWriteSubprocess();180 const stream = subprocess[methodName]();181 182 subprocess.stdin.destroy();183 182- 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 };194 193-test('subprocess.stdin abort -> .writable() error + subprocess fail', testStdinAbort, 'writable');194-test('subprocess.stdin abort -> .duplex() error + subprocess fail', testStdinAbort, 'duplex');195+test('subprocess.stdin abort -> .writable() error + subprocess fail', () => testStdinAbort('writable'));196+test('subprocess.stdin abort -> .duplex() error + subprocess fail', () => testStdinAbort('duplex'));197 196-const testStdinError = async (t, methodName) => {198+const testStdinError = async methodName => {199 const subprocess = getReadWriteSubprocess();200 const stream = subprocess[methodName]();201 202 const cause = new Error(foobarString);203 subprocess.stdin.destroy(cause);204 203- 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 };212 211-test('subprocess.stdin error -> .writable() error + subprocess fail', testStdinError, 'writable');212-test('subprocess.stdin error -> .duplex() error + subprocess fail', testStdinError, 'duplex');213+test('subprocess.stdin error -> .writable() error + subprocess fail', () => testStdinError('writable'));214+test('subprocess.stdin error -> .duplex() error + subprocess fail', () => testStdinError('duplex'));215 214-test('.writable() can be used with Stream.pipeline()', async t => {216+test('.writable() can be used with Stream.pipeline()', async () => {217 const subprocess = getWritableSubprocess();218 const inputStream = Readable.from([foobarString]);219 const stream = subprocess.writable();220 221 await pipeline(inputStream, stream);222 223 await finishedStream(inputStream);224 await finishedStream(stream);223- await assertSubprocessOutput(t, subprocess, foobarString, 2);225+ await assertSubprocessOutput(subprocess, foobarString, 2);226 });227 226-test('.writable() can error with Stream.pipeline()', async t => {228+test('.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();232 231- 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);236 237 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 });241 240-test('.writable() can pipe to errored stream with Stream.pipeline()', async t => {242+test('.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();246 247 const cause = new Error('test');248 inputStream.destroy(cause);249 248- 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));252 251- 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 });257 256-test('.writable() can be used with Stream.compose()', async t => {258+test('.writable() can be used with Stream.compose()', async () => {259 const subprocess = getWritableSubprocess();260 const inputStream = Readable.from([foobarString]);261 const stream = subprocess.writable();262 263 await finishedStream(compose(inputStream, stream));262- await assertSubprocessOutput(t, subprocess, foobarString, 2);264+ await assertSubprocessOutput(subprocess, foobarString, 2);265 });266 265-test('.writable() works with objectMode', async t => {267+test('.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);273 274 await finishedStream(stream);273- await assertSubprocessOutput(t, subprocess, foobarObjectString);275+ await assertSubprocessOutput(subprocess, foobarObjectString);276 });277 276-test('.duplex() works with objectMode and writes', async t => {278+test('.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);286 285- await assertStreamOutput(t, stream, foobarObjectString);286- await assertSubprocessOutput(t, subprocess, foobarObjectString);287+ await assertStreamOutput(stream, foobarObjectString);288+ await assertSubprocessOutput(subprocess, foobarObjectString);289 });290 289-test('.writable() has the right highWaterMark', async t => {291+test('.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 });298 297-const writeUntilFull = async (t, stream, subprocess) => {299+const writeUntilFull = async (stream, subprocess) => {300 const size = stream.writableHighWaterMark / 2;301 const chunk = '.'.repeat(size);302 301- 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);307 306- 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);313 312- 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);319 318- 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);325 326 await once(stream, 'drain');327 stream.end();328 329 return '.'.repeat(size * 3);330 };331 330-test('.writable() waits when its buffer is full', async t => {332+test('.writable() waits when its buffer is full', async () => {333 const subprocess = getReadWriteSubprocess({stdin: noopAsyncGenerator(false, true)});334 const stream = subprocess.writable();335 334- const expectedOutput = await writeUntilFull(t, stream, subprocess);336+ const expectedOutput = await writeUntilFull(stream, subprocess);337 336- await assertSubprocessOutput(t, subprocess, expectedOutput);338+ await assertSubprocessOutput(subprocess, expectedOutput);339 });340 339-test('.duplex() waits when its buffer is full', async t => {341+test('.duplex() waits when its buffer is full', async () => {342 const subprocess = getReadWriteSubprocess({stdin: noopAsyncGenerator(false, true)});343 const stream = subprocess.duplex();344 343- const expectedOutput = await writeUntilFull(t, stream, subprocess);345+ const expectedOutput = await writeUntilFull(stream, subprocess);346 345- await assertStreamOutput(t, stream, expectedOutput);346- await assertSubprocessOutput(t, subprocess, expectedOutput);347+ await assertStreamOutput(stream, expectedOutput);348+ await assertSubprocessOutput(subprocess, expectedOutput);349 });350 349-const testPropagateError = async (t, methodName) => {351+const 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 };358 357-test('.writable() propagates write errors', testPropagateError, 'writable');358-test('.duplex() propagates write errors', testPropagateError, 'duplex');359+test('.writable() propagates write errors', () => testPropagateError('writable'));360+test('.duplex() propagates write errors', () => testPropagateError('duplex'));361 360-const testWritev = async (t, methodName, waitForStream) => {362+const testWritev = async (methodName, waitForStream) => {363 const subprocess = getReadWriteSubprocess({stdin: noopAsyncGenerator()});364 const stream = subprocess[methodName]();365 366 const chunk = '.'.repeat(stream.writableHighWaterMark);367 stream.write(chunk);366- t.true(stream.writableNeedDrain);368+ assert.equal(stream.writableNeedDrain, true);369 370 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);375 376 stream.end();377 await waitForStream(stream);378 };379 378-test('.writable() can use .writev()', testWritev, 'writable', finishedStream);379-test('.duplex() can use .writev()', testWritev, 'duplex', text);380+test('.writable() can use .writev()', () => testWritev('writable', finishedStream));381+test('.duplex() can use .writev()', () => testWritev('duplex', text));382 381-test('.writable() can set encoding', async t => {383+test('.writable() can set encoding', async () => {384 const subprocess = getReadWriteSubprocess();385 const stream = subprocess.writable();386 387 stream.end(foobarBuffer.toString('hex'), 'hex');388 389 await finishedStream(stream);388- await assertSubprocessOutput(t, subprocess);390+ await assertSubprocessOutput(subprocess);391 });392 391-test('.duplex() can set encoding', async t => {393+test('.duplex() can set encoding', async () => {394 const subprocess = getReadWriteSubprocess();395 const stream = subprocess.duplex();396 397 stream.end(foobarBuffer.toString('hex'), 'hex');398 397- 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 line2 import process from 'node:process';3 import {getCancelSignal} from 'execa';4 5 // 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 caught7 for (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 lineadded:test/fixtures/ipc-send-strict-forged.js+8 added
1+#!/usr/bin/env node2+import {sendMessage} from '../../index.js';3+4+// Forged `strict` acknowledgment responses, for messages which were sent to another subprocess5+for (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 lines7 const execaMethod = isSyncString === 'true' ? execaSync : execa;8 const options = {9 input: foobarString,10 [optionName]: JSON.parse(stdioOptionString),11+ ...((optionName === 'stdin') && {stdout: 'inherit'}),12 };13 13-if (optionName === 'stdin') {14- options.stdout = 'inherit';15-}16-14 await execaMethod('stdin.js', options);added:test/fixtures/nested-pipe-all-stream.js+8 added
1+#!/usr/bin/env node2+import process from 'node:process';3+import {execa, getOneMessage} from '../../index.js';4+5+const {file, commandArguments, options} = await getOneMessage();6+const subprocess = execa(file, commandArguments, {...options, all: true});7+subprocess.all.pipe(process.stdout);8+await subprocess;modified:test/fixtures/noop-fd-large.js+1 added
1 #!/usr/bin/env node2 import {Buffer} from 'node:buffer';3+import process from 'node:process';4 import {getWriteStream} from '../helpers/fs.js';5 6 const fdNumber = Number(process.argv[2]);7 const bytes = Number(process.argv[3]);1 unmodified lineadded:test/helpers/assert.js+70 added
1+import assert from 'node:assert/strict';2+import isPlainObject from 'is-plain-obj';3+4+/*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+*/8+9+const checkExpectation = (error, expectation) => {10+ if (expectation === undefined) {11+ return;12+ }13+14+ // 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+ }18+19+ // `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+ }25+26+ 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+};33+34+export const assertThrows = (synchronousFunction, expectation) => {35+ let error;36+ assert.throws(synchronousFunction, thrownError => {37+ error = thrownError;38+ return true;39+ });40+41+ checkExpectation(error, expectation);42+ return error;43+};44+45+export const assertRejects = async (promise, expectation) => {46+ let error;47+ await assert.rejects(promise, thrownError => {48+ error = thrownError;49+ return true;50+ });51+52+ checkExpectation(error, expectation);53+ return error;54+};55+56+/*57+Like `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.59+The properties are read directly, so non-enumerable ones like `error.cause` are included.60+*/61+export 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
1 import {text} from 'node:stream/consumers';2 import {finished} from 'node:stream/promises';3+import assert from 'node:assert/strict';4 import getStream from 'get-stream';5 import isPlainObj from 'is-plain-obj';6 import {execa} from '../../index.js';7+import {assertRejects} from './assert.js';8 import {foobarString} from './input.js';9 10 export const arrayFromAsync = async (asyncIterable, lines = []) => {11 for await (const line of asyncIterable) {4 unmodified lines16 };17 18 export const finishedStream = stream => finished(stream, {cleanup: true});19 18-export const assertWritableAborted = (t, writable) => {19- t.false(writable.writableEnded);20- t.is(writable.errored, null);21- t.false(writable.writable);20+export const assertWritableAborted = writable => {21+ assert.equal(writable.writableEnded, false);22+ assert.equal(writable.errored, null);23+ assert.equal(writable.writable, false);24 };25 24-export const assertReadableAborted = (t, readable) => {25- t.false(readable.readableEnded);26- t.is(readable.errored, null);27- t.false(readable.readable);26+export const assertReadableAborted = readable => {27+ assert.equal(readable.readableEnded, false);28+ assert.equal(readable.errored, null);29+ assert.equal(readable.readable, false);30 };31 30-export const assertProcessNormalExit = (t, error, exitCode = 0) => {31- t.is(error.exitCode, exitCode);32- t.is(error.signal, undefined);32+export const assertProcessNormalExit = (error, exitCode = 0) => {33+ assert.equal(error.exitCode, exitCode);34+ assert.equal(error.signal, undefined);35 };36 35-export const assertStreamOutput = async (t, stream, expectedOutput = foobarString) => {36- t.is(await text(stream), expectedOutput);37+export const assertStreamOutput = async (stream, expectedOutput = foobarString) => {38+ assert.equal(await text(stream), expectedOutput);39 };40 39-export const assertStreamDataEvents = async (t, stream, expectedOutput = foobarString) => {40- t.is(await getStream(stream), expectedOutput);41+export const assertStreamDataEvents = async (stream, expectedOutput = foobarString) => {42+ assert.equal(await getStream(stream), expectedOutput);43 };44 43-export const assertIterableChunks = async (t, asyncIterable, expectedChunks) => {44- t.deepEqual(await arrayFromAsync(asyncIterable), expectedChunks);45+export const assertIterableChunks = async (asyncIterable, expectedChunks) => {46+ assert.deepEqual(await arrayFromAsync(asyncIterable), expectedChunks);47 };48 47-export const assertStreamChunks = async (t, stream, expectedOutput) => {48- t.deepEqual(await stream.toArray(), expectedOutput);49+export const assertStreamChunks = async (stream, expectedOutput) => {50+ assert.deepEqual(await stream.toArray(), expectedOutput);51 };52 51-export const assertSubprocessOutput = async (t, subprocess, expectedOutput = foobarString, fdNumber = 1) => {53+export 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 };57 56-export const assertStreamError = (t, stream, error) => assertPromiseError(t, finishedStream(stream), error);58+export const assertStreamError = (stream, error) => assertPromiseError(finishedStream(stream), error);59 58-export const assertStreamReadError = (t, stream, error) => assertPromiseError(t, text(stream), error);60+export const assertStreamReadError = (stream, error) => assertPromiseError(text(stream), error);61 60-export const assertSubprocessError = (t, subprocess, error) => assertPromiseError(t, subprocess, error);62+export const assertSubprocessError = (subprocess, error) => assertPromiseError(subprocess, error);63 62-export const assertPromiseError = async (t, promise, error) => {63- const thrownError = await t.throwsAsync(promise);64+export const assertPromiseError = async (promise, error) => {65+ const thrownError = await assertRejects(promise);66 67 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 }72 73 return thrownError;74 };6 unmodified linesmodified:test/helpers/fs.js+1 added-5 removed
8 unmodified lines9 if (fdNumber === 1) {10 return process.stdout;11 }12 13- if (fdNumber === 2) {14- return process.stderr;15- }16-17- 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
1+import assert from 'node:assert/strict';2 import process from 'node:process';3 3-export const assertMaxListeners = t => {4+export const assertMaxListeners = () => {5 let warning;6 const captureWarning = warningArgument => {7 warning = warningArgument;8 };9 10 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
1+import assert from 'node:assert/strict';2 import {execa, execaSync} from '../../index.js';3 4 export const maxBuffer = 10;5 5-export const assertErrorMessage = (t, shortMessage, {execaMethod = execa, length = maxBuffer, fdNumber = 1, unit = 'characters'} = {}) => {6+export 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 };10 11 const 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`.2 const nativePromise = Promise;3 // eslint-disable-next-line unicorn/no-global-object-property-assignment -- intentionally mocking the global `Promise`4 globalThis.Promise = class BrokenPromise {5 then() { // eslint-disable-line unicorn/no-thenable8 unmodified linesmodified:test/helpers/pipe.js+24 added-21 removed
1-export const assertPipeError = async (t, pipePromise, message) => {2- const error = await t.throwsAsync(pipePromise);1+import assert from 'node:assert/strict';2+import {assertRejects} from './assert.js';3 4- t.is(error.command, 'source.pipe(destination)');5- t.is(error.escapedCommand, error.command);4+export const assertPipeError = async (pipePromise, message) => {5+ const error = await assertRejects(pipePromise);6 7- 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);9 21- 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, []);23 24+ 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));27+25- t.true(error.originalMessage.includes(message));28+ assert.ok(error.originalMessage.includes(message));29 };modified:test/helpers/stdio.js+4 added-7 removed
1+import assert from 'node:assert/strict';2 import process, {platform} from 'node:process';3 import {noopReadable} from './stream.js';4 5 export const identity = value => value;16 unmodified lines22 export const prematureClose = {code: 'ERR_STREAM_PREMATURE_CLOSE'};23 24 const isWindows = platform === 'win32';25 25-export const assertEpipe = (t, stderr, fdNumber = 1) => {26+export const assertEpipe = (stderr, fdNumber = 1) => {27 if (fdNumber === 1 && !isWindows) {27- t.true(stderr.includes('EPIPE'));28+ assert.ok(stderr.includes('EPIPE'));29 }30 };31 32 export const parseStdioOption = stdioOption => {1 unmodified line34 if (typeof optionValue === 'string' && optionValue in process) {35 return process[optionValue];36 }37 37- if (Array.isArray(optionValue) && typeof optionValue[0] === 'string' && optionValue[0] in process) {38- return [process[optionValue[0]], ...optionValue.slice(1)];39- }40-41- 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
1+import assert from 'node:assert/strict';2 import {platform} from 'node:process';3 import {stripVTControlCharacters} from 'node:util';4 import {replaceSymbols} from 'figures';5 import {foobarString} from './input.js';2 unmodified lines8 9 const isWindows = platform === 'win32';10 export const QUOTE = isWindows ? '"' : '\'';11 11-export const runErrorSubprocess = async (t, verbose, isSync = false, options = {}) => {12+export 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 }19 20 return stderr;21 };22 22-export const runWarningSubprocess = async (t, isSync) => {23+export 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 };29 29-export const runEarlyErrorSubprocess = async (t, isSync) => {30+export 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 };36 37 export const runVerboseSubprocess = ({68 unmodified linesmodified:test/io/input-option.js+64 added-61 removed
1+import assert from 'node:assert/strict';2 import {Buffer} from 'node:buffer';3 import {Writable} from 'node:stream';3-import test from 'ava';4+import test from 'node:test';5+import {assertThrows} from '../helpers/assert.js';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {9 runExeca,12 unmodified lines22 import {noopGenerator} from '../helpers/generator.js';23 24 setFixtureDirectory();25 24-const testInput = async (t, input, execaMethod) => {26+const testInput = async (input, execaMethod) => {27 const {stdout} = await execaMethod('stdin.js', {input});26- t.is(stdout, 'foobar');28+ assert.equal(stdout, 'foobar');29 };30 29-test('input option can be a String', testInput, 'foobar', runExeca);30-test('input option can be a Uint8Array', testInput, foobarUint8Array, runExeca);31-test('input option can be a Buffer', testInput, foobarBuffer, runExeca);32-test('input option can be a String - sync', testInput, 'foobar', runExecaSync);33-test('input option can be a Uint8Array - sync', testInput, foobarUint8Array, runExecaSync);34-test('input option can be a Buffer - sync', testInput, foobarBuffer, runExecaSync);35-test('input option can be used with $', testInput, 'foobar', runScript);36-test('input option can be used with $.sync', testInput, 'foobar', runScriptSync);31+test('input option can be a String', () => testInput('foobar', runExeca));32+test('input option can be a Uint8Array', () => testInput(foobarUint8Array, runExeca));33+test('input option can be a Buffer', () => testInput(foobarBuffer, runExeca));34+test('input option can be a String - sync', () => testInput('foobar', runExecaSync));35+test('input option can be a Uint8Array - sync', () => testInput(foobarUint8Array, runExecaSync));36+test('input option can be a Buffer - sync', () => testInput(foobarBuffer, runExecaSync));37+test('input option can be used with $', () => testInput('foobar', runScript));38+test('input option can be used with $.sync', () => testInput('foobar', runScriptSync));39 38-const testInputIgnoresInheritedStdin = async (t, optionName, stdioOption, isSync) => {40+const 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 };44 43-test('input option ignores stdin "inherit"', testInputIgnoresInheritedStdin, 'stdin', 'inherit', false);44-test('input option ignores stdin ["inherit"]', testInputIgnoresInheritedStdin, 'stdin', ['inherit'], false);45-test('input option ignores stdio "inherit"', testInputIgnoresInheritedStdin, 'stdio', 'inherit', false);46-test('input option ignores stdio[0] "inherit"', testInputIgnoresInheritedStdin, 'stdio', ['inherit', 'inherit', 'pipe'], false);47-test.serial('input option ignores stdin "inherit" - sync', testInputIgnoresInheritedStdin, 'stdin', 'inherit', true);48-test.serial('input option ignores stdin ["inherit"] - sync', testInputIgnoresInheritedStdin, 'stdin', ['inherit'], true);49-test.serial('input option ignores stdio "inherit" - sync', testInputIgnoresInheritedStdin, 'stdio', 'inherit', true);50-test.serial('input option ignores stdio[0] "inherit" - sync', testInputIgnoresInheritedStdin, 'stdio', ['inherit', 'inherit', 'pipe'], true);45+test('input option ignores stdin "inherit"', () => testInputIgnoresInheritedStdin('stdin', 'inherit', false));46+test('input option ignores stdin ["inherit"]', () => testInputIgnoresInheritedStdin('stdin', ['inherit'], false));47+test('input option ignores stdio "inherit"', () => testInputIgnoresInheritedStdin('stdio', 'inherit', false));48+test('input option ignores stdio[0] "inherit"', () => testInputIgnoresInheritedStdin('stdio', ['inherit', 'inherit', 'pipe'], false));49+test('input option ignores stdin "inherit" - sync', () => testInputIgnoresInheritedStdin('stdin', 'inherit', true));50+test('input option ignores stdin ["inherit"] - sync', () => testInputIgnoresInheritedStdin('stdin', ['inherit'], true));51+test('input option ignores stdio "inherit" - sync', () => testInputIgnoresInheritedStdin('stdio', 'inherit', true));52+test('input option ignores stdio[0] "inherit" - sync', () => testInputIgnoresInheritedStdin('stdio', ['inherit', 'inherit', 'pipe'], true));53 52-const testInvalidInput = async (t, input, execaMethod) => {53- t.throws(() => {54+const testInvalidInput = async (input, execaMethod) => {55+ assertThrows(() => {56 execaMethod('empty.js', {input});57 }, {message: /a string, a Uint8Array/});58 };59 58-test('input option cannot be an ArrayBuffer', testInvalidInput, foobarArrayBuffer, execa);59-test('input option cannot be a DataView', testInvalidInput, foobarDataView, execa);60-test('input option cannot be a Uint16Array', testInvalidInput, foobarUint16Array, execa);61-test('input option cannot be 0', testInvalidInput, 0, execa);62-test('input option cannot be false', testInvalidInput, false, execa);63-test('input option cannot be null', testInvalidInput, null, execa);64-test('input option cannot be a non-Readable stream', testInvalidInput, new Writable(), execa);65-test('input option cannot be an ArrayBuffer - sync', testInvalidInput, foobarArrayBuffer, execaSync);66-test('input option cannot be a DataView - sync', testInvalidInput, foobarDataView, execaSync);67-test('input option cannot be a Uint16Array - sync', testInvalidInput, foobarUint16Array, execaSync);68-test('input option cannot be 0 - sync', testInvalidInput, 0, execaSync);69-test('input option cannot be false - sync', testInvalidInput, false, execaSync);70-test('input option cannot be null - sync', testInvalidInput, null, execaSync);71-test('input option cannot be a non-Readable stream - sync', testInvalidInput, new Writable(), execaSync);60+test('input option cannot be an ArrayBuffer', () => testInvalidInput(foobarArrayBuffer, execa));61+test('input option cannot be a DataView', () => testInvalidInput(foobarDataView, execa));62+test('input option cannot be a Uint16Array', () => testInvalidInput(foobarUint16Array, execa));63+test('input option cannot be 0', () => testInvalidInput(0, execa));64+test('input option cannot be false', () => testInvalidInput(false, execa));65+test('input option cannot be null', () => testInvalidInput(null, execa));66+test('input option cannot be a non-Readable stream', () => testInvalidInput(new Writable(), execa));67+test('input option cannot be an ArrayBuffer - sync', () => testInvalidInput(foobarArrayBuffer, execaSync));68+test('input option cannot be a DataView - sync', () => testInvalidInput(foobarDataView, execaSync));69+test('input option cannot be a Uint16Array - sync', () => testInvalidInput(foobarUint16Array, execaSync));70+test('input option cannot be 0 - sync', () => testInvalidInput(0, execaSync));71+test('input option cannot be false - sync', () => testInvalidInput(false, execaSync));72+test('input option cannot be null - sync', () => testInvalidInput(null, execaSync));73+test('input option cannot be a non-Readable stream - sync', () => testInvalidInput(new Writable(), execaSync));74 75 /*74-String input is encoded with the `encoding` option, so it round-trips with subprocesses echoing it back.76+The `encoding` option only applies to the output: string input is always encoded with UTF-8, like with a binary encoding.77+Since the subprocess echoes its input, its output is those UTF-8 bytes decoded as UTF-16.78 This must not depend on whether a `stdin` transform happens to be present.79 */80 const nonAsciiString = '🦄🦄';81+const getUtf16Output = input => Buffer.from(input).toString('utf16le');82 79-const testStringEncoding = async (t, options, execaMethod) => {83+const 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 };87 84-test('input option string is encoded with encoding "utf16le" without transforms', testStringEncoding, {}, execa);85-test('input option string is encoded with encoding "utf16le" without transforms - sync', testStringEncoding, {}, execaSync);86-test('input option string is encoded with encoding "utf16le" with transforms', testStringEncoding, {stdin: noopGenerator()}, execa);87-test('input option string is encoded with encoding "utf16le" with transforms - sync', testStringEncoding, {stdin: noopGenerator()}, execaSync);88+test('input option string is encoded with UTF-8 with encoding "utf16le" without transforms', () => testStringEncoding({}, execa));89+test('input option string is encoded with UTF-8 with encoding "utf16le" without transforms - sync', () => testStringEncoding({}, execaSync));90+test('input option string is encoded with UTF-8 with encoding "utf16le" with transforms', () => testStringEncoding({stdin: noopGenerator()}, execa));91+test('input option string is encoded with UTF-8 with encoding "utf16le" with transforms - sync', () => testStringEncoding({stdin: noopGenerator()}, execaSync));92 89-/*90-Sources other than the `input` option also pass strings to the subprocess, which must be encoded with the `encoding` option too.91-*/92-const testIterableInputEncoding = async (t, execaMethod) => {93+// Sources other than the `input` option also pass strings to the subprocess, which are encoded with UTF-8 too94+const 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 };103 101-test('Iterable string input is encoded with encoding "utf16le"', testIterableInputEncoding, execa);102-test('Iterable string input is encoded with encoding "utf16le" - sync', testIterableInputEncoding, execaSync);104+test('Iterable string input is encoded with UTF-8 with encoding "utf16le"', () => testIterableInputEncoding(execa));105+test('Iterable string input is encoded with UTF-8 with encoding "utf16le" - sync', () => testIterableInputEncoding(execaSync));106 104-const testAsyncIterableInputEncoding = async t => {107+const testAsyncIterableInputEncoding = async () => {108 const chunks = async function * () {109 yield nonAsciiString;110 };111 112 const {stdout} = await execa('stdin.js', {stdin: [chunks()], encoding: 'utf16le'});110- t.is(stdout, nonAsciiString);113+ assert.equal(stdout, getUtf16Output(nonAsciiString));114 };115 113-test('Async iterable string input is encoded with encoding "utf16le"', testAsyncIterableInputEncoding);116+test('Async iterable string input is encoded with UTF-8 with encoding "utf16le"', () => testAsyncIterableInputEncoding());117 118 /*119 The `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 */118-const testBinaryEncodingInput = async (t, encoding, execaMethod) => {121+const 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 };125 123-test('String input stays UTF-8 with encoding "latin1"', testBinaryEncodingInput, 'latin1', execa);124-test('String input stays UTF-8 with encoding "latin1" - sync', testBinaryEncodingInput, 'latin1', execaSync);125-test('String input stays UTF-8 with encoding "hex"', testBinaryEncodingInput, 'hex', execa);126-test('String input stays UTF-8 with encoding "hex" - sync', testBinaryEncodingInput, 'hex', execaSync);126+test('String input stays UTF-8 with encoding "latin1"', () => testBinaryEncodingInput('latin1', execa));127+test('String input stays UTF-8 with encoding "latin1" - sync', () => testBinaryEncodingInput('latin1', execaSync));128+test('String input stays UTF-8 with encoding "hex"', () => testBinaryEncodingInput('hex', execa));129+test('String input stays UTF-8 with encoding "hex" - sync', () => testBinaryEncodingInput('hex', execaSync));modified:test/io/input-sync.js+48 added-30 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import {openSync, closeSync} from 'node:fs';3+import process from 'node:process';4+import test from 'node:test';5+import {assertThrows} from '../helpers/assert.js';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {getStdio} from '../helpers/stdio.js';9 import {noopGenerator, serializeGenerator} from '../helpers/generator.js';10 import {foobarObject, foobarObjectString} from '../helpers/input.js';11+import {nestedSubprocess} from '../helpers/nested.js';12 13 setFixtureDirectory();14 15 const getFd3InputMessage = type => `not \`stdio[3]\`, can be ${type}`;16 12-const testFd3InputSync = (t, stdioOption, expectedMessage) => {13- const {message} = t.throws(() => {17+const 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 };23 19-test('Cannot use Uint8Array with stdio[*], sync', testFd3InputSync, new Uint8Array(), getFd3InputMessage('a Uint8Array'));20-test('Cannot use iterable with stdio[*], sync', testFd3InputSync, [[]], getFd3InputMessage('an iterable'));24+test('Cannot use Uint8Array with stdio[*], sync', () => testFd3InputSync(new Uint8Array(), getFd3InputMessage('a Uint8Array')));25+test('Cannot use iterable with stdio[*], sync', () => testFd3InputSync([[]], getFd3InputMessage('an iterable')));26 27 /*28 With asynchronous methods, all `stdin` sources are merged into a single stream before being transformed, so transform state (including line splitting) spans all sources.29 Synchronous methods must apply the transform pipeline once over the merged sources, not once per source.30 */26-const testMultipleSources = async (t, execaMethod) => {31+const 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 };37 33-test('Multiple stdin sources are transformed as a single stream', testMultipleSources, execa);34-test('Multiple stdin sources are transformed as a single stream, sync', testMultipleSources, execaSync);38+test('Multiple stdin sources are transformed as a single stream', () => testMultipleSources(execa));39+test('Multiple stdin sources are transformed as a single stream, sync', () => testMultipleSources(execaSync));40 41 // The generator's `final` function must run once overall, not once per source42 const finalCountGenerator = {43 * transform(value) {3 unmodified lines47 yield '[F]';48 },49 };50 46-const testMultipleSourcesFinal = async (t, execaMethod) => {51+const 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 };57 53-test('Generator "final" runs once with multiple stdin sources', testMultipleSourcesFinal, execa);54-test('Generator "final" runs once with multiple stdin sources, sync', testMultipleSourcesFinal, execaSync);58+test('Generator "final" runs once with multiple stdin sources', () => testMultipleSourcesFinal(execa));59+test('Generator "final" runs once with multiple stdin sources, sync', () => testMultipleSourcesFinal(execaSync));60 61 // Without transforms, multiple sources are simply concatenated, like a single source with multiple chunks57-const testMultipleSourcesNoTransform = async (t, execaMethod) => {62+const 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 };66 62-test('Multiple stdin sources are concatenated without transforms', testMultipleSourcesNoTransform, execa);63-test('Multiple stdin sources are concatenated without transforms, sync', testMultipleSourcesNoTransform, execaSync);67+test('Multiple stdin sources are concatenated without transforms', () => testMultipleSourcesNoTransform(execa));68+test('Multiple stdin sources are concatenated without transforms, sync', () => testMultipleSourcesNoTransform(execaSync));69 70 // A `\r\n` sequence split across two sources must still be detected, like across two chunks of a single source66-const testWindowsNewlineSpanningSources = async (t, execaMethod) => {71+const 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 };78 74-test('Windows newlines can span multiple stdin sources', testWindowsNewlineSpanningSources, execa);75-test('Windows newlines can span multiple stdin sources, sync', testWindowsNewlineSpanningSources, execaSync);79+test('Windows newlines can span multiple stdin sources', () => testWindowsNewlineSpanningSources(execa));80+test('Windows newlines can span multiple stdin sources, sync', () => testWindowsNewlineSpanningSources(execaSync));81 82 // The `input` option is one more source going through the same transforms, in the order the sources were passed78-const testInputOptionWithStdinSource = async (t, execaMethod) => {83+const 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 };90 86-test('The input option is transformed together with stdin sources', testInputOptionWithStdinSource, execa);87-test('The input option is transformed together with stdin sources, sync', testInputOptionWithStdinSource, execaSync);91+test('The input option is transformed together with stdin sources', () => testInputOptionWithStdinSource(execa));92+test('The input option is transformed together with stdin sources, sync', () => testInputOptionWithStdinSource(execaSync));93 94 // Object inputs are serialized no matter how many sources they come from90-const testMultipleObjectSources = async (t, execaMethod) => {95+const 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 };101 97-test('Multiple object stdin sources are serialized', testMultipleObjectSources, execa);98-test('Multiple object stdin sources are serialized, sync', testMultipleObjectSources, execaSync);102+test('Multiple object stdin sources are serialized', () => testMultipleObjectSources(execa));103+test('Multiple object stdin sources are serialized, sync', () => testMultipleObjectSources(execaSync));104+105+// Like `inputFile`, the inherited file descriptor is read lazily, so that a read failure is reported like any other error, including with `reject: false`106+if (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
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {getDefaultHighWaterMark} from 'node:stream';3-import test from 'ava';4+import test from 'node:test';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {7 assertStreamOutput,8 assertIterableChunks,42 unmodified lines51 subprocess.stdin.end(output);52 return subprocess;53 };54 54-const assertChunks = async (t, streamOrIterable, expectedChunks, methodName) => {55+const assertChunks = async (streamOrIterable, expectedChunks, methodName) => {56 const assertMethod = methodName === 'iterable' ? assertIterableChunks : assertStreamChunks;56- await assertMethod(t, streamOrIterable, expectedChunks);57+ await assertMethod(streamOrIterable, expectedChunks);58 };59 60 // eslint-disable-next-line max-params60-const testText = async (t, expectedChunks, methodName, binary, preserveNewlines, encoding) => {61+const 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});66 66- 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 };73 73-test('.iterable() can use "binary: true"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'utf8');74-test('.iterable() can use "binary: true" + "encoding: utf16le"', testText, [complexFullUtf16Uint8Array], 'iterable', true, undefined, 'utf16le');75-test('.iterable() can use "binary: true" + "encoding: "buffer"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'buffer');76-test('.iterable() can use "binary: true" + "encoding: "hex"', testText, [singleComplexUint8Array], 'iterable', true, undefined, 'hex');77-test('.iterable() can use "binary: undefined"', testText, complexChunks, 'iterable', undefined, undefined, 'utf8');78-test('.iterable() can use "binary: undefined" + "encoding: utf16le"', testText, complexChunks, 'iterable', undefined, undefined, 'utf16le');79-test('.iterable() can use "binary: undefined" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'buffer');80-test('.iterable() can use "binary: undefined" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', undefined, undefined, 'hex');81-test('.iterable() can use "binary: false"', testText, complexChunks, 'iterable', false, undefined, 'utf8');82-test('.iterable() can use "binary: false" + "encoding: utf16le"', testText, complexChunks, 'iterable', false, undefined, 'utf16le');83-test('.iterable() can use "binary: false" + "encoding: buffer"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'buffer');84-test('.iterable() can use "binary: false" + "encoding: hex"', testText, [singleComplexUint8Array], 'iterable', false, undefined, 'hex');85-test('.iterable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'iterable', false, true, 'utf8');86-test('.iterable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'iterable', false, false, 'utf8');87-test('.readable() can use "binary: true"', testText, singleComplexBuffer, 'readable', true, undefined, 'utf8');88-test('.readable() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', true, undefined, 'utf16le');89-test('.readable() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', true, undefined, 'buffer');90-test('.readable() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'readable', true, undefined, 'hex');91-test('.readable() can use "binary: undefined"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'utf8');92-test('.readable() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'readable', undefined, undefined, 'utf16le');93-test('.readable() can use "binary: undefined" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'buffer');94-test('.readable() can use "binary: undefined" + "encoding: hex"', testText, singleComplexBuffer, 'readable', undefined, undefined, 'hex');95-test('.readable() can use "binary: false"', testText, complexChunksEnd, 'readable', false, undefined, 'utf8');96-test('.readable() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'readable', false, undefined, 'utf16le');97-test('.readable() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'readable', false, undefined, 'buffer');98-test('.readable() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'readable', false, undefined, 'hex');99-test('.readable() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'readable', false, true, 'utf8');100-test('.readable() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'readable', false, false, 'utf8');101-test('.duplex() can use "binary: true"', testText, singleComplexBuffer, 'duplex', true, undefined, 'utf8');102-test('.duplex() can use "binary: true" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', true, undefined, 'utf16le');103-test('.duplex() can use "binary: true" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', true, undefined, 'buffer');104-test('.duplex() can use "binary: true" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', true, undefined, 'hex');105-test('.duplex() can use "binary: undefined"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'utf8');106-test('.duplex() can use "binary: undefined" + "encoding: utf16le"', testText, singleComplexUtf16Buffer, 'duplex', undefined, undefined, 'utf16le');107-test('.duplex() can use "binary: undefined" + "encoding: "buffer"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'buffer');108-test('.duplex() can use "binary: undefined" + "encoding: "hex"', testText, singleComplexBuffer, 'duplex', undefined, undefined, 'hex');109-test('.duplex() can use "binary: false"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf8');110-test('.duplex() can use "binary: false" + "encoding: utf16le"', testText, complexChunksEnd, 'duplex', false, undefined, 'utf16le');111-test('.duplex() can use "binary: false" + "encoding: buffer"', testText, singleComplexBuffer, 'duplex', false, undefined, 'buffer');112-test('.duplex() can use "binary: false" + "encoding: hex"', testText, singleComplexBuffer, 'duplex', false, undefined, 'hex');113-test('.duplex() can use "binary: false" + "preserveNewlines: true"', testText, complexChunksEnd, 'duplex', false, true, 'utf8');114-test('.duplex() can use "binary: false" + "preserveNewlines: false"', testText, complexChunks, 'duplex', false, false, 'utf8');74+test('.iterable() can use "binary: true"', () => testText([singleComplexUint8Array], 'iterable', true, undefined, 'utf8'));75+test('.iterable() can use "binary: true" + "encoding: utf16le"', () => testText([complexFullUtf16Uint8Array], 'iterable', true, undefined, 'utf16le'));76+test('.iterable() can use "binary: true" + "encoding: "buffer"', () => testText([singleComplexUint8Array], 'iterable', true, undefined, 'buffer'));77+test('.iterable() can use "binary: true" + "encoding: "hex"', () => testText([singleComplexUint8Array], 'iterable', true, undefined, 'hex'));78+test('.iterable() can use "binary: undefined"', () => testText(complexChunks, 'iterable', undefined, undefined, 'utf8'));79+test('.iterable() can use "binary: undefined" + "encoding: utf16le"', () => testText(complexChunks, 'iterable', undefined, undefined, 'utf16le'));80+test('.iterable() can use "binary: undefined" + "encoding: buffer"', () => testText([singleComplexUint8Array], 'iterable', undefined, undefined, 'buffer'));81+test('.iterable() can use "binary: undefined" + "encoding: hex"', () => testText([singleComplexUint8Array], 'iterable', undefined, undefined, 'hex'));82+test('.iterable() can use "binary: false"', () => testText(complexChunks, 'iterable', false, undefined, 'utf8'));83+test('.iterable() can use "binary: false" + "encoding: utf16le"', () => testText(complexChunks, 'iterable', false, undefined, 'utf16le'));84+test('.iterable() can use "binary: false" + "encoding: buffer"', () => testText([singleComplexUint8Array], 'iterable', false, undefined, 'buffer'));85+test('.iterable() can use "binary: false" + "encoding: hex"', () => testText([singleComplexUint8Array], 'iterable', false, undefined, 'hex'));86+test('.iterable() can use "binary: false" + "preserveNewlines: true"', () => testText(complexChunksEnd, 'iterable', false, true, 'utf8'));87+test('.iterable() can use "binary: false" + "preserveNewlines: false"', () => testText(complexChunks, 'iterable', false, false, 'utf8'));88+test('.readable() can use "binary: true"', () => testText(singleComplexBuffer, 'readable', true, undefined, 'utf8'));89+test('.readable() can use "binary: true" + "encoding: utf16le"', () => testText(singleComplexUtf16Buffer, 'readable', true, undefined, 'utf16le'));90+test('.readable() can use "binary: true" + "encoding: buffer"', () => testText(singleComplexBuffer, 'readable', true, undefined, 'buffer'));91+test('.readable() can use "binary: true" + "encoding: hex"', () => testText(singleComplexBuffer, 'readable', true, undefined, 'hex'));92+test('.readable() can use "binary: undefined"', () => testText(singleComplexBuffer, 'readable', undefined, undefined, 'utf8'));93+test('.readable() can use "binary: undefined" + "encoding: utf16le"', () => testText(singleComplexUtf16Buffer, 'readable', undefined, undefined, 'utf16le'));94+test('.readable() can use "binary: undefined" + "encoding: buffer"', () => testText(singleComplexBuffer, 'readable', undefined, undefined, 'buffer'));95+test('.readable() can use "binary: undefined" + "encoding: hex"', () => testText(singleComplexBuffer, 'readable', undefined, undefined, 'hex'));96+test('.readable() can use "binary: false"', () => testText(complexChunksEnd, 'readable', false, undefined, 'utf8'));97+test('.readable() can use "binary: false" + "encoding: utf16le"', () => testText(complexChunksEnd, 'readable', false, undefined, 'utf16le'));98+test('.readable() can use "binary: false" + "encoding: buffer"', () => testText(singleComplexBuffer, 'readable', false, undefined, 'buffer'));99+test('.readable() can use "binary: false" + "encoding: hex"', () => testText(singleComplexBuffer, 'readable', false, undefined, 'hex'));100+test('.readable() can use "binary: false" + "preserveNewlines: true"', () => testText(complexChunksEnd, 'readable', false, true, 'utf8'));101+test('.readable() can use "binary: false" + "preserveNewlines: false"', () => testText(complexChunks, 'readable', false, false, 'utf8'));102+test('.duplex() can use "binary: true"', () => testText(singleComplexBuffer, 'duplex', true, undefined, 'utf8'));103+test('.duplex() can use "binary: true" + "encoding: utf16le"', () => testText(singleComplexUtf16Buffer, 'duplex', true, undefined, 'utf16le'));104+test('.duplex() can use "binary: true" + "encoding: buffer"', () => testText(singleComplexBuffer, 'duplex', true, undefined, 'buffer'));105+test('.duplex() can use "binary: true" + "encoding: hex"', () => testText(singleComplexBuffer, 'duplex', true, undefined, 'hex'));106+test('.duplex() can use "binary: undefined"', () => testText(singleComplexBuffer, 'duplex', undefined, undefined, 'utf8'));107+test('.duplex() can use "binary: undefined" + "encoding: utf16le"', () => testText(singleComplexUtf16Buffer, 'duplex', undefined, undefined, 'utf16le'));108+test('.duplex() can use "binary: undefined" + "encoding: "buffer"', () => testText(singleComplexBuffer, 'duplex', undefined, undefined, 'buffer'));109+test('.duplex() can use "binary: undefined" + "encoding: "hex"', () => testText(singleComplexBuffer, 'duplex', undefined, undefined, 'hex'));110+test('.duplex() can use "binary: false"', () => testText(complexChunksEnd, 'duplex', false, undefined, 'utf8'));111+test('.duplex() can use "binary: false" + "encoding: utf16le"', () => testText(complexChunksEnd, 'duplex', false, undefined, 'utf16le'));112+test('.duplex() can use "binary: false" + "encoding: buffer"', () => testText(singleComplexBuffer, 'duplex', false, undefined, 'buffer'));113+test('.duplex() can use "binary: false" + "encoding: hex"', () => testText(singleComplexBuffer, 'duplex', false, undefined, 'hex'));114+test('.duplex() can use "binary: false" + "preserveNewlines: true"', () => testText(complexChunksEnd, 'duplex', false, true, 'utf8'));115+test('.duplex() can use "binary: false" + "preserveNewlines: false"', () => testText(complexChunks, 'duplex', false, false, 'utf8'));116 116-const testTextOutput = async (t, expectedOutput, methodName, preserveNewlines) => {117+const testTextOutput = async (expectedOutput, methodName, preserveNewlines) => {118 const subprocess = getSubprocess(methodName, complexFull);119 const stream = subprocess[methodName]({binary: false, preserveNewlines});120 120- await assertStreamOutput(t, stream, expectedOutput);121- await assertSubprocessOutput(t, subprocess, complexFull);121+ await assertStreamOutput(stream, expectedOutput);122+ await assertSubprocessOutput(subprocess, complexFull);123 };124 124-test('.readable() "binary: false" keeps output as is', testTextOutput, complexFull, 'readable', undefined);125-test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'readable', true);126-test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'readable', false);127-test('.duplex() "binary: false" keeps output as is', testTextOutput, complexFull, 'duplex', undefined);128-test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', testTextOutput, complexFull, 'duplex', true);129-test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', testTextOutput, noNewlinesFull, 'duplex', false);125+test('.readable() "binary: false" keeps output as is', () => testTextOutput(complexFull, 'readable', undefined));126+test('.readable() "binary: false" + "preserveNewlines: true" keeps output as is', () => testTextOutput(complexFull, 'readable', true));127+test('.readable() "binary: false" + "preserveNewlines: false" removes all newlines', () => testTextOutput(noNewlinesFull, 'readable', false));128+test('.duplex() "binary: false" keeps output as is', () => testTextOutput(complexFull, 'duplex', undefined));129+test('.duplex() "binary: false" + "preserveNewlines: true" keeps output as is', () => testTextOutput(complexFull, 'duplex', true));130+test('.duplex() "binary: false" + "preserveNewlines: false" removes all newlines', () => testTextOutput(noNewlinesFull, 'duplex', false));131 132 // eslint-disable-next-line max-params132-const testObjectMode = async (t, expectedChunks, methodName, encoding, initialObjectMode, finalObjectMode, binary, options) => {133+const 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 }138 138- 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));142 143 const stream = subprocess[methodName]({binary, preserveNewlines: true});144 145 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 }150 150- 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));154 154- await assertChunks(t, stream, expectedChunks, methodName);155+ await assertChunks(stream, expectedChunks, methodName);156 await subprocess;157 };158 158-test('.iterable() uses Uint8Arrays with "binary: true"', testObjectMode, simpleChunksUint8Array, 'iterable', null, false, false, true);159-test('.iterable() uses Uint8Arrays with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true);160-test('.iterable() uses Uint8Arrays with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'});161-test('.iterable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()});162-test('.iterable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'iterable', null, false, true, false);163-test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'iterable', 'utf8', false, true, false);164-test('.iterable() uses Uint8Arrays in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunksUint8Array, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'});165-test('.iterable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()});166-test('.readable() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'readable', null, false, false, true);167-test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true);168-test('.readable() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'});169-test('.readable() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()});170-test('.readable() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'readable', null, false, true, false);171-test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'readable', 'utf8', false, true, false);172-test('.readable() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'});173-test('.readable() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()});174-test('.duplex() uses Buffers with "binary: true"', testObjectMode, simpleChunksBuffer, 'duplex', null, false, false, true);175-test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true);176-test('.duplex() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'});177-test('.duplex() uses strings in objectMode with "binary: true" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()});178-test('.duplex() uses strings in objectMode with "binary: false"', testObjectMode, simpleLines, 'duplex', null, false, true, false);179-test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', testObjectMode, simpleLines, 'duplex', 'utf8', false, true, false);180-test('.duplex() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', testObjectMode, simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'});181-test('.duplex() uses strings in objectMode with "binary: false" and object transforms', testObjectMode, foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()});159+test('.iterable() uses Uint8Arrays with "binary: true"', () => testObjectMode(simpleChunksUint8Array, 'iterable', null, false, false, true));160+test('.iterable() uses Uint8Arrays with "binary: true" and .setEncoding("utf8")', () => testObjectMode(simpleChunksUint8Array, 'iterable', 'utf8', false, false, true));161+test('.iterable() uses Uint8Arrays with "binary: true", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunksUint8Array, 'iterable', 'utf8', false, false, true, {encoding: 'buffer'}));162+test('.iterable() uses strings in objectMode with "binary: true" and object transforms', () => testObjectMode(foobarObjectChunks, 'iterable', null, true, true, true, {stdout: outputObjectGenerator()}));163+test('.iterable() uses strings in objectMode with "binary: false"', () => testObjectMode(simpleLines, 'iterable', null, false, true, false));164+test('.iterable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', () => testObjectMode(simpleLines, 'iterable', 'utf8', false, true, false));165+test('.iterable() uses Uint8Arrays in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunksUint8Array, 'iterable', 'utf8', false, true, false, {encoding: 'buffer'}));166+test('.iterable() uses strings in objectMode with "binary: false" and object transforms', () => testObjectMode(foobarObjectChunks, 'iterable', null, true, true, false, {stdout: outputObjectGenerator()}));167+test('.readable() uses Buffers with "binary: true"', () => testObjectMode(simpleChunksBuffer, 'readable', null, false, false, true));168+test('.readable() uses strings with "binary: true" and .setEncoding("utf8")', () => testObjectMode(simpleChunks, 'readable', 'utf8', false, false, true));169+test('.readable() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunks, 'readable', 'utf8', false, false, true, {encoding: 'buffer'}));170+test('.readable() uses strings in objectMode with "binary: true" and object transforms', () => testObjectMode(foobarObjectChunks, 'readable', null, true, true, true, {stdout: outputObjectGenerator()}));171+test('.readable() uses strings in objectMode with "binary: false"', () => testObjectMode(simpleLines, 'readable', null, false, true, false));172+test('.readable() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', () => testObjectMode(simpleLines, 'readable', 'utf8', false, true, false));173+test('.readable() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunks, 'readable', 'utf8', false, false, false, {encoding: 'buffer'}));174+test('.readable() uses strings in objectMode with "binary: false" and object transforms', () => testObjectMode(foobarObjectChunks, 'readable', null, true, true, false, {stdout: outputObjectGenerator()}));175+test('.duplex() uses Buffers with "binary: true"', () => testObjectMode(simpleChunksBuffer, 'duplex', null, false, false, true));176+test('.duplex() uses strings with "binary: true" and .setEncoding("utf8")', () => testObjectMode(simpleChunks, 'duplex', 'utf8', false, false, true));177+test('.duplex() uses strings with "binary: true", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunks, 'duplex', 'utf8', false, false, true, {encoding: 'buffer'}));178+test('.duplex() uses strings in objectMode with "binary: true" and object transforms', () => testObjectMode(foobarObjectChunks, 'duplex', null, true, true, true, {stdout: outputObjectGenerator()}));179+test('.duplex() uses strings in objectMode with "binary: false"', () => testObjectMode(simpleLines, 'duplex', null, false, true, false));180+test('.duplex() uses strings in objectMode with "binary: false" and .setEncoding("utf8")', () => testObjectMode(simpleLines, 'duplex', 'utf8', false, true, false));181+test('.duplex() uses strings in objectMode with "binary: false", .setEncoding("utf8") and "encoding: buffer"', () => testObjectMode(simpleChunks, 'duplex', 'utf8', false, false, false, {encoding: 'buffer'}));182+test('.duplex() uses strings in objectMode with "binary: false" and object transforms', () => testObjectMode(foobarObjectChunks, 'duplex', null, true, true, false, {stdout: outputObjectGenerator()}));183 183-const testObjectSplit = async (t, methodName) => {184+const 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 };190 190-test('.iterable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'iterable');191-test('.readable() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'readable');192-test('.duplex() "binary: false" does not split lines of strings produced by object transforms', testObjectSplit, 'duplex');191+test('.iterable() "binary: false" does not split lines of strings produced by object transforms', () => testObjectSplit('iterable'));192+test('.readable() "binary: false" does not split lines of strings produced by object transforms', () => testObjectSplit('readable'));193+test('.duplex() "binary: false" does not split lines of strings produced by object transforms', () => testObjectSplit('duplex'));194 194-const testMultibyteCharacters = async (t, methodName) => {195+const 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 };204 204-test('.iterable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'iterable');205-test('.readable() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'readable');206-test('.duplex() "binary: false" handles partial multibyte characters', testMultibyteCharacters, 'duplex');205+test('.iterable() "binary: false" handles partial multibyte characters', () => testMultibyteCharacters('iterable'));206+test('.readable() "binary: false" handles partial multibyte characters', () => testMultibyteCharacters('readable'));207+test('.duplex() "binary: false" handles partial multibyte characters', () => testMultibyteCharacters('duplex'));modified:test/io/max-buffer.js+291 added-264 removed
1+import assert from 'node:assert/strict';2 import {Buffer} from 'node:buffer';2-import test from 'ava';3+import {readFile, rm} from 'node:fs/promises';4+import test from 'node:test';5 import getStream from 'get-stream';6+import tempfile from 'tempfile';7+import {assertThrows, assertRejects} from '../helpers/assert.js';8 import {execa, execaSync} from '../../index.js';9 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10 import {fullStdio} from '../helpers/stdio.js';11 import {getEarlyErrorSubprocess} from '../helpers/early-error.js';4 unmodified lines16 17 const maxBufferMessage = {message: /maxBuffer exceeded/};18 const maxBufferCodeSync = {code: 'ENOBUFS'};19 16-const runMaxBuffer = async (t, execaMethod, fdNumber, options) => {20+const 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 };30 31 const getMaxBufferSubprocess = (execaMethod, fdNumber, {length = maxBuffer, ...options} = {}) =>32 execaMethod('max-buffer.js', [`${fdNumber}`, `${length + 1}`], {...fullStdio, maxBuffer, ...options});33 34 const getExpectedOutput = (length = maxBuffer) => '.'.repeat(length);35 32-const testMaxBufferSuccess = async (t, execaMethod, fdNumber, all) => {36+const 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 };40 37-test('maxBuffer does not affect stdout if too high', testMaxBufferSuccess, execa, 1, false);38-test('maxBuffer does not affect stderr if too high', testMaxBufferSuccess, execa, 2, false);39-test('maxBuffer does not affect stdio[*] if too high', testMaxBufferSuccess, execa, 3, false);40-test('maxBuffer does not affect all if too high', testMaxBufferSuccess, execa, 1, true);41-test('maxBuffer does not affect stdout if too high, sync', testMaxBufferSuccess, execaSync, 1, false);42-test('maxBuffer does not affect stderr if too high, sync', testMaxBufferSuccess, execaSync, 2, false);43-test('maxBuffer does not affect stdio[*] if too high, sync', testMaxBufferSuccess, execaSync, 3, false);44-test('maxBuffer does not affect all if too high, sync', testMaxBufferSuccess, execaSync, 1, true);41+test('maxBuffer does not affect stdout if too high', () => testMaxBufferSuccess(execa, 1, false));42+test('maxBuffer does not affect stderr if too high', () => testMaxBufferSuccess(execa, 2, false));43+test('maxBuffer does not affect stdio[*] if too high', () => testMaxBufferSuccess(execa, 3, false));44+test('maxBuffer does not affect all if too high', () => testMaxBufferSuccess(execa, 1, true));45+test('maxBuffer does not affect stdout if too high, sync', () => testMaxBufferSuccess(execaSync, 1, false));46+test('maxBuffer does not affect stderr if too high, sync', () => testMaxBufferSuccess(execaSync, 2, false));47+test('maxBuffer does not affect stdio[*] if too high, sync', () => testMaxBufferSuccess(execaSync, 3, false));48+test('maxBuffer does not affect all if too high, sync', () => testMaxBufferSuccess(execaSync, 1, true));49 46-const testGracefulExit = async (t, fixtureName, expectedExitCode) => {47- const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = await t.throwsAsync(50+const 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 };61 58-test('maxBuffer terminates stream gracefully, more writes', testGracefulExit, 'noop-repeat.js', 1);59-test('maxBuffer terminates stream gracefully, no more writes', testGracefulExit, 'noop-fd.js', 0);62+test('maxBuffer terminates stream gracefully, more writes', () => testGracefulExit('noop-repeat.js', 1));63+test('maxBuffer terminates stream gracefully, no more writes', () => testGracefulExit('noop-fd.js', 0));64 61-const testGracefulExitSync = (t, fixtureName) => {62- const {isMaxBuffer, shortMessage, exitCode, signal, stdout} = t.throws(() => {65+const 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 };75 72-test('maxBuffer terminate stream with killSignal, more writes, sync', testGracefulExitSync, 'noop-repeat.js');73-test('maxBuffer terminate stream with killSignal, no more writes, sync', testGracefulExitSync, 'noop-fd.js');76+test('maxBuffer terminate stream with killSignal, more writes, sync', () => testGracefulExitSync('noop-repeat.js'));77+test('maxBuffer terminate stream with killSignal, no more writes, sync', () => testGracefulExitSync('noop-fd.js'));78 75-const testMaxBufferLimit = async (t, execaMethod, fdNumber, all) => {79+const 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 };85 82-test('maxBuffer truncates stdout', testMaxBufferLimit, execa, 1, false);83-test('maxBuffer truncates stderr', testMaxBufferLimit, execa, 2, false);84-test('maxBuffer truncates stdio[*]', testMaxBufferLimit, execa, 3, false);85-test('maxBuffer truncates all', testMaxBufferLimit, execa, 1, true);86-test('maxBuffer truncates stdout, sync', testMaxBufferLimit, execaSync, 1, false);87-test('maxBuffer truncates stderr, sync', testMaxBufferLimit, execaSync, 2, false);88-test('maxBuffer truncates stdio[*], sync', testMaxBufferLimit, execaSync, 3, false);89-test('maxBuffer truncates all, sync', testMaxBufferLimit, execaSync, 1, true);86+test('maxBuffer truncates stdout', () => testMaxBufferLimit(execa, 1, false));87+test('maxBuffer truncates stderr', () => testMaxBufferLimit(execa, 2, false));88+test('maxBuffer truncates stdio[*]', () => testMaxBufferLimit(execa, 3, false));89+test('maxBuffer truncates all', () => testMaxBufferLimit(execa, 1, true));90+test('maxBuffer truncates stdout, sync', () => testMaxBufferLimit(execaSync, 1, false));91+test('maxBuffer truncates stderr, sync', () => testMaxBufferLimit(execaSync, 2, false));92+test('maxBuffer truncates stdio[*], sync', () => testMaxBufferLimit(execaSync, 3, false));93+test('maxBuffer truncates all, sync', () => testMaxBufferLimit(execaSync, 1, true));94 95 const MAX_BUFFER_DEFAULT = 1e8;96 93-const testMaxBufferDefault = async (t, execaMethod, fdNumber, maxBuffer) => {97+const 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 };103 100-test('maxBuffer has a default value with stdout', testMaxBufferDefault, execa, 1, undefined);101-test('maxBuffer has a default value with stderr', testMaxBufferDefault, execa, 2, undefined);102-test('maxBuffer has a default value with stdio[*]', testMaxBufferDefault, execa, 3, undefined);103-test('maxBuffer has a default value with stdout, sync', testMaxBufferDefault, execaSync, 1, undefined);104-test('maxBuffer has a default value with stderr, sync', testMaxBufferDefault, execaSync, 2, undefined);105-test('maxBuffer has a default value with stdio[*], sync', testMaxBufferDefault, execaSync, 3, undefined);106-test('maxBuffer has a default value with stdout with fd-specific options', testMaxBufferDefault, execa, 1, {stderr: 1e9});107-test('maxBuffer has a default value with stderr with fd-specific options', testMaxBufferDefault, execa, 2, {stdout: 1e9});108-test('maxBuffer has a default value with stdio[*] with fd-specific options', testMaxBufferDefault, execa, 3, {stdout: 1e9});109-test('maxBuffer has a default value with stdout with empty fd-specific options', testMaxBufferDefault, execa, 1, {});104+test('maxBuffer has a default value with stdout', () => testMaxBufferDefault(execa, 1, undefined));105+test('maxBuffer has a default value with stderr', () => testMaxBufferDefault(execa, 2, undefined));106+test('maxBuffer has a default value with stdio[*]', () => testMaxBufferDefault(execa, 3, undefined));107+test('maxBuffer has a default value with stdout, sync', () => testMaxBufferDefault(execaSync, 1, undefined));108+test('maxBuffer has a default value with stderr, sync', () => testMaxBufferDefault(execaSync, 2, undefined));109+test('maxBuffer has a default value with stdio[*], sync', () => testMaxBufferDefault(execaSync, 3, undefined));110+test('maxBuffer has a default value with stdout with fd-specific options', () => testMaxBufferDefault(execa, 1, {stderr: 1e9}));111+test('maxBuffer has a default value with stderr with fd-specific options', () => testMaxBufferDefault(execa, 2, {stdout: 1e9}));112+test('maxBuffer has a default value with stdio[*] with fd-specific options', () => testMaxBufferDefault(execa, 3, {stdout: 1e9}));113+test('maxBuffer has a default value with stdout with empty fd-specific options', () => testMaxBufferDefault(execa, 1, {}));114 111-const testFdSpecific = async (t, fdNumber, fdName, execaMethod) => {115+const 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 };121 118-test('maxBuffer truncates file descriptors with fd-specific options, stdout', testFdSpecific, 1, 'stdout', execa);119-test('maxBuffer truncates file descriptors with fd-specific options, fd1', testFdSpecific, 1, 'fd1', execa);120-test('maxBuffer truncates file descriptors with fd-specific options, stderr', testFdSpecific, 2, 'stderr', execa);121-test('maxBuffer truncates file descriptors with fd-specific options, fd2', testFdSpecific, 2, 'fd2', execa);122-test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', testFdSpecific, 1, 'all', execa);123-test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', testFdSpecific, 2, 'all', execa);124-test('maxBuffer truncates file descriptors with fd-specific options, fd3', testFdSpecific, 3, 'fd3', execa);125-test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', testFdSpecific, 1, 'stdout', execaSync);126-test('maxBuffer.stderr is used for stderr with fd-specific options, stderr, sync', testFdSpecific, 2, 'stderr', execaSync);127-test('maxBuffer.fd3 is used for stdio[*] with fd-specific options, fd3, sync', testFdSpecific, 3, 'fd3', execaSync);122+test('maxBuffer truncates file descriptors with fd-specific options, stdout', () => testFdSpecific(1, 'stdout', execa));123+test('maxBuffer truncates file descriptors with fd-specific options, fd1', () => testFdSpecific(1, 'fd1', execa));124+test('maxBuffer truncates file descriptors with fd-specific options, stderr', () => testFdSpecific(2, 'stderr', execa));125+test('maxBuffer truncates file descriptors with fd-specific options, fd2', () => testFdSpecific(2, 'fd2', execa));126+test('maxBuffer truncates file descriptors with fd-specific options, stdout, all', () => testFdSpecific(1, 'all', execa));127+test('maxBuffer truncates file descriptors with fd-specific options, stderr, all', () => testFdSpecific(2, 'all', execa));128+test('maxBuffer truncates file descriptors with fd-specific options, fd3', () => testFdSpecific(3, 'fd3', execa));129+test('maxBuffer.stdout is used for stdout with fd-specific options, stdout, sync', () => testFdSpecific(1, 'stdout', execaSync));130+test('maxBuffer.stderr is used for stderr with fd-specific options, stderr, sync', () => testFdSpecific(2, 'stderr', execaSync));131+test('maxBuffer.fd3 is used for stdio[*] with fd-specific options, fd3, sync', () => testFdSpecific(3, 'fd3', execaSync));132 129-test('maxBuffer does not affect other file descriptors with fd-specific options', async t => {133+test('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 });137 134-test('maxBuffer.fd3 is invalid without stdio[3], even with ipc', t => {135- const {message} = t.throws(() => {138+test('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 });144 141-test('maxBuffer.fd3 and maxBuffer.ipc are distinct', async t => {145+test('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 });157 154-test('maxBuffer.stdout is used for other file descriptors with fd-specific options, sync', async t => {158+test('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 });164 165 // `spawnSync()`'s native `maxBuffer` is `maxBuffer.stdout`, so a lower limit on another file descriptor is only enforced from the output, after the subprocess exits162-test('maxBuffer.stderr is used when lower than maxBuffer.stdout, sync', t => {166+test('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 });179 176-test('maxBuffer.stderr is used when lower than maxBuffer.stdout', async t => {180+test('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 });190 187-test('maxBuffer is not hit when under each file descriptor\'s value, sync', t => {191+test('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 });198 199+// 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.201+const 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+};210+211+test('maxBuffer.stderr is ignored with buffer: false', () => testMaxBufferNoBuffer(execa));212+test('maxBuffer.stderr is ignored with buffer: false, sync', () => testMaxBufferNoBuffer(execaSync));213+214+// `spawnSync()`'s native `maxBuffer` limits the total output of all file descriptors, even when none of them is over its own limit215+test('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+});221+195-const testAll = async (t, shouldFail) => {222+const 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 lines232 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 }240 214- 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 };245 219-test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', testAll, false);220-test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', testAll, true);246+test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, below threshold', () => testAll(false));247+test('maxBuffer.stdout can differ from maxBuffer.stderr, combined with all, above threshold', () => testAll(true));248 222-const testInvalidFd = async (t, fdName, execaMethod) => {223- const {message} = t.throws(() => {249+const 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 };255 229-test('maxBuffer.stdin is invalid', testInvalidFd, 'stdin', execa);230-test('maxBuffer.fd0 is invalid', testInvalidFd, 'fd0', execa);231-test('maxBuffer.other is invalid', testInvalidFd, 'other', execa);232-test('maxBuffer.fd10 is invalid', testInvalidFd, 'fd10', execa);233-test('maxBuffer.stdin is invalid, sync', testInvalidFd, 'stdin', execaSync);234-test('maxBuffer.fd0 is invalid, sync', testInvalidFd, 'fd0', execaSync);235-test('maxBuffer.other is invalid, sync', testInvalidFd, 'other', execaSync);236-test('maxBuffer.fd10 is invalid, sync', testInvalidFd, 'fd10', execaSync);256+test('maxBuffer.stdin is invalid', () => testInvalidFd('stdin', execa));257+test('maxBuffer.fd0 is invalid', () => testInvalidFd('fd0', execa));258+test('maxBuffer.other is invalid', () => testInvalidFd('other', execa));259+test('maxBuffer.fd10 is invalid', () => testInvalidFd('fd10', execa));260+test('maxBuffer.stdin is invalid, sync', () => testInvalidFd('stdin', execaSync));261+test('maxBuffer.fd0 is invalid, sync', () => testInvalidFd('fd0', execaSync));262+test('maxBuffer.other is invalid, sync', () => testInvalidFd('other', execaSync));263+test('maxBuffer.fd10 is invalid, sync', () => testInvalidFd('fd10', execaSync));264 265 // 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.266 const SYNC_TIMEOUT = 1e4;267 268 // A file descriptor limit lower than `maxBuffer.stdout` does not stop the subprocess with synchronous methods, so the subprocess can still time out afterwards242-const testMaxBufferTimeoutSync = (t, fdNumber, fdName) => {269+const 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 };281 255-test('timeout is reported instead of maxBuffer.stderr, sync', testMaxBufferTimeoutSync, 2, 'stderr');256-test('timeout is reported instead of maxBuffer.fd3, sync', testMaxBufferTimeoutSync, 3, 'fd3');282+test('timeout is reported instead of maxBuffer.stderr, sync', () => testMaxBufferTimeoutSync(2, 'stderr'));283+test('timeout is reported instead of maxBuffer.fd3, sync', () => testMaxBufferTimeoutSync(3, 'fd3'));284 258-test('timeout does not truncate output under maxBuffer.stderr, sync', t => {259- const {timedOut, isMaxBuffer, stderr} = t.throws(() => {285+test('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 });293 294 // `maxBuffer.stdout` is enforced by `spawnSync()` itself, which stops the subprocess before it can time out268-test('maxBuffer.stdout is reported before timeout, sync', t => {295+test('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 });306 280-test('maxBuffer.stderr is reported with a non-zero exit code, sync', t => {307+test('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 });319 293-test('maxBuffer.stderr works with reject false, sync', t => {320+test('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 });329 303-test('maxBuffer.stderr works with lines, sync', t => {330+test('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 });338 312-test('maxBuffer.stdout is an upper bound for maxBuffer.stderr, sync', t => {339+test('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 });348 322-test('maxBuffer.stderr is not reported on spawn errors, sync', t => {323- const {code, isMaxBuffer} = t.throws(() => {349+test('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 });356 330-const testMaxBufferEncoding = async (t, execaMethod, fdNumber) => {331- const {shortMessage, stdio} = await runMaxBuffer(t, execaMethod, fdNumber, {encoding: 'buffer'});332- assertErrorMessage(t, shortMessage, {execaMethod, fdNumber, unit: 'bytes'});357+const 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 };364 338-test('maxBuffer works with encoding buffer and stdout', testMaxBufferEncoding, execa, 1);339-test('maxBuffer works with encoding buffer and stderr', testMaxBufferEncoding, execa, 2);340-test('maxBuffer works with encoding buffer and stdio[*]', testMaxBufferEncoding, execa, 3);341-test('maxBuffer works with encoding buffer and stdout, sync', testMaxBufferEncoding, execaSync, 1);342-test('maxBuffer works with encoding buffer and stderr, sync', testMaxBufferEncoding, execaSync, 2);343-test('maxBuffer works with encoding buffer and stdio[*], sync', testMaxBufferEncoding, execaSync, 3);365+test('maxBuffer works with encoding buffer and stdout', () => testMaxBufferEncoding(execa, 1));366+test('maxBuffer works with encoding buffer and stderr', () => testMaxBufferEncoding(execa, 2));367+test('maxBuffer works with encoding buffer and stdio[*]', () => testMaxBufferEncoding(execa, 3));368+test('maxBuffer works with encoding buffer and stdout, sync', () => testMaxBufferEncoding(execaSync, 1));369+test('maxBuffer works with encoding buffer and stderr, sync', () => testMaxBufferEncoding(execaSync, 2));370+test('maxBuffer works with encoding buffer and stdio[*], sync', () => testMaxBufferEncoding(execaSync, 3));371 345-const testMaxBufferHex = async (t, fdNumber) => {372+const 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 };378 352-test('maxBuffer works with other encodings and stdout', testMaxBufferHex, 1);353-test('maxBuffer works with other encodings and stderr', testMaxBufferHex, 2);354-test('maxBuffer works with other encodings and stdio[*]', testMaxBufferHex, 3);379+test('maxBuffer works with other encodings and stdout', () => testMaxBufferHex(1));380+test('maxBuffer works with other encodings and stderr', () => testMaxBufferHex(2));381+test('maxBuffer works with other encodings and stdio[*]', () => testMaxBufferHex(3));382 356-const testMaxBufferHexSync = async (t, fdNumber) => {383+const 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 };389 363-test('maxBuffer ignores other encodings and stdout, sync', testMaxBufferHexSync, 1);364-test('maxBuffer ignores other encodings and stderr, sync', testMaxBufferHexSync, 2);365-test('maxBuffer ignores other encodings and stdio[*], sync', testMaxBufferHexSync, 3);390+test('maxBuffer ignores other encodings and stdout, sync', () => testMaxBufferHexSync(1));391+test('maxBuffer ignores other encodings and stderr, sync', () => testMaxBufferHexSync(2));392+test('maxBuffer ignores other encodings and stdio[*], sync', () => testMaxBufferHexSync(3));393 367-const testNoMaxBuffer = async (t, fdNumber, buffer) => {394+const 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 };404 378-test('do not buffer stdout when `buffer` set to `false`', testNoMaxBuffer, 1, false);379-test('do not buffer stdout when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 1, {stdout: false});380-test('do not buffer stderr when `buffer` set to `false`', testNoMaxBuffer, 2, false);381-test('do not buffer stderr when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 2, {stderr: false});382-test('do not buffer stdio[*] when `buffer` set to `false`', testNoMaxBuffer, 3, false);383-test('do not buffer stdio[*] when `buffer` set to `false`, fd-specific', testNoMaxBuffer, 3, {fd3: false});405+test('do not buffer stdout when `buffer` set to `false`', () => testNoMaxBuffer(1, false));406+test('do not buffer stdout when `buffer` set to `false`, fd-specific', () => testNoMaxBuffer(1, {stdout: false}));407+test('do not buffer stderr when `buffer` set to `false`', () => testNoMaxBuffer(2, false));408+test('do not buffer stderr when `buffer` set to `false`, fd-specific', () => testNoMaxBuffer(2, {stderr: false}));409+test('do not buffer stdio[*] when `buffer` set to `false`', () => testNoMaxBuffer(3, false));410+test('do not buffer stdio[*] when `buffer` set to `false`, fd-specific', () => testNoMaxBuffer(3, {fd3: false}));411 385-const testNoMaxBufferSync = (t, fdNumber, buffer) => {412+const 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 };417 418 // @todo: add tests for fd3 once the following Node.js bug is fixed.419 // https://github.com/nodejs/node/issues/52422393-test('do not buffer stdout when `buffer` set to `false`, sync', testNoMaxBufferSync, 1, false);394-test('do not buffer stdout when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 1, {stdout: false});395-test('do not buffer stderr when `buffer` set to `false`, sync', testNoMaxBufferSync, 2, false);396-test('do not buffer stderr when `buffer` set to `false`, fd-specific, sync', testNoMaxBufferSync, 2, {stderr: false});420+test('do not buffer stdout when `buffer` set to `false`, sync', () => testNoMaxBufferSync(1, false));421+test('do not buffer stdout when `buffer` set to `false`, fd-specific, sync', () => testNoMaxBufferSync(1, {stdout: false}));422+test('do not buffer stderr when `buffer` set to `false`, sync', () => testNoMaxBufferSync(2, false));423+test('do not buffer stderr when `buffer` set to `false`, fd-specific, sync', () => testNoMaxBufferSync(2, {stderr: false}));424 398-const testNoMaxBufferSyncObjectPipe = (t, fdNumber, fdName, stdioOption) => {425+const 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 };434 408-test('do not buffer stdout object pipe when `buffer` set to `false`, sync', testNoMaxBufferSyncObjectPipe, 1, 'stdout', {value: 'pipe'});409-test('do not buffer stdout object pipe with input false when `buffer` set to `false`, sync', testNoMaxBufferSyncObjectPipe, 1, 'stdout', {value: 'pipe', input: false});410-test('do not buffer stdout object pipe with input true when `buffer` set to `false`, sync', testNoMaxBufferSyncObjectPipe, 1, 'stdout', {value: 'pipe', input: true});411-test('do not buffer stderr object pipe with input true when `buffer` set to `false`, sync', testNoMaxBufferSyncObjectPipe, 2, 'stderr', {value: 'pipe', input: true});435+test('do not buffer stdout object pipe when `buffer` set to `false`, sync', () => testNoMaxBufferSyncObjectPipe(1, 'stdout', {value: 'pipe'}));436+test('do not buffer stdout object pipe with input false when `buffer` set to `false`, sync', () => testNoMaxBufferSyncObjectPipe(1, 'stdout', {value: 'pipe', input: false}));437+test('do not buffer stdout object pipe with input true when `buffer` set to `false`, sync', () => testNoMaxBufferSyncObjectPipe(1, 'stdout', {value: 'pipe', input: true}));438+test('do not buffer stderr object pipe with input true when `buffer` set to `false`, sync', () => testNoMaxBufferSyncObjectPipe(2, 'stderr', {value: 'pipe', input: true}));439 413-const testMaxBufferAbort = async (t, fdNumber) => {440+const 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 };449 423-test('abort stream when hitting maxBuffer with stdout', testMaxBufferAbort, 1);424-test('abort stream when hitting maxBuffer with stderr', testMaxBufferAbort, 2);425-test('abort stream when hitting maxBuffer with stdio[*]', testMaxBufferAbort, 3);450+test('abort stream when hitting maxBuffer with stdout', () => testMaxBufferAbort(1));451+test('abort stream when hitting maxBuffer with stderr', () => testMaxBufferAbort(2));452+test('abort stream when hitting maxBuffer with stdio[*]', () => testMaxBufferAbort(3));453 427-test('error.isMaxBuffer is false on early errors', async t => {454+test('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 });459 433-test('maxBuffer works with result.ipcOutput', async t => {460+test('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 });474 448-test('maxBuffer is ignored with result.ipcOutput if buffer is false', async t => {475+test('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 });479 480 /*481 `result.ipcOutput` is counted in messages, which are indivisible, so any `maxBuffer` value the count cannot land on exactly must still be enforced.482 The threshold is hit as soon as buffering one more message would exceed it, which is how the stream-based `maxBuffer` behaves too.483 */457-const 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);484+const 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 };489 463-test('maxBuffer works with result.ipcOutput, negative', testIpcMaxBufferValue, -1, []);464-test('maxBuffer works with result.ipcOutput, 0', testIpcMaxBufferValue, 0, []);465-test('maxBuffer works with result.ipcOutput, below 1', testIpcMaxBufferValue, 0.5, []);466-test('maxBuffer works with result.ipcOutput, 1', testIpcMaxBufferValue, 1, [foobarArray[0]]);467-test('maxBuffer works with result.ipcOutput, fractional', testIpcMaxBufferValue, 1.5, [foobarArray[0]]);490+test('maxBuffer works with result.ipcOutput, negative', () => testIpcMaxBufferValue(-1, []));491+test('maxBuffer works with result.ipcOutput, 0', () => testIpcMaxBufferValue(0, []));492+test('maxBuffer works with result.ipcOutput, below 1', () => testIpcMaxBufferValue(0.5, []));493+test('maxBuffer works with result.ipcOutput, 1', () => testIpcMaxBufferValue(1, [foobarArray[0]]));494+test('maxBuffer works with result.ipcOutput, fractional', () => testIpcMaxBufferValue(1.5, [foobarArray[0]]));495 469-const testIpcMaxBufferNotHit = async (t, maxBuffer) => {496+const 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 };501 475-test('maxBuffer is not hit with result.ipcOutput, exact count', testIpcMaxBufferNotHit, 2);476-test('maxBuffer is not hit with result.ipcOutput, fractional', testIpcMaxBufferNotHit, 2.5);502+test('maxBuffer is not hit with result.ipcOutput, exact count', () => testIpcMaxBufferNotHit(2));503+test('maxBuffer is not hit with result.ipcOutput, fractional', () => testIpcMaxBufferNotHit(2.5));504 505 // The same `maxBuffer` value must be interpreted the same way whether the output is buffered as messages or as characters479-const testIpcMaxBufferLikeStream = async (t, maxBuffer) => {506+const 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 };514 488-test('maxBuffer with result.ipcOutput matches stdout, 0.5', testIpcMaxBufferLikeStream, 0.5);489-test('maxBuffer with result.ipcOutput matches stdout, 1', testIpcMaxBufferLikeStream, 1);490-test('maxBuffer with result.ipcOutput matches stdout, 1.5', testIpcMaxBufferLikeStream, 1.5);491-test('maxBuffer with result.ipcOutput matches stdout, 2', testIpcMaxBufferLikeStream, 2);515+test('maxBuffer with result.ipcOutput matches stdout, 0.5', () => testIpcMaxBufferLikeStream(0.5));516+test('maxBuffer with result.ipcOutput matches stdout, 1', () => testIpcMaxBufferLikeStream(1));517+test('maxBuffer with result.ipcOutput matches stdout, 1.5', () => testIpcMaxBufferLikeStream(1.5));518+test('maxBuffer with result.ipcOutput matches stdout, 2', () => testIpcMaxBufferLikeStream(2));modified:test/io/output-async.js+23 added-22 removed
1+import assert from 'node:assert/strict';2 import {once, defaultMaxListeners} from 'node:events';3 import process from 'node:process';4 import {setImmediate} from 'node:timers/promises';4-import test from 'ava';5+import test from 'node:test';6 import {execa} from '../../index.js';7 import {STANDARD_STREAMS} from '../helpers/stdio.js';8 import {foobarString} from '../helpers/input.js';9 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';12 unmodified lines22 });23 24 const onStdinRemoveListener = () => once(process.stdin, 'removeListener');25 25-const testListenersCleanup = async (t, isMultiple) => {26+const 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 }34 35 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 };40 40-test.serial('process.std* listeners are cleaned up on success with a single input', testListenersCleanup, false);41-test.serial('process.std* listeners are cleaned up on success with multiple inputs', testListenersCleanup, true);41+test('process.std* listeners are cleaned up on success with a single input', () => testListenersCleanup(false));42+test('process.std* listeners are cleaned up on success with multiple inputs', () => testListenersCleanup(true));43 43-test.serial('Can spawn many subprocesses in parallel', async t => {44+test('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 });48 48-const testMaxListeners = async (t, isMultiple, maxListenersCount) => {49- const checkMaxListeners = assertMaxListeners(t);49+const testMaxListeners = async (isMultiple, maxListenersCount) => {50+ const checkMaxListeners = assertMaxListeners();51 52 for (const standardStream of STANDARD_STREAMS) {53 standardStream.setMaxListeners(maxListenersCount);54 }55 56 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();63 64 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 };70 70-test.serial('No warning with maxListeners 1 and ["pipe", "inherit"]', testMaxListeners, false, 1);71-test.serial('No warning with maxListeners default and ["pipe", "inherit"]', testMaxListeners, false, defaultMaxListeners);72-test.serial('No warning with maxListeners 100 and ["pipe", "inherit"]', testMaxListeners, false, 100);73-test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"]', testMaxListeners, false, Infinity);74-test.serial('No warning with maxListeners 0 and ["pipe", "inherit"]', testMaxListeners, false, 0);75-test.serial('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 1);76-test.serial('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, defaultMaxListeners);77-test.serial('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 100);78-test.serial('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, Infinity);79-test.serial('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', testMaxListeners, true, 0);71+test('No warning with maxListeners 1 and ["pipe", "inherit"]', () => testMaxListeners(false, 1));72+test('No warning with maxListeners default and ["pipe", "inherit"]', () => testMaxListeners(false, defaultMaxListeners));73+test('No warning with maxListeners 100 and ["pipe", "inherit"]', () => testMaxListeners(false, 100));74+test('No warning with maxListeners Infinity and ["pipe", "inherit"]', () => testMaxListeners(false, Infinity));75+test('No warning with maxListeners 0 and ["pipe", "inherit"]', () => testMaxListeners(false, 0));76+test('No warning with maxListeners 1 and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, 1));77+test('No warning with maxListeners default and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, defaultMaxListeners));78+test('No warning with maxListeners 100 and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, 100));79+test('No warning with maxListeners Infinity and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, Infinity));80+test('No warning with maxListeners 0 and ["pipe", "inherit"], multiple inputs', () => testMaxListeners(true, 0));modified:test/io/output-sync.js+14 added-12 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows} from '../helpers/assert.js';4 import {execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {throwingGenerator} from '../helpers/generator.js';7 import {foobarString} from '../helpers/input.js';8 9 setFixtureDirectory();10 9-test('Handles errors with stdout generator, sync', t => {11+test('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 });18 17-test('Handles errors with stdout generator, spawn failure, sync', t => {19+test('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 });27 26-test('Handles errors with stdout generator, subprocess failure, sync', t => {28+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects, assertLike} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {getStdio, STANDARD_STREAMS} from '../helpers/stdio.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';8 9 setFixtureDirectory();10 9-const testDestroyStandard = async (t, fdNumber) => {11+const 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 };16 15-test('Does not destroy process.stdin on subprocess errors', testDestroyStandard, 0);16-test('Does not destroy process.stdout on subprocess errors', testDestroyStandard, 1);17-test('Does not destroy process.stderr on subprocess errors', testDestroyStandard, 2);17+test('Does not destroy process.stdin on subprocess errors', () => testDestroyStandard(0));18+test('Does not destroy process.stdout on subprocess errors', () => testDestroyStandard(1));19+test('Does not destroy process.stderr on subprocess errors', () => testDestroyStandard(2));20 19-const 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);21+const 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 };26 25-test('Does not destroy process.stdin on subprocess early errors', testDestroyStandardSpawn, 0);26-test('Does not destroy process.stdout on subprocess early errors', testDestroyStandardSpawn, 1);27-test('Does not destroy process.stderr on subprocess early errors', testDestroyStandardSpawn, 2);27+test('Does not destroy process.stdin on subprocess early errors', () => testDestroyStandardSpawn(0));28+test('Does not destroy process.stdout on subprocess early errors', () => testDestroyStandardSpawn(1));29+test('Does not destroy process.stderr on subprocess early errors', () => testDestroyStandardSpawn(2));30 29-const testDestroyStandardStream = async (t, fdNumber) => {31+const 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 };39 38-test('Does not destroy process.stdin on stream subprocess errors', testDestroyStandardStream, 0);39-test('Does not destroy process.stdout on stream subprocess errors', testDestroyStandardStream, 1);40-test('Does not destroy process.stderr on stream subprocess errors', testDestroyStandardStream, 2);40+test('Does not destroy process.stdin on stream subprocess errors', () => testDestroyStandardStream(0));41+test('Does not destroy process.stdout on stream subprocess errors', () => testDestroyStandardStream(1));42+test('Does not destroy process.stderr on stream subprocess errors', () => testDestroyStandardStream(2));modified:test/io/strip-newline.js+42 added-42 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {fullStdio} from '../helpers/stdio.js';6 import {noopGenerator} from '../helpers/generator.js';7 import {foobarString} from '../helpers/input.js';8 9 setFixtureDirectory();10 10-// eslint-disable-next-line max-params11-const testStripFinalNewline = async (t, fdNumber, stripFinalNewline, shouldStrip, execaMethod) => {11+const 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 };15 16-test('stripFinalNewline: default with stdout', testStripFinalNewline, 1, undefined, true, execa);17-test('stripFinalNewline: true with stdout', testStripFinalNewline, 1, true, true, execa);18-test('stripFinalNewline: false with stdout', testStripFinalNewline, 1, false, false, execa);19-test('stripFinalNewline: default with stderr', testStripFinalNewline, 2, undefined, true, execa);20-test('stripFinalNewline: true with stderr', testStripFinalNewline, 2, true, true, execa);21-test('stripFinalNewline: false with stderr', testStripFinalNewline, 2, false, false, execa);22-test('stripFinalNewline: default with stdio[*]', testStripFinalNewline, 3, undefined, true, execa);23-test('stripFinalNewline: true with stdio[*]', testStripFinalNewline, 3, true, true, execa);24-test('stripFinalNewline: false with stdio[*]', testStripFinalNewline, 3, false, false, execa);25-test('stripFinalNewline: default with stdout, fd-specific', testStripFinalNewline, 1, {}, true, execa);26-test('stripFinalNewline: true with stdout, fd-specific', testStripFinalNewline, 1, {stdout: true}, true, execa);27-test('stripFinalNewline: false with stdout, fd-specific', testStripFinalNewline, 1, {stdout: false}, false, execa);28-test('stripFinalNewline: default with stderr, fd-specific', testStripFinalNewline, 2, {}, true, execa);29-test('stripFinalNewline: true with stderr, fd-specific', testStripFinalNewline, 2, {stderr: true}, true, execa);30-test('stripFinalNewline: false with stderr, fd-specific', testStripFinalNewline, 2, {stderr: false}, false, execa);31-test('stripFinalNewline: default with stdio[*], fd-specific', testStripFinalNewline, 3, {}, true, execa);32-test('stripFinalNewline: true with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: true}, true, execa);33-test('stripFinalNewline: false with stdio[*], fd-specific', testStripFinalNewline, 3, {fd3: false}, false, execa);34-test('stripFinalNewline: default with stdout, sync', testStripFinalNewline, 1, undefined, true, execaSync);35-test('stripFinalNewline: true with stdout, sync', testStripFinalNewline, 1, true, true, execaSync);36-test('stripFinalNewline: false with stdout, sync', testStripFinalNewline, 1, false, false, execaSync);37-test('stripFinalNewline: default with stderr, sync', testStripFinalNewline, 2, undefined, true, execaSync);38-test('stripFinalNewline: true with stderr, sync', testStripFinalNewline, 2, true, true, execaSync);39-test('stripFinalNewline: false with stderr, sync', testStripFinalNewline, 2, false, false, execaSync);40-test('stripFinalNewline: default with stdio[*], sync', testStripFinalNewline, 3, undefined, true, execaSync);41-test('stripFinalNewline: true with stdio[*], sync', testStripFinalNewline, 3, true, true, execaSync);42-test('stripFinalNewline: false with stdio[*], sync', testStripFinalNewline, 3, false, false, execaSync);43-test('stripFinalNewline: default with stdout, fd-specific, sync', testStripFinalNewline, 1, {}, true, execaSync);44-test('stripFinalNewline: true with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: true}, true, execaSync);45-test('stripFinalNewline: false with stdout, fd-specific, sync', testStripFinalNewline, 1, {stdout: false}, false, execaSync);46-test('stripFinalNewline: default with stderr, fd-specific, sync', testStripFinalNewline, 2, {}, true, execaSync);47-test('stripFinalNewline: true with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: true}, true, execaSync);48-test('stripFinalNewline: false with stderr, fd-specific, sync', testStripFinalNewline, 2, {stderr: false}, false, execaSync);49-test('stripFinalNewline: default with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {}, true, execaSync);50-test('stripFinalNewline: true with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: true}, true, execaSync);51-test('stripFinalNewline: false with stdio[*], fd-specific, sync', testStripFinalNewline, 3, {fd3: false}, false, execaSync);16+test('stripFinalNewline: default with stdout', () => testStripFinalNewline(1, undefined, true, execa));17+test('stripFinalNewline: true with stdout', () => testStripFinalNewline(1, true, true, execa));18+test('stripFinalNewline: false with stdout', () => testStripFinalNewline(1, false, false, execa));19+test('stripFinalNewline: default with stderr', () => testStripFinalNewline(2, undefined, true, execa));20+test('stripFinalNewline: true with stderr', () => testStripFinalNewline(2, true, true, execa));21+test('stripFinalNewline: false with stderr', () => testStripFinalNewline(2, false, false, execa));22+test('stripFinalNewline: default with stdio[*]', () => testStripFinalNewline(3, undefined, true, execa));23+test('stripFinalNewline: true with stdio[*]', () => testStripFinalNewline(3, true, true, execa));24+test('stripFinalNewline: false with stdio[*]', () => testStripFinalNewline(3, false, false, execa));25+test('stripFinalNewline: default with stdout, fd-specific', () => testStripFinalNewline(1, {}, true, execa));26+test('stripFinalNewline: true with stdout, fd-specific', () => testStripFinalNewline(1, {stdout: true}, true, execa));27+test('stripFinalNewline: false with stdout, fd-specific', () => testStripFinalNewline(1, {stdout: false}, false, execa));28+test('stripFinalNewline: default with stderr, fd-specific', () => testStripFinalNewline(2, {}, true, execa));29+test('stripFinalNewline: true with stderr, fd-specific', () => testStripFinalNewline(2, {stderr: true}, true, execa));30+test('stripFinalNewline: false with stderr, fd-specific', () => testStripFinalNewline(2, {stderr: false}, false, execa));31+test('stripFinalNewline: default with stdio[*], fd-specific', () => testStripFinalNewline(3, {}, true, execa));32+test('stripFinalNewline: true with stdio[*], fd-specific', () => testStripFinalNewline(3, {fd3: true}, true, execa));33+test('stripFinalNewline: false with stdio[*], fd-specific', () => testStripFinalNewline(3, {fd3: false}, false, execa));34+test('stripFinalNewline: default with stdout, sync', () => testStripFinalNewline(1, undefined, true, execaSync));35+test('stripFinalNewline: true with stdout, sync', () => testStripFinalNewline(1, true, true, execaSync));36+test('stripFinalNewline: false with stdout, sync', () => testStripFinalNewline(1, false, false, execaSync));37+test('stripFinalNewline: default with stderr, sync', () => testStripFinalNewline(2, undefined, true, execaSync));38+test('stripFinalNewline: true with stderr, sync', () => testStripFinalNewline(2, true, true, execaSync));39+test('stripFinalNewline: false with stderr, sync', () => testStripFinalNewline(2, false, false, execaSync));40+test('stripFinalNewline: default with stdio[*], sync', () => testStripFinalNewline(3, undefined, true, execaSync));41+test('stripFinalNewline: true with stdio[*], sync', () => testStripFinalNewline(3, true, true, execaSync));42+test('stripFinalNewline: false with stdio[*], sync', () => testStripFinalNewline(3, false, false, execaSync));43+test('stripFinalNewline: default with stdout, fd-specific, sync', () => testStripFinalNewline(1, {}, true, execaSync));44+test('stripFinalNewline: true with stdout, fd-specific, sync', () => testStripFinalNewline(1, {stdout: true}, true, execaSync));45+test('stripFinalNewline: false with stdout, fd-specific, sync', () => testStripFinalNewline(1, {stdout: false}, false, execaSync));46+test('stripFinalNewline: default with stderr, fd-specific, sync', () => testStripFinalNewline(2, {}, true, execaSync));47+test('stripFinalNewline: true with stderr, fd-specific, sync', () => testStripFinalNewline(2, {stderr: true}, true, execaSync));48+test('stripFinalNewline: false with stderr, fd-specific, sync', () => testStripFinalNewline(2, {stderr: false}, false, execaSync));49+test('stripFinalNewline: default with stdio[*], fd-specific, sync', () => testStripFinalNewline(3, {}, true, execaSync));50+test('stripFinalNewline: true with stdio[*], fd-specific, sync', () => testStripFinalNewline(3, {fd3: true}, true, execaSync));51+test('stripFinalNewline: false with stdio[*], fd-specific, sync', () => testStripFinalNewline(3, {fd3: false}, false, execaSync));52 53-test('stripFinalNewline is not used in objectMode', async t => {53+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows, assertRejects} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString, foobarArray} from '../helpers/input.js';7 import {PARALLEL_COUNT} from '../helpers/parallel.js';8 import {fullStdio} from '../helpers/stdio.js';9 10 setFixtureDirectory();11 10-const testResultIpc = async (t, options) => {12+const 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 };16 15-test('Sets result.ipcOutput', testResultIpc, {});16-test('Sets result.ipcOutput, fd-specific buffer', testResultIpc, {buffer: {stdout: false}});17+test('Sets result.ipcOutput', () => testResultIpc({}));18+test('Sets result.ipcOutput, fd-specific buffer', () => testResultIpc({buffer: {stdout: false}}));19 18-const testResultNoBuffer = async (t, options) => {20+const testResultNoBuffer = async options => {21 const {ipcOutput} = await execa('ipc-send.js', {...options, ipc: true});20- t.deepEqual(ipcOutput, []);22+ assert.deepEqual(ipcOutput, []);23 };24 23-test('Sets empty result.ipcOutput if buffer is false', testResultNoBuffer, {buffer: false});24-test('Sets empty result.ipcOutput if buffer is false, fd-specific buffer', testResultNoBuffer, {buffer: {ipc: false}});25+test('Sets empty result.ipcOutput if buffer is false', () => testResultNoBuffer({buffer: false}));26+test('Sets empty result.ipcOutput if buffer is false, fd-specific buffer', () => testResultNoBuffer({buffer: {ipc: false}}));27 26-test('buffer.fd3 is invalid without stdio[3], even with ipc', t => {27- const {message} = t.throws(() => {28+test('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 });34 33-test('buffer.fd3 does not affect result.ipcOutput', async t => {35+test('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 });39 38-test('Can use IPC methods when buffer is false', async t => {40+test('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 });46 45-test('Sets empty result.ipcOutput if ipc is false', async t => {47+test('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 });51 50-test('Sets empty result.ipcOutput, sync', t => {52+test('Sets empty result.ipcOutput, sync', () => {53 const {ipcOutput} = execaSync('empty.js');52- t.deepEqual(ipcOutput, []);54+ assert.deepEqual(ipcOutput, []);55 });56 55-const testErrorIpc = async (t, options) => {56- const {ipcOutput} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));57- t.deepEqual(ipcOutput, [foobarString]);57+const testErrorIpc = async options => {58+ const {ipcOutput} = await assertRejects(execa('ipc-send-fail.js', {...options, ipc: true}));59+ assert.deepEqual(ipcOutput, [foobarString]);60 };61 60-test('Sets error.ipcOutput', testErrorIpc, {});61-test('Sets error.ipcOutput, fd-specific buffer', testErrorIpc, {buffer: {stdout: false}});62+test('Sets error.ipcOutput', () => testErrorIpc({}));63+test('Sets error.ipcOutput, fd-specific buffer', () => testErrorIpc({buffer: {stdout: false}}));64 63-const testErrorNoBuffer = async (t, options) => {64- const {ipcOutput} = await t.throwsAsync(execa('ipc-send-fail.js', {...options, ipc: true}));65- t.deepEqual(ipcOutput, []);65+const testErrorNoBuffer = async options => {66+ const {ipcOutput} = await assertRejects(execa('ipc-send-fail.js', {...options, ipc: true}));67+ assert.deepEqual(ipcOutput, []);68 };69 68-test('Sets empty error.ipcOutput if buffer is false', testErrorNoBuffer, {buffer: false});69-test('Sets empty error.ipcOutput if buffer is false, fd-specific buffer', testErrorNoBuffer, {buffer: {ipc: false}});70+test('Sets empty error.ipcOutput if buffer is false', () => testErrorNoBuffer({buffer: false}));71+test('Sets empty error.ipcOutput if buffer is false, fd-specific buffer', () => testErrorNoBuffer({buffer: {ipc: false}}));72 71-test('Sets empty error.ipcOutput if ipc is false', async t => {72- const {ipcOutput} = await t.throwsAsync(execa('fail.js'));73- t.deepEqual(ipcOutput, []);73+test('Sets empty error.ipcOutput if ipc is false', async () => {74+ const {ipcOutput} = await assertRejects(execa('fail.js'));75+ assert.deepEqual(ipcOutput, []);76 });77 76-test('Sets empty error.ipcOutput, sync', t => {77- const {ipcOutput} = t.throws(() => execaSync('fail.js'));78- t.deepEqual(ipcOutput, []);78+test('Sets empty error.ipcOutput, sync', () => {79+ const {ipcOutput} = assertThrows(() => execaSync('fail.js'));80+ assert.deepEqual(ipcOutput, []);81 });82 81-test.serial('Can retrieve initial IPC messages under heavy load', async t => {83+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString, foobarArray} from '../helpers/input.js';7 import {iterateAllMessages, isAlwaysTrue} from '../helpers/ipc.js';8 9 setFixtureDirectory();10 9-const testParentErrorOne = async (t, filter, buffer) => {11+const testParentErrorOne = async (filter, buffer) => {12 const subprocess = execa('ipc-send.js', {ipc: true, buffer});13 14 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);18 17- 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 };27 26-test('"error" event does not interrupt subprocess.getOneMessage(), buffer false', testParentErrorOne, undefined, false);27-test('"error" event does not interrupt subprocess.getOneMessage(), buffer true', testParentErrorOne, undefined, true);28-test('"error" event does not interrupt subprocess.getOneMessage(), buffer false, filter', testParentErrorOne, isAlwaysTrue, false);29-test('"error" event does not interrupt subprocess.getOneMessage(), buffer true, filter', testParentErrorOne, isAlwaysTrue, true);28+test('"error" event does not interrupt subprocess.getOneMessage(), buffer false', () => testParentErrorOne(undefined, false));29+test('"error" event does not interrupt subprocess.getOneMessage(), buffer true', () => testParentErrorOne(undefined, true));30+test('"error" event does not interrupt subprocess.getOneMessage(), buffer false, filter', () => testParentErrorOne(isAlwaysTrue, false));31+test('"error" event does not interrupt subprocess.getOneMessage(), buffer true, filter', () => testParentErrorOne(isAlwaysTrue, true));32 31-const testSubprocessErrorOne = async (t, filter, buffer) => {33+const 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);37 38 const {ipcOutput} = await subprocess;39 if (buffer) {38- t.deepEqual(ipcOutput, [foobarString]);40+ assert.deepEqual(ipcOutput, [foobarString]);41 }42 };43 42-test('"error" event does not interrupt exports.getOneMessage(), buffer false', testSubprocessErrorOne, false, false);43-test('"error" event does not interrupt exports.getOneMessage(), buffer true', testSubprocessErrorOne, false, true);44-test('"error" event does not interrupt exports.getOneMessage(), buffer false, filter', testSubprocessErrorOne, true, false);45-test('"error" event does not interrupt exports.getOneMessage(), buffer true, filter', testSubprocessErrorOne, true, true);44+test('"error" event does not interrupt exports.getOneMessage(), buffer false', () => testSubprocessErrorOne(false, false));45+test('"error" event does not interrupt exports.getOneMessage(), buffer true', () => testSubprocessErrorOne(false, true));46+test('"error" event does not interrupt exports.getOneMessage(), buffer false, filter', () => testSubprocessErrorOne(true, false));47+test('"error" event does not interrupt exports.getOneMessage(), buffer true, filter', () => testSubprocessErrorOne(true, true));48 47-const testParentErrorEach = async (t, buffer) => {49+const testParentErrorEach = async buffer => {50 const subprocess = execa('ipc-send-twice.js', {ipc: true, buffer});51 52 const promise = iterateAllMessages(subprocess);53 const cause = new Error(foobarString);54 subprocess.nodeChildProcess.emit('error', cause);55 54- 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 };65 64-test('"error" event does not interrupt subprocess.getEachMessage(), buffer false', testParentErrorEach, false);65-test('"error" event does not interrupt subprocess.getEachMessage(), buffer true', testParentErrorEach, true);66+test('"error" event does not interrupt subprocess.getEachMessage(), buffer false', () => testParentErrorEach(false));67+test('"error" event does not interrupt subprocess.getEachMessage(), buffer true', () => testParentErrorEach(true));68 67-const testSubprocessErrorEach = async (t, filter, buffer) => {69+const 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);74 75 const {ipcOutput} = await subprocess;76 if (buffer) {75- t.deepEqual(ipcOutput, ['.']);77+ assert.deepEqual(ipcOutput, ['.']);78 }79 };80 79-test('"error" event does not interrupt exports.getEachMessage(), buffer false', testSubprocessErrorEach, 'ipc-iterate-error.js', false);80-test('"error" event does not interrupt exports.getEachMessage(), buffer true', testSubprocessErrorEach, 'ipc-iterate-error.js', true);81+test('"error" event does not interrupt exports.getEachMessage(), buffer false', () => testSubprocessErrorEach('ipc-iterate-error.js', false));82+test('"error" event does not interrupt exports.getEachMessage(), buffer true', () => testSubprocessErrorEach('ipc-iterate-error.js', true));83 82-test('"error" event does not interrupt result.ipcOutput', async t => {84+test('"error" event does not interrupt result.ipcOutput', async () => {85 const subprocess = execa('ipc-echo-twice.js', {ipcInput: foobarString});86 87 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);92 91- 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
1+import assert from 'node:assert/strict';2 import {scheduler} from 'node:timers/promises';2-import test from 'ava';3+import test from 'node:test';4+import {assertRejects} from '../helpers/assert.js';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {foobarString, foobarArray} from '../helpers/input.js';8 import {PARALLEL_COUNT} from '../helpers/parallel.js';9 import {iterateAllMessages} from '../helpers/ipc.js';10+/* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */11 12 setFixtureDirectory();13 11-test('Can iterate over IPC messages', async t => {14+test('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 }20 21 const {ipcOutput} = await subprocess;19- t.deepEqual(ipcOutput, foobarArray);22+ assert.deepEqual(ipcOutput, foobarArray);23 });24 22-test('Can iterate over IPC messages in subprocess', async t => {25+test('Can iterate over IPC messages in subprocess', async () => {26 const subprocess = execa('ipc-iterate.js', {ipc: true});27 28 await subprocess.sendMessage('.');29 await subprocess.sendMessage('.');30 await subprocess.sendMessage(foobarString);31 32 const {ipcOutput} = await subprocess;30- t.deepEqual(ipcOutput, ['.', '.']);33+ assert.deepEqual(ipcOutput, ['.', '.']);34 });35 33-test('subprocess.getEachMessage() can be called twice at the same time', async t => {36+test('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 );42 43 const {ipcOutput} = await subprocess;41- t.deepEqual(ipcOutput, foobarArray);44+ assert.deepEqual(ipcOutput, foobarArray);45 });46 44-const iterateAndBreak = async (t, subprocess) => {47+const 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 };54 52-test('Breaking in subprocess.getEachMessage() disconnects', async t => {55+test('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 });61 59-test('Breaking from subprocess.getEachMessage() awaits the subprocess', async t => {62+test('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);65 66 const {ipcOutput, stdout} = await subprocess;64- t.deepEqual(ipcOutput, [foobarString]);65- t.is(stdout, '.');67+ assert.deepEqual(ipcOutput, [foobarString]);68+ assert.equal(stdout, '.');69 });70 68-test('Breaking from exports.getEachMessage() disconnects', async t => {71+test('Breaking from exports.getEachMessage() disconnects', async () => {72 const subprocess = execa('ipc-iterate-break.js', {ipc: true});73 71- 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'));78 79 const {ipcOutput} = await subprocess;77- t.deepEqual(ipcOutput, [foobarString]);80+ assert.deepEqual(ipcOutput, [foobarString]);81 });82 80-const iterateAndThrow = async (t, subprocess, cause) => {83+const 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 };90 88-test('Throwing from subprocess.getEachMessage() disconnects', async t => {91+test('Throwing from subprocess.getEachMessage() disconnects', async () => {92 const subprocess = execa('ipc-iterate-send.js', {ipc: true});93 94 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);96 97 const {ipcOutput} = await subprocess;95- t.deepEqual(ipcOutput, [foobarString]);98+ assert.deepEqual(ipcOutput, [foobarString]);99 });100 98-test('Throwing from subprocess.getEachMessage() awaits the subprocess', async t => {101+test('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);105 106 const {ipcOutput, stdout} = await subprocess;104- t.deepEqual(ipcOutput, [foobarString]);105- t.is(stdout, '.');107+ assert.deepEqual(ipcOutput, [foobarString]);108+ assert.equal(stdout, '.');109 });110 108-test('Throwing from exports.getEachMessage() disconnects', async t => {111+test('Throwing from exports.getEachMessage() disconnects', async () => {112 const subprocess = execa('ipc-iterate-throw.js', {ipc: true});113 111- 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'));118 116- 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 });125 123-test.serial('Can send many messages at once with exports.getEachMessage()', async t => {126+test('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);130 131 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 });134 132-test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', async t => {135+test('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)));139 140 const {stdout} = await subprocess;141 const expectedOutput = indexes.join('\n');139- t.is(stdout, expectedOutput);142+ assert.equal(stdout, expectedOutput);143 });144 142-test('Disconnecting in the current process stops exports.getEachMessage()', async t => {145+test('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();150 151 const {stdout} = await subprocess;149- t.is(stdout, '.');152+ assert.equal(stdout, '.');153 });154 152-test('Disconnecting in the subprocess stops subprocess.getEachMessage()', async t => {155+test('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 }160 161 const {ipcOutput} = await subprocess;159- t.deepEqual(ipcOutput, [foobarString]);162+ assert.deepEqual(ipcOutput, [foobarString]);163 });164 162-test('Exiting the subprocess stops subprocess.getEachMessage()', async t => {165+test('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 }170 171 const {ipcOutput} = await subprocess;169- t.deepEqual(ipcOutput, [foobarString]);172+ assert.deepEqual(ipcOutput, [foobarString]);173 });174 172-const testCleanupListeners = async (t, buffer) => {175+const testCleanupListeners = async buffer => {176 const subprocess = execa('ipc-send.js', {ipc: true, buffer});177 175- 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);180 181 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]);185 183- 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 };189 187-test('Cleans up subprocess.getEachMessage() listeners, buffer false', testCleanupListeners, false);188-test('Cleans up subprocess.getEachMessage() listeners, buffer true', testCleanupListeners, true);190+test('Cleans up subprocess.getEachMessage() listeners, buffer false', () => testCleanupListeners(false));191+test('Cleans up subprocess.getEachMessage() listeners, buffer true', () => testCleanupListeners(true));192 193 const sendContinuousMessages = async subprocess => {194 while (subprocess.nodeChildProcess.connected) {195 for (let index = 0; index < 10; index += 1) {4 unmodified lines200 await scheduler.yield();201 }202 };203 201-test.serial('Handles buffered messages when disconnecting', async t => {204+test('Handles buffered messages when disconnecting', async () => {205 const subprocess = execa('ipc-send-fail.js', {ipc: true, buffer: false});206 207 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);211 209- 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 });217+218+/* eslint-enable node-test/no-conditional-assertion */modified:test/ipc/get-one.js+59 added-57 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString, foobarArray} from '../helpers/input.js';7 import {isAlwaysTrue} from '../helpers/ipc.js';8 import {PARALLEL_COUNT} from '../helpers/parallel.js';9 10 setFixtureDirectory();11 10-test('subprocess.getOneMessage() can filter messages', async t => {12+test('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]);16 17 const {ipcOutput} = await subprocess;16- t.deepEqual(ipcOutput, foobarArray);18+ assert.deepEqual(ipcOutput, foobarArray);19 });20 19-test('exports.getOneMessage() can filter messages', async t => {21+test('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]);25 26 const {ipcOutput} = await subprocess;25- t.deepEqual(ipcOutput, [foobarArray[1]]);27+ assert.deepEqual(ipcOutput, [foobarArray[1]]);28 });29 28-test('Throwing from subprocess.getOneMessage() filter disconnects', async t => {30+test('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);38 37- 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 });45 44-test('Throwing from exports.getOneMessage() filter disconnects', async t => {46+test('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 });51 50- 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 });58 57-test.serial('Can retrieve initial IPC messages under heavy load', async t => {59+test('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 });66 65-const testTwice = async (t, buffer, filter) => {67+const 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 };75 74-test('subprocess.getOneMessage() can be called twice at the same time, buffer false', testTwice, false, undefined);75-test('subprocess.getOneMessage() can be called twice at the same time, buffer true', testTwice, true, undefined);76-test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', testTwice, false, isAlwaysTrue);77-test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', testTwice, true, isAlwaysTrue);76+test('subprocess.getOneMessage() can be called twice at the same time, buffer false', () => testTwice(false, undefined));77+test('subprocess.getOneMessage() can be called twice at the same time, buffer true', () => testTwice(true, undefined));78+test('subprocess.getOneMessage() can be called twice at the same time, buffer false, filter', () => testTwice(false, isAlwaysTrue));79+test('subprocess.getOneMessage() can be called twice at the same time, buffer true, filter', () => testTwice(true, isAlwaysTrue));80 79-const testCleanupListeners = async (t, buffer, filter) => {81+const testCleanupListeners = async (buffer, filter) => {82 const subprocess = execa('ipc-send.js', {ipc: true, buffer});83 82- 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);86 87 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);90 89- t.is(await promise, foobarString);91+ assert.equal(await promise, foobarString);92 await subprocess;93 92- 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 };97 96-test('Cleans up subprocess.getOneMessage() listeners, buffer false', testCleanupListeners, false, undefined);97-test('Cleans up subprocess.getOneMessage() listeners, buffer true', testCleanupListeners, true, undefined);98-test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', testCleanupListeners, false, isAlwaysTrue);99-test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', testCleanupListeners, true, isAlwaysTrue);98+test('Cleans up subprocess.getOneMessage() listeners, buffer false', () => testCleanupListeners(false, undefined));99+test('Cleans up subprocess.getOneMessage() listeners, buffer true', () => testCleanupListeners(true, undefined));100+test('Cleans up subprocess.getOneMessage() listeners, buffer false, filter', () => testCleanupListeners(false, isAlwaysTrue));101+test('Cleans up subprocess.getOneMessage() listeners, buffer true, filter', () => testCleanupListeners(true, isAlwaysTrue));102 101-const testParentDisconnect = async (t, buffer, filter) => {103+const 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);107 108 subprocess.nodeChildProcess.disconnect();109 108- 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 };117 116-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', testParentDisconnect, false, false);117-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', testParentDisconnect, true, false);118-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', testParentDisconnect, false, true);119-test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', testParentDisconnect, true, false);118+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false', () => testParentDisconnect(false, false));119+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true', () => testParentDisconnect(true, false));120+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer false, filter', () => testParentDisconnect(false, true));121+test('subprocess.disconnect() interrupts exports.getOneMessage(), buffer true, filter', () => testParentDisconnect(true, false));122 121-const testSubprocessDisconnect = async (t, buffer, filter) => {123+const 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 };129 128-test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', testSubprocessDisconnect, false, undefined);129-test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', testSubprocessDisconnect, true, undefined);130-test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', testSubprocessDisconnect, false, isAlwaysTrue);131-test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', testSubprocessDisconnect, true, isAlwaysTrue);130+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false', () => testSubprocessDisconnect(false, undefined));131+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true', () => testSubprocessDisconnect(true, undefined));132+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer false, filter', () => testSubprocessDisconnect(false, isAlwaysTrue));133+test('Subprocess exit interrupts subprocess.getOneMessage(), buffer true, filter', () => testSubprocessDisconnect(true, isAlwaysTrue));modified:test/ipc/graceful.js+127 added-125 removed
1+import assert from 'node:assert/strict';2 import {getEventListeners} from 'node:events';3 import {setTimeout} from 'node:timers/promises';3-import test from 'ava';4+import test from 'node:test';5+import {assertRejects} from '../helpers/assert.js';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {foobarString} from '../helpers/input.js';9 10 setFixtureDirectory();11 10-test('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]);12+test('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 });20 19-test('Graceful cancelSignal can be aborted', async t => {21+test('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 });33 32-test('Graceful cancelSignal can be never aborted', async t => {34+test('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 });40 39-test('Graceful cancelSignal can be already aborted but not used', async t => {41+test('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 });53 52-test('Graceful cancelSignal can be aborted but not used', async t => {54+test('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 });68 67-test('Graceful cancelSignal can be never aborted nor used', async t => {69+test('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 });76 75-test('Graceful cancelSignal can be aborted twice', async t => {77+test('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 });90 89-test('Graceful cancelSignal cannot be manually aborted after disconnection', async t => {91+test('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 });104 103-test('Graceful cancelSignal can disconnect after being manually aborted', async t => {105+test('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 });118 117-test('Graceful cancelSignal is automatically aborted on disconnection', async t => {119+test('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 });130 129-test('getCancelSignal() aborts if already disconnected', async t => {131+test('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 });141 140-test('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`.'));142+test('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 });151 150-test('getCancelSignal() fails on every call if no IPC', async t => {152+test('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 });157 156-test.serial('getCancelSignal() hangs if cancelSignal without gracefulCancel', async t => {158+test('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 });167 166-test('Subprocess cancelSignal does not keep subprocess alive', async t => {168+test('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 });173 172-test('Subprocess can send a message right away', async t => {174+test('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 });179 178-test('Subprocess can receive a message right away', async t => {180+test('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 });185 184-test('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]);186+test('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 });194 193-test('Graceful cancelSignal can use cancelSignal.onabort', async t => {195+test('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 });207 206-test('Graceful cancelSignal abort reason cannot be directly received', async t => {208+test('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 });219 218-test('error.isGracefullyCanceled is always false with execaSync()', t => {220+test('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 });225 226 // 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.226-test('Subprocess messages with the internal graceful cancellation shape are kept', async t => {228+test('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 });232 231-test('Graceful cancelSignal is not aborted by the subprocess\' own subprocess', async t => {233+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {foobarString} from '../helpers/input.js';6 import {isAlwaysTrue} from '../helpers/ipc.js';7 import {PARALLEL_COUNT} from '../helpers/parallel.js';8 9 setFixtureDirectory();10 10-const testSeriesParent = async (t, buffer, filter) => {11+const testSeriesParent = async (buffer, filter) => {12 const subprocess = execa('ipc-send-many.js', [`${PARALLEL_COUNT}`], {ipc: true, buffer});13 14 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 }18 19 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 };24 24-test('subprocess.getOneMessage() can be called multiple times in a row, buffer false', testSeriesParent, false, undefined);25-test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', testSeriesParent, true, undefined);26-test('subprocess.getOneMessage() can be called multiple times in a row, buffer false, filter', testSeriesParent, false, isAlwaysTrue);27-test('subprocess.getOneMessage() can be called multiple times in a row, buffer true, filter', testSeriesParent, true, isAlwaysTrue);25+test('subprocess.getOneMessage() can be called multiple times in a row, buffer false', () => testSeriesParent(false, undefined));26+test('subprocess.getOneMessage() can be called multiple times in a row, buffer true', () => testSeriesParent(true, undefined));27+test('subprocess.getOneMessage() can be called multiple times in a row, buffer false, filter', () => testSeriesParent(false, isAlwaysTrue));28+test('subprocess.getOneMessage() can be called multiple times in a row, buffer true, filter', () => testSeriesParent(true, isAlwaysTrue));29 29-const testSeriesSubprocess = async (t, filter) => {30+const 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)));34 35 const {stdout} = await subprocess;36 const expectedOutput = indexes.join('\n');36- t.is(stdout, expectedOutput);37+ assert.equal(stdout, expectedOutput);38 };39 39-test('exports.getOneMessage() can be called multiple times in a row', testSeriesSubprocess, false);40-test('exports.getOneMessage() can be called multiple times in a row, filter', testSeriesSubprocess, true);40+test('exports.getOneMessage() can be called multiple times in a row', () => testSeriesSubprocess(false));41+test('exports.getOneMessage() can be called multiple times in a row, filter', () => testSeriesSubprocess(true));42 42-test('Can iterate multiple times over IPC messages in subprocess', async t => {43+test('Can iterate multiple times over IPC messages in subprocess', async () => {44 const subprocess = execa('ipc-iterate-twice.js', {ipc: true});45 45- 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);54 55 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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows, assertRejects} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString} from '../helpers/input.js';7 8 setFixtureDirectory();9 8-const testSuccess = async (t, options) => {10+const 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 };14 13-test('Sends a message with the "ipcInput" option, ipc undefined', testSuccess, {});14-test('Sends a message with the "ipcInput" option, ipc true', testSuccess, {ipc: true});15+test('Sends a message with the "ipcInput" option, ipc undefined', () => testSuccess({}));16+test('Sends a message with the "ipcInput" option, ipc true', () => testSuccess({ipc: true}));17 16-test('Cannot use the "ipcInput" option with "ipc" false', t => {17- t.throws(() => {18+test('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 });23 24 // Any value can be sent over IPC, including falsy ones, so those must be reported as `ipcInput`, not as `ipc`23-const testInvalidSyncIpcInput = (t, ipcInput) => {24- t.throws(() => {25+const testInvalidSyncIpcInput = ipcInput => {26+ assertThrows(() => {27 execaSync('empty.js', {ipcInput});28 }, {message: /The "ipcInput" option cannot be used with synchronous/});29 };30 29-test('Cannot use the "ipcInput" option with execaSync()', testInvalidSyncIpcInput, foobarString);30-test('Cannot use the "ipcInput" option with execaSync(), 0', testInvalidSyncIpcInput, 0);31-test('Cannot use the "ipcInput" option with execaSync(), empty string', testInvalidSyncIpcInput, '');32-test('Cannot use the "ipcInput" option with execaSync(), false', testInvalidSyncIpcInput, false);33-test('Cannot use the "ipcInput" option with execaSync(), null', testInvalidSyncIpcInput, null);31+test('Cannot use the "ipcInput" option with execaSync()', () => testInvalidSyncIpcInput(foobarString));32+test('Cannot use the "ipcInput" option with execaSync(), 0', () => testInvalidSyncIpcInput(0));33+test('Cannot use the "ipcInput" option with execaSync(), empty string', () => testInvalidSyncIpcInput(''));34+test('Cannot use the "ipcInput" option with execaSync(), false', () => testInvalidSyncIpcInput(false));35+test('Cannot use the "ipcInput" option with execaSync(), null', () => testInvalidSyncIpcInput(null));36 35-test('Invalid "ipcInput" option v8 format', t => {36- const {message, cause} = t.throws(() => {37+test('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 });44 43-test('Invalid "ipcInput" option JSON format', t => {44- const {message, cause} = t.throws(() => {45+test('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 });52 53 // `JSON.stringify()` returns `undefined`, instead of throwing, for values it cannot represent52-const testUnrepresentableJson = (t, ipcInput) => {53- const {message} = t.throws(() => {54+const 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 };60 59-test('Invalid "ipcInput" option JSON format, function', testUnrepresentableJson, () => {});60-test('Invalid "ipcInput" option JSON format, symbol', testUnrepresentableJson, Symbol('test'));61+test('Invalid "ipcInput" option JSON format, function', () => testUnrepresentableJson(() => {}));62+test('Invalid "ipcInput" option JSON format, symbol', () => testUnrepresentableJson(Symbol('test')));63 64 // 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.64-const testInvalidSerialization = async (t, serialization) => {65- const {code} = await t.throwsAsync(execa('empty.js', {ipcInput: foobarString, serialization}));66- t.is(code, 'ERR_INVALID_ARG_VALUE');66+const testInvalidSerialization = async serialization => {67+ const {code} = await assertRejects(execa('empty.js', {ipcInput: foobarString, serialization}));68+ assert.equal(code, 'ERR_INVALID_ARG_VALUE');69 };70 69-test('Invalid "serialization" option with the "ipcInput" option', testInvalidSerialization, 'invalid');70-test('Invalid "serialization" option with the "ipcInput" option, __proto__', testInvalidSerialization, '__proto__');71-test('Invalid "serialization" option with the "ipcInput" option, toString', testInvalidSerialization, 'toString');72-test('Invalid "serialization" option with the "ipcInput" option, constructor', testInvalidSerialization, 'constructor');71+test('Invalid "serialization" option with the "ipcInput" option', () => testInvalidSerialization('invalid'));72+test('Invalid "serialization" option with the "ipcInput" option, __proto__', () => testInvalidSerialization('__proto__'));73+test('Invalid "serialization" option with the "ipcInput" option, toString', () => testInvalidSerialization('toString'));74+test('Invalid "serialization" option with the "ipcInput" option, constructor', () => testInvalidSerialization('constructor'));75 74-test('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'));76+test('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 });81 80-test.serial('Can use "ipcInput" option even if the subprocess is not listening to messages', async t => {82+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {foobarString} from '../helpers/input.js';6 import {isAlwaysTrue, subprocessGetOne, subprocessGetFirst} from '../helpers/ipc.js';7 import {PARALLEL_COUNT} from '../helpers/parallel.js';8 9 setFixtureDirectory();10 10-const testSendHoldParent = async (t, getMessage, buffer, filter) => {11+const testSendHoldParent = async (getMessage, buffer, filter) => {12 const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});13 14 await subprocess.sendMessage(0);14- t.is(await subprocess.getOneMessage({filter}), 0);15+ assert.equal(await subprocess.getOneMessage({filter}), 0);16 17 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}), '.');24 25 const {ipcOutput} = await subprocess;25- if (buffer) {26- const expectedOutput = [0, '.', ...messages];27- t.deepEqual(ipcOutput, expectedOutput);26+ if (!buffer) {27+ return;28 }29+30+ const expectedOutput = [0, '.', ...messages];31+ assert.deepEqual(ipcOutput, expectedOutput);32 };33 31-test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', testSendHoldParent, subprocessGetOne, false, undefined);32-test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', testSendHoldParent, subprocessGetOne, true, undefined);33-test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', testSendHoldParent, subprocessGetOne, false, isAlwaysTrue);34-test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', testSendHoldParent, subprocessGetOne, true, isAlwaysTrue);35-test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParent, subprocessGetFirst, false, undefined);36-test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParent, subprocessGetFirst, true, undefined);34+test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', () => testSendHoldParent(subprocessGetOne, false, undefined));35+test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', () => testSendHoldParent(subprocessGetOne, true, undefined));36+test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', () => testSendHoldParent(subprocessGetOne, false, isAlwaysTrue));37+test('Multiple parallel subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', () => testSendHoldParent(subprocessGetOne, true, isAlwaysTrue));38+test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', () => testSendHoldParent(subprocessGetFirst, false, undefined));39+test('Multiple parallel subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', () => testSendHoldParent(subprocessGetFirst, true, undefined));40 38-const testSendHoldSubprocess = async (t, filter, isGetEach) => {41+const 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 };46 44-test('Multiple parallel exports.sendMessage() + exports.getOneMessage()', testSendHoldSubprocess, false, false);45-test('Multiple parallel exports.sendMessage() + exports.getOneMessage(), filter', testSendHoldSubprocess, true, false);46-test('Multiple parallel exports.sendMessage() + exports.getEachMessage()', testSendHoldSubprocess, false, true);47+test('Multiple parallel exports.sendMessage() + exports.getOneMessage()', () => testSendHoldSubprocess(false, false));48+test('Multiple parallel exports.sendMessage() + exports.getOneMessage(), filter', () => testSendHoldSubprocess(true, false));49+test('Multiple parallel exports.sendMessage() + exports.getEachMessage()', () => testSendHoldSubprocess(false, true));50 48-const testSendHoldParentSerial = async (t, getMessage, buffer, filter) => {51+const testSendHoldParentSerial = async (getMessage, buffer, filter) => {52 const subprocess = execa('ipc-iterate.js', {ipc: true, buffer});53 54 await subprocess.sendMessage(0);52- t.is(await subprocess.getOneMessage({filter}), 0);55+ assert.equal(await subprocess.getOneMessage({filter}), 0);56 57 const promise = subprocess.sendMessage(1);58 subprocess.nodeChildProcess.emit('message', '.');59 await promise;6 unmodified lines66 67 await subprocess.sendMessage(foobarString);68 69 const {ipcOutput} = await subprocess;67- if (buffer) {68- const expectedOutput = [0, '.', 1, ...messages];69- t.deepEqual(ipcOutput, expectedOutput);70+ if (!buffer) {71+ return;72 }73+74+ const expectedOutput = [0, '.', 1, ...messages];75+ assert.deepEqual(ipcOutput, expectedOutput);76 };77 73-test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', testSendHoldParentSerial, subprocessGetOne, false, undefined);74-test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', testSendHoldParentSerial, subprocessGetOne, true, undefined);75-test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', testSendHoldParentSerial, subprocessGetOne, false, isAlwaysTrue);76-test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', testSendHoldParentSerial, subprocessGetOne, true, isAlwaysTrue);77-test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', testSendHoldParentSerial, subprocessGetFirst, false, undefined);78-test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', testSendHoldParentSerial, subprocessGetFirst, true, undefined);78+test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false', () => testSendHoldParentSerial(subprocessGetOne, false, undefined));79+test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true', () => testSendHoldParentSerial(subprocessGetOne, true, undefined));80+test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer false, filter', () => testSendHoldParentSerial(subprocessGetOne, false, isAlwaysTrue));81+test('Multiple serial subprocess.sendMessage() + subprocess.getOneMessage(), buffer true, filter', () => testSendHoldParentSerial(subprocessGetOne, true, isAlwaysTrue));82+test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer false', () => testSendHoldParentSerial(subprocessGetFirst, false, undefined));83+test('Multiple serial subprocess.sendMessage() + subprocess.getEachMessage(), buffer true', () => testSendHoldParentSerial(subprocessGetFirst, true, undefined));84 80-const testSendHoldSubprocessSerial = async (t, filter, isGetEach) => {85+const 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 };90 86-test('Multiple serial exports.sendMessage() + exports.getOneMessage()', testSendHoldSubprocessSerial, false, false);87-test('Multiple serial exports.sendMessage() + exports.getOneMessage(), filter', testSendHoldSubprocessSerial, true, false);88-test('Multiple serial exports.sendMessage() + exports.getEachMessage()', testSendHoldSubprocessSerial, false, true);91+test('Multiple serial exports.sendMessage() + exports.getOneMessage()', () => testSendHoldSubprocessSerial(false, false));92+test('Multiple serial exports.sendMessage() + exports.getOneMessage(), filter', () => testSendHoldSubprocessSerial(true, false));93+test('Multiple serial exports.sendMessage() + exports.getEachMessage()', () => testSendHoldSubprocessSerial(false, true));modified:test/ipc/pending.js+36 added-35 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {setTimeout} from 'node:timers/promises';3-import test from 'ava';4+import test from 'node:test';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {foobarString} from '../helpers/input.js';8 9 setFixtureDirectory();10 10-const testBufferInitial = async (t, buffer) => {11+const 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);14 15 const {ipcOutput} = await subprocess;15- t.deepEqual(ipcOutput, buffer ? [foobarString] : []);16+ assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);17 };18 18-test('Buffers initial message to subprocess, buffer false', testBufferInitial, false);19-test('Buffers initial message to subprocess, buffer true', testBufferInitial, true);19+test('Buffers initial message to subprocess, buffer false', () => testBufferInitial(false));20+test('Buffers initial message to subprocess, buffer true', () => testBufferInitial(true));21 21-const testBufferInitialSend = async (t, buffer) => {22+const 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);26 27 const {ipcOutput} = await subprocess;27- t.deepEqual(ipcOutput, buffer ? ['.', foobarString] : []);28+ assert.deepEqual(ipcOutput, buffer ? ['.', foobarString] : []);29 };30 30-test('sendMessage() does not empty the initial message buffering, buffer false', testBufferInitialSend, false);31-test('sendMessage() does not empty the initial message buffering, buffer true', testBufferInitialSend, true);31+test('sendMessage() does not empty the initial message buffering, buffer false', () => testBufferInitialSend(false));32+test('sendMessage() does not empty the initial message buffering, buffer true', () => testBufferInitialSend(true));33 33-const testBufferInitialStrict = async (t, buffer) => {34+const 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, '..');41 42 const {ipcOutput} = await subprocess;42- t.deepEqual(ipcOutput, buffer ? ['.', '..'] : []);43+ assert.deepEqual(ipcOutput, buffer ? ['.', '..'] : []);44 };45 45-test('sendMessage() with "strict" empties the initial message buffering, buffer false', testBufferInitialStrict, false);46-test('sendMessage() with "strict" empties the initial message buffering, buffer true', testBufferInitialStrict, true);46+test('sendMessage() with "strict" empties the initial message buffering, buffer false', () => testBufferInitialStrict(false));47+test('sendMessage() with "strict" empties the initial message buffering, buffer true', () => testBufferInitialStrict(true));48 48-const testNoBufferInitial = async (t, buffer) => {49+const 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('.');56 57 const {ipcOutput} = await subprocess;57- t.deepEqual(ipcOutput, buffer ? [foobarString] : []);58+ assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);59 };60 60-test.serial('Does not buffer initial message to current process, buffer false', testNoBufferInitial, false);61-test.serial('Does not buffer initial message to current process, buffer true', testNoBufferInitial, true);61+test('Does not buffer initial message to current process, buffer false', () => testNoBufferInitial(false));62+test('Does not buffer initial message to current process, buffer true', () => testNoBufferInitial(true));63 63-const testReplay = async (t, buffer) => {64+const 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);71 72 const {ipcOutput} = await subprocess;72- t.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);73+ assert.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);74 };75 75-test.serial('Does not replay missed messages in subprocess, buffer false', testReplay, false);76-test.serial('Does not replay missed messages in subprocess, buffer true', testReplay, true);76+test('Does not replay missed messages in subprocess, buffer false', () => testReplay(false));77+test('Does not replay missed messages in subprocess, buffer true', () => testReplay(true));78 78-const testFastSend = async (t, buffer) => {79+const 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(), '.');82 83 const {ipcOutput} = await subprocess;83- t.deepEqual(ipcOutput, buffer ? ['.'] : []);84+ assert.deepEqual(ipcOutput, buffer ? ['.'] : []);85 };86 86-test('Subprocess can send messages right away, buffer false', testFastSend, false);87-test('Subprocess can send messages right away, buffer true', testFastSend, true);87+test('Subprocess can send messages right away, buffer false', () => testFastSend(false));88+test('Subprocess can send messages right away, buffer true', () => testFastSend(true));modified:test/ipc/reference.js+57 added-54 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString} from '../helpers/input.js';7 import {PARALLEL_COUNT} from '../helpers/parallel.js';8 9 setFixtureDirectory();10 9-const testReference = async (t, fixtureName) => {10- const {timedOut} = await t.throwsAsync(execa(fixtureName, {ipc: true, timeout: 1e3}));11- t.true(timedOut);11+const testReference = async fixtureName => {12+ const {timedOut} = await assertRejects(execa(fixtureName, {ipc: true, timeout: 1e3}));13+ assert.equal(timedOut, true);14 };15 14-test('exports.getOneMessage() keeps the subprocess alive', testReference, 'ipc-get-ref.js');15-test('exports.getEachMessage() keeps the subprocess alive', testReference, 'ipc-iterate-ref.js');16+test('exports.getOneMessage() keeps the subprocess alive', () => testReference('ipc-get-ref.js'));17+test('exports.getEachMessage() keeps the subprocess alive', () => testReference('ipc-iterate-ref.js'));18 17-const testUnreference = async (t, fixtureName) => {19+const testUnreference = async fixtureName => {20 const {ipcOutput} = await execa(fixtureName, {ipc: true});19- t.deepEqual(ipcOutput, []);21+ assert.deepEqual(ipcOutput, []);22 };23 22-test('exports.getOneMessage() does not keep the subprocess alive, reference false', testUnreference, 'ipc-get-unref.js');23-test('exports.getEachMessage() does not keep the subprocess alive, reference false', testUnreference, 'ipc-iterate-unref.js');24+test('exports.getOneMessage() does not keep the subprocess alive, reference false', () => testUnreference('ipc-get-unref.js'));25+test('exports.getEachMessage() does not keep the subprocess alive, reference false', () => testUnreference('ipc-iterate-unref.js'));26 25-test('exports.sendMessage() keeps the subprocess alive', async t => {27+test('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 });32 31-test('process.send() keeps the subprocess alive', async t => {33+test('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 });38 37-test('process.send() keeps the subprocess alive, after getOneMessage()', async t => {39+test('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 });44 43-test('process.send() keeps the subprocess alive, after sendMessage()', async t => {45+test('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 });50 49-test('process.once("message") keeps the subprocess alive', async t => {51+test('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);55 56 const {ipcOutput, stdout} = await subprocess;55- t.deepEqual(ipcOutput, ['.']);56- t.is(stdout, foobarString);57+ assert.deepEqual(ipcOutput, ['.']);58+ assert.equal(stdout, foobarString);59 });60 59-test('process.once("message") keeps the subprocess alive, after sendMessage()', async t => {61+test('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);65 66 const {ipcOutput, stdout} = await subprocess;65- t.deepEqual(ipcOutput, ['.']);66- t.is(stdout, foobarString);67+ assert.deepEqual(ipcOutput, ['.']);68+ assert.equal(stdout, foobarString);69 });70 69-test('process.once("message") keeps the subprocess alive, after getOneMessage()', async t => {71+test('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);76 77 const {ipcOutput, stdout} = await subprocess;76- t.deepEqual(ipcOutput, ['.']);77- t.is(stdout, foobarString);78+ assert.deepEqual(ipcOutput, ['.']);79+ assert.equal(stdout, foobarString);80 });81 80-test('process.once("disconnect") keeps the subprocess alive', async t => {82+test('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();86 87 const {ipcOutput, stdout} = await subprocess;86- t.deepEqual(ipcOutput, ['.']);87- t.is(stdout, '.');88+ assert.deepEqual(ipcOutput, ['.']);89+ assert.equal(stdout, '.');90 });91 90-test('process.once("disconnect") keeps the subprocess alive, after sendMessage()', async t => {92+test('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();98 99 const {ipcOutput, stdout} = await subprocess;97- t.deepEqual(ipcOutput, ['.', '.']);98- t.is(stdout, '.');100+ assert.deepEqual(ipcOutput, ['.', '.']);101+ assert.equal(stdout, '.');102 });103 101-test('process.once("disconnect") does not keep the subprocess alive, after getOneMessage()', async t => {104+test('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();109 110 const {ipcOutput, stdout} = await subprocess;108- t.deepEqual(ipcOutput, ['.']);109- t.is(stdout, '.');111+ assert.deepEqual(ipcOutput, ['.']);112+ assert.equal(stdout, '.');113 });114 112-test('Can call subprocess.disconnect() right away', async t => {115+test('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);119 117- 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 });127 125-test('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'));128+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString} from '../helpers/input.js';7 import {PARALLEL_COUNT} from '../helpers/parallel.js';8 import {mockSendIoError} from '../helpers/ipc.js';9 10 setFixtureDirectory();11 10-test('Can exchange IPC messages', async t => {12+test('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 });18 17-test.serial('Can exchange IPC messages under heavy load', async t => {19+test('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 });27 26-test('The "serialization" option defaults to "advanced"', async t => {28+test('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 });35 34-test('Can use "serialization: json" option', async t => {36+test('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 });43 42-test('Validates JSON payload with serialization: "json"', async t => {44+test('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 });49 50 const BIG_PAYLOAD_SIZE = '.'.repeat(1e6);51 50-test('Handles backpressure', async t => {52+test('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 });60 59-test('Disconnects IPC on exports.sendMessage() error', async t => {61+test('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);65 64- 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'));69 68- 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 });75 74-test('Disconnects IPC on subprocess.sendMessage() error', async t => {76+test('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'));80 79- 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 });87 88 // EPIPE happens based on timing conditions, so we must repeat it until it happens87-const findEpipeError = async t => {89+const 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 lines104 await subprocess.sendMessage('.');105 }106 };107 106-test.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.');108+test('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 });112 111-test('subprocess.sendMessage() handles I/O errors', async t => {113+test('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);117 116- 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 });124 123-test('Does not hold message events on I/O errors', async t => {125+test('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);131 130- 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 });138 137-test('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, []);139+test('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
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';2-import test from 'ava';3+import {setTimeout} from 'node:timers/promises';4+import test from 'node:test';5+import {assertRejects} from '../helpers/assert.js';6 import {execa} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {foobarString} from '../helpers/input.js';9 import {assertMaxListeners} from '../helpers/listeners.js';1 unmodified line11 import {PARALLEL_COUNT} from '../helpers/parallel.js';12 13 setFixtureDirectory();14 12-const testStrictSuccessParentOne = async (t, buffer) => {15+const 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);19 20 const {ipcOutput} = await subprocess;18- t.deepEqual(ipcOutput, buffer ? [foobarString] : []);21+ assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);22 };23 21-test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer false', testStrictSuccessParentOne, false);22-test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer true', testStrictSuccessParentOne, true);24+test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer false', () => testStrictSuccessParentOne(false));25+test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getOneMessage(), buffer true', () => testStrictSuccessParentOne(true));26 24-const testStrictSuccessParentEach = async (t, buffer) => {27+const 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);32 33 const {ipcOutput} = await subprocess;31- t.deepEqual(ipcOutput, buffer ? ['.'] : []);34+ assert.deepEqual(ipcOutput, buffer ? ['.'] : []);35 };36 34-test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer false', testStrictSuccessParentEach, false);35-test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer true', testStrictSuccessParentEach, true);37+test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer false', () => testStrictSuccessParentEach(false));38+test('subprocess.sendMessage() "strict" succeeds if the subprocess uses exports.getEachMessage(), buffer true', () => testStrictSuccessParentEach(true));39 37-const testStrictMissingParent = async (t, buffer) => {40+const 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;48 49 const {ipcOutput} = await subprocess;47- t.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);50+ assert.deepEqual(ipcOutput, buffer ? [foobarString, foobarString] : []);51 };52 50-test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer false', testStrictMissingParent, false);51-test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer true', testStrictMissingParent, true);53+test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer false', () => testStrictMissingParent(false));54+test('subprocess.sendMessage() "strict" fails if the subprocess is not listening, buffer true', () => testStrictMissingParent(true));55 53-const testStrictExit = async (t, buffer) => {56+const 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.');60 61 const {ipcOutput} = await subprocess;59- t.deepEqual(ipcOutput, buffer ? [foobarString] : []);62+ assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);63 };64 62-test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer false', testStrictExit, false);63-test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer true', testStrictExit, true);65+test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer false', () => testStrictExit(false));66+test('subprocess.sendMessage() "strict" fails if the subprocess exits, buffer true', () => testStrictExit(true));67 65-const testStrictSuccessSubprocess = async (t, getMessage, buffer) => {68+const 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);71 72 const {ipcOutput} = await subprocess;70- t.deepEqual(ipcOutput, buffer ? [foobarString] : []);73+ assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);74 };75 73-test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer false', testStrictSuccessSubprocess, subprocessGetOne, false);74-test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer true', testStrictSuccessSubprocess, subprocessGetOne, true);75-test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer false', testStrictSuccessSubprocess, subprocessGetFirst, false);76-test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer true', testStrictSuccessSubprocess, subprocessGetFirst, true);76+test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer false', () => testStrictSuccessSubprocess(subprocessGetOne, false));77+test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getOneMessage(), buffer true', () => testStrictSuccessSubprocess(subprocessGetOne, true));78+test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer false', () => testStrictSuccessSubprocess(subprocessGetFirst, false));79+test('exports.sendMessage() "strict" succeeds if the current process uses subprocess.getEachMessage(), buffer true', () => testStrictSuccessSubprocess(subprocessGetFirst, true));80 78-test('exports.sendMessage() "strict" succeeds if the current process uses result.ipcOutput', async t => {81+test('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 });85 83-test('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, []);86+test('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 });93 91-test.serial('Multiple subprocess.sendMessage() "strict" at once', async t => {92- const checkMaxListeners = assertMaxListeners(t);94+test('Multiple subprocess.sendMessage() "strict" at once', async () => {95+ const checkMaxListeners = assertMaxListeners();96 97 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);101 102 const {ipcOutput} = await subprocess;100- t.deepEqual(ipcOutput, messages);103+ assert.deepEqual(ipcOutput, messages);104 105 checkMaxListeners();106 });107 105-test('subprocess.sendMessage() "strict" fails if the subprocess uses once()', async t => {108+test('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.');112 113 const {ipcOutput} = await subprocess;111- t.deepEqual(ipcOutput, ['.']);114+ assert.deepEqual(ipcOutput, ['.']);115 });116 114-test('exports.sendMessage() "strict" fails if the current process uses once() and buffer false', async t => {117+test('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 });126 124- 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 });133 131-test('subprocess.sendMessage() "strict" failure disconnects', async t => {134+test('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;142 140- 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 });149 147-test('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, []);150+test('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 });157 155-const testIoErrorParent = async (t, getMessage) => {158+const 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);164 162- 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 };171 169-test('subprocess.getOneMessage() acknowledgment I/O error', testIoErrorParent, subprocessGetOne);170-test('subprocess.getEachMessage() acknowledgment I/O error', testIoErrorParent, subprocessGetFirst);172+test('subprocess.getOneMessage() acknowledgment I/O error', () => testIoErrorParent(subprocessGetOne));173+test('subprocess.getEachMessage() acknowledgment I/O error', () => testIoErrorParent(subprocessGetFirst));174 172-const testIoErrorSubprocess = async (t, fixtureName) => {175+const 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.');179 177- 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 };188 186-test('exports.getOneMessage() acknowledgment I/O error', testIoErrorSubprocess, 'ipc-get-io-error.js');187-test('exports.getEachMessage() acknowledgment I/O error', testIoErrorSubprocess, 'ipc-iterate-io-error.js');189+test('exports.getOneMessage() acknowledgment I/O error', () => testIoErrorSubprocess('ipc-get-io-error.js'));190+test('exports.getEachMessage() acknowledgment I/O error', () => testIoErrorSubprocess('ipc-iterate-io-error.js'));191 189-test('Opposite sendMessage() "strict", buffer true', async t => {192+test('Opposite sendMessage() "strict", buffer true', async () => {193 const subprocess = execa('ipc-send-strict-get.js', {ipc: true});194 await subprocess.sendMessage(foobarString, {strict: true});195 196 const {ipcOutput} = await subprocess;194- t.deepEqual(ipcOutput, [foobarString, foobarString]);197+ assert.deepEqual(ipcOutput, [foobarString, foobarString]);198 });199 197-test('Opposite sendMessage() "strict", current process listening, buffer false', async t => {200+test('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);208 209 const {ipcOutput} = await subprocess;207- t.deepEqual(ipcOutput, []);210+ assert.deepEqual(ipcOutput, []);211 });212 210-test('Opposite sendMessage() "strict", subprocess listening, buffer false', async t => {213+test('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);217 218 const {ipcOutput} = await subprocess;216- t.deepEqual(ipcOutput, []);219+ assert.deepEqual(ipcOutput, []);220 });221 219-test('Opposite sendMessage() "strict", not listening, buffer false', async t => {222+test('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.'));226 224- 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 });233 231-test('Ignores "strict" responses with an Object.prototype property as id', async t => {234+test('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 });238 239+// `forever.js` does not use Execa, so it never acknowledges the message240+test('Ignores "strict" responses sent by another subprocess', async () => {241+ const subprocess = execa('forever.js', {ipc: true});242+ const sendPromise = subprocess.sendMessage(foobarString, {strict: true});243+244+ 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+ }251+252+ await Promise.all([assertRejects(sendPromise), assertRejects(subprocess)]);253+});254+236-const testStrictJson = async (t, buffer) => {255+const 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);259 260 const {ipcOutput} = await subprocess;242- t.deepEqual(ipcOutput, buffer ? [foobarString] : []);261+ assert.deepEqual(ipcOutput, buffer ? [foobarString] : []);262 };263 245-test('subprocess.sendMessage() "strict" works with serialization "json", buffer false', testStrictJson, false);246-test('subprocess.sendMessage() "strict" works with serialization "json", buffer true', testStrictJson, true);264+test('subprocess.sendMessage() "strict" works with serialization "json", buffer false', () => testStrictJson(false));265+test('subprocess.sendMessage() "strict" works with serialization "json", buffer true', () => testStrictJson(true));266 248-test('exports.sendMessage() "strict" works with serialization "json"', async t => {267+test('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});270 271 const {ipcOutput} = await subprocess;253- t.deepEqual(ipcOutput, [foobarString, foobarString]);272+ assert.deepEqual(ipcOutput, [foobarString, foobarString]);273 });274 256-test('subprocess.sendMessage() "strict" fails with serialization "json" if the subprocess is not listening', async t => {275+test('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.');279 280 const {ipcOutput} = await subprocess;262- t.deepEqual(ipcOutput, [foobarString]);281+ assert.deepEqual(ipcOutput, [foobarString]);282 });283 284 const noop = () => {};285 286 // 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.270-test('Detects a "strict" deadlock on a later message of the same batch', async t => {289+test('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);293 275- 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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows, assertRejects} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString} from '../helpers/input.js';7 8 setFixtureDirectory();9 8-const testRequiredIpcSubprocess = async (t, methodName, options) => {10+const 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 };16 15-test('Cannot use subprocess.sendMessage() without ipc option', testRequiredIpcSubprocess, 'sendMessage', {});16-test('Cannot use subprocess.sendMessage() with ipc: false', testRequiredIpcSubprocess, 'sendMessage', {ipc: false});17-test('Cannot use subprocess.getOneMessage() without ipc option', testRequiredIpcSubprocess, 'getOneMessage', {});18-test('Cannot use subprocess.getOneMessage() with ipc: false', testRequiredIpcSubprocess, 'getOneMessage', {ipc: false});19-test('Cannot use subprocess.getEachMessage() without ipc option', testRequiredIpcSubprocess, 'getEachMessage', {});20-test('Cannot use subprocess.getEachMessage() with ipc: false', testRequiredIpcSubprocess, 'getEachMessage', {ipc: false});17+test('Cannot use subprocess.sendMessage() without ipc option', () => testRequiredIpcSubprocess('sendMessage', {}));18+test('Cannot use subprocess.sendMessage() with ipc: false', () => testRequiredIpcSubprocess('sendMessage', {ipc: false}));19+test('Cannot use subprocess.getOneMessage() without ipc option', () => testRequiredIpcSubprocess('getOneMessage', {}));20+test('Cannot use subprocess.getOneMessage() with ipc: false', () => testRequiredIpcSubprocess('getOneMessage', {ipc: false}));21+test('Cannot use subprocess.getEachMessage() without ipc option', () => testRequiredIpcSubprocess('getEachMessage', {}));22+test('Cannot use subprocess.getEachMessage() with ipc: false', () => testRequiredIpcSubprocess('getEachMessage', {ipc: false}));23 22-const 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`));24+const 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 };28 27-test('Cannot use exports.sendMessage() without ipc option', testRequiredIpcExports, 'sendMessage', {});28-test('Cannot use exports.sendMessage() with ipc: false', testRequiredIpcExports, 'sendMessage', {ipc: false});29-test('Cannot use exports.getOneMessage() without ipc option', testRequiredIpcExports, 'getOneMessage', {});30-test('Cannot use exports.getOneMessage() with ipc: false', testRequiredIpcExports, 'getOneMessage', {ipc: false});31-test('Cannot use exports.getEachMessage() without ipc option', testRequiredIpcExports, 'getEachMessage', {});32-test('Cannot use exports.getEachMessage() with ipc: false', testRequiredIpcExports, 'getEachMessage', {ipc: false});29+test('Cannot use exports.sendMessage() without ipc option', () => testRequiredIpcExports('sendMessage', {}));30+test('Cannot use exports.sendMessage() with ipc: false', () => testRequiredIpcExports('sendMessage', {ipc: false}));31+test('Cannot use exports.getOneMessage() without ipc option', () => testRequiredIpcExports('getOneMessage', {}));32+test('Cannot use exports.getOneMessage() with ipc: false', () => testRequiredIpcExports('getOneMessage', {ipc: false}));33+test('Cannot use exports.getEachMessage() without ipc option', () => testRequiredIpcExports('getEachMessage', {}));34+test('Cannot use exports.getEachMessage() with ipc: false', () => testRequiredIpcExports('getEachMessage', {ipc: false}));35 34-const testPostDisconnection = async (t, methodName) => {36+const 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 };42 41-test('subprocess.sendMessage() after disconnection', testPostDisconnection, 'sendMessage');42-test('subprocess.getOneMessage() after disconnection', testPostDisconnection, 'getOneMessage');43-test('subprocess.getEachMessage() after disconnection', testPostDisconnection, 'getEachMessage');43+test('subprocess.sendMessage() after disconnection', () => testPostDisconnection('sendMessage'));44+test('subprocess.getOneMessage() after disconnection', () => testPostDisconnection('getOneMessage'));45+test('subprocess.getEachMessage() after disconnection', () => testPostDisconnection('getEachMessage'));46 45-const testPostDisconnectionSubprocess = async (t, methodName) => {47+const 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 };53 52-test('exports.sendMessage() after disconnection', testPostDisconnectionSubprocess, 'sendMessage');53-test('exports.getOneMessage() after disconnection', testPostDisconnectionSubprocess, 'getOneMessage');54-test('exports.getEachMessage() after disconnection', testPostDisconnectionSubprocess, 'getEachMessage');54+test('exports.sendMessage() after disconnection', () => testPostDisconnectionSubprocess('sendMessage'));55+test('exports.getOneMessage() after disconnection', () => testPostDisconnectionSubprocess('getOneMessage'));56+test('exports.getEachMessage() after disconnection', () => testPostDisconnectionSubprocess('getEachMessage'));57 58 const INVALID_TYPE_MESSAGE = 'The "message" argument must be one of type string';59 const UNDEFINED_MESSAGE = 'The "message" argument must be specified';60 const CLONE_MESSAGE = 'could not be cloned';61 const CYCLE_MESSAGE = 'Converting circular structure to JSON';62 const MAX_CALL_STACK_MESSAGE = 'Maximum call stack size exceeded';63 62-const testInvalidPayload = async (t, serialization, message, expectedMessage) => {64+const 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 };71 72 const cycleObject = {};73 cycleObject.self = cycleObject;74 const toJsonCycle = {toJSON: () => ({test: true, toJsonCycle})};75 74-test('subprocess.sendMessage() cannot send undefined', testInvalidPayload, 'advanced', undefined, UNDEFINED_MESSAGE);75-test('subprocess.sendMessage() cannot send bigints', testInvalidPayload, 'advanced', 0n, INVALID_TYPE_MESSAGE);76-test('subprocess.sendMessage() cannot send symbols', testInvalidPayload, 'advanced', Symbol('test'), INVALID_TYPE_MESSAGE);77-test('subprocess.sendMessage() cannot send functions', testInvalidPayload, 'advanced', () => {}, INVALID_TYPE_MESSAGE);78-test('subprocess.sendMessage() cannot send promises', testInvalidPayload, 'advanced', Promise.resolve(), CLONE_MESSAGE);79-test('subprocess.sendMessage() cannot send proxies', testInvalidPayload, 'advanced', new Proxy({}, {}), CLONE_MESSAGE);80-test('subprocess.sendMessage() cannot send Intl', testInvalidPayload, 'advanced', new Intl.Collator(), CLONE_MESSAGE);81-test('subprocess.sendMessage() cannot send undefined, JSON', testInvalidPayload, 'json', undefined, UNDEFINED_MESSAGE);82-test('subprocess.sendMessage() cannot send bigints, JSON', testInvalidPayload, 'json', 0n, INVALID_TYPE_MESSAGE);83-test('subprocess.sendMessage() cannot send symbols, JSON', testInvalidPayload, 'json', Symbol('test'), INVALID_TYPE_MESSAGE);84-test('subprocess.sendMessage() cannot send functions, JSON', testInvalidPayload, 'json', () => {}, INVALID_TYPE_MESSAGE);85-test('subprocess.sendMessage() cannot send cycles, JSON', testInvalidPayload, 'json', cycleObject, CYCLE_MESSAGE);86-test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', testInvalidPayload, 'json', toJsonCycle, MAX_CALL_STACK_MESSAGE);76+test('subprocess.sendMessage() cannot send undefined', () => testInvalidPayload('advanced', undefined, UNDEFINED_MESSAGE));77+test('subprocess.sendMessage() cannot send bigints', () => testInvalidPayload('advanced', 0n, INVALID_TYPE_MESSAGE));78+test('subprocess.sendMessage() cannot send symbols', () => testInvalidPayload('advanced', Symbol('test'), INVALID_TYPE_MESSAGE));79+test('subprocess.sendMessage() cannot send functions', () => testInvalidPayload('advanced', () => {}, INVALID_TYPE_MESSAGE));80+test('subprocess.sendMessage() cannot send promises', () => testInvalidPayload('advanced', Promise.resolve(), CLONE_MESSAGE));81+test('subprocess.sendMessage() cannot send proxies', () => testInvalidPayload('advanced', new Proxy({}, {}), CLONE_MESSAGE));82+test('subprocess.sendMessage() cannot send Intl', () => testInvalidPayload('advanced', new Intl.Collator(), CLONE_MESSAGE));83+test('subprocess.sendMessage() cannot send undefined, JSON', () => testInvalidPayload('json', undefined, UNDEFINED_MESSAGE));84+test('subprocess.sendMessage() cannot send bigints, JSON', () => testInvalidPayload('json', 0n, INVALID_TYPE_MESSAGE));85+test('subprocess.sendMessage() cannot send symbols, JSON', () => testInvalidPayload('json', Symbol('test'), INVALID_TYPE_MESSAGE));86+test('subprocess.sendMessage() cannot send functions, JSON', () => testInvalidPayload('json', () => {}, INVALID_TYPE_MESSAGE));87+test('subprocess.sendMessage() cannot send cycles, JSON', () => testInvalidPayload('json', cycleObject, CYCLE_MESSAGE));88+test('subprocess.sendMessage() cannot send cycles in toJSON(), JSON', () => testInvalidPayload('json', toJsonCycle, MAX_CALL_STACK_MESSAGE));89 88-test('exports.sendMessage() validates payload', async t => {90+test('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
1+import assert from 'node:assert/strict';2 import path from 'node:path';2-import test from 'ava';3+import test from 'node:test';4+import {assertRejects} from '../helpers/assert.js';5 import {6 execa,7 execaSync,8 execaNode,7 unmodified lines16 17 const NOOP_PATH = path.join(FIXTURES_DIRECTORY, 'noop.js');18 const PRINT_ENV_PATH = path.join(FIXTURES_DIRECTORY, 'environment.js');19 18-const testBindOptions = async (t, execaMethod) => {20+const 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 };24 23-test('execa() can bind options', testBindOptions, execa);24-test('execaNode() can bind options', testBindOptions, execaNode);25-test('$ can bind options', testBindOptions, $);25+test('execa() can bind options', () => testBindOptions(execa));26+test('execaNode() can bind options', () => testBindOptions(execaNode));27+test('$ can bind options', () => testBindOptions($));28 27-const testBindOptionsSync = (t, execaMethod) => {29+const testBindOptionsSync = execaMethod => {30 const {stdout} = execaMethod({stripFinalNewline: false})(NOOP_PATH, [foobarString]);29- t.is(stdout, `${foobarString}\n`);31+ assert.equal(stdout, `${foobarString}\n`);32 };33 32-test('execaSync() can bind options', testBindOptionsSync, execaSync);33-test('$.sync can bind options', testBindOptionsSync, $.sync);34+test('execaSync() can bind options', () => testBindOptionsSync(execaSync));35+test('$.sync can bind options', () => testBindOptionsSync($.sync));36 35-const testBindPriority = async (t, execaMethod) => {37+const 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 };41 40-test('execa() bound options have lower priority', testBindPriority, execa);41-test('execaSync() bound options have lower priority', testBindPriority, execaSync);42-test('execaNode() bound options have lower priority', testBindPriority, execaNode);43-test('$ bound options have lower priority', testBindPriority, $);44-test('$.sync bound options have lower priority', testBindPriority, $.sync);42+test('execa() bound options have lower priority', () => testBindPriority(execa));43+test('execaSync() bound options have lower priority', () => testBindPriority(execaSync));44+test('execaNode() bound options have lower priority', () => testBindPriority(execaNode));45+test('$ bound options have lower priority', () => testBindPriority($));46+test('$.sync bound options have lower priority', () => testBindPriority($.sync));47 46-const testBindUndefined = async (t, execaMethod) => {48+const 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 };52 51-test('execa() undefined options use default value', testBindUndefined, execa);52-test('execaSync() undefined options use default value', testBindUndefined, execaSync);53-test('execaNode() undefined options use default value', testBindUndefined, execaNode);54-test('$ undefined options use default value', testBindUndefined, $);55-test('$.sync undefined options use default value', testBindUndefined, $.sync);53+test('execa() undefined options use default value', () => testBindUndefined(execa));54+test('execaSync() undefined options use default value', () => testBindUndefined(execaSync));55+test('execaNode() undefined options use default value', () => testBindUndefined(execaNode));56+test('$ undefined options use default value', () => testBindUndefined($));57+test('$.sync undefined options use default value', () => testBindUndefined($.sync));58 57-const testMergeEnv = async (t, execaMethod) => {59+const 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 };63 62-test('execa() bound options are merged', testMergeEnv, execa);63-test('execaSync() bound options are merged', testMergeEnv, execaSync);64-test('execaNode() bound options are merged', testMergeEnv, execaNode);65-test('$ bound options are merged', testMergeEnv, $);66-test('$.sync bound options are merged', testMergeEnv, $.sync);64+test('execa() bound options are merged', () => testMergeEnv(execa));65+test('execaSync() bound options are merged', () => testMergeEnv(execaSync));66+test('execaNode() bound options are merged', () => testMergeEnv(execaNode));67+test('$ bound options are merged', () => testMergeEnv($));68+test('$.sync bound options are merged', () => testMergeEnv($.sync));69 68-const testMergeMultiple = async (t, execaMethod) => {70+const 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 };74 73-test('execa() bound options are merged multiple times', testMergeMultiple, execa);74-test('execaSync() bound options are merged multiple times', testMergeMultiple, execaSync);75-test('execaNode() bound options are merged multiple times', testMergeMultiple, execaNode);76-test('$ bound options are merged multiple times', testMergeMultiple, $);77-test('$.sync bound options are merged multiple times', testMergeMultiple, $.sync);75+test('execa() bound options are merged multiple times', () => testMergeMultiple(execa));76+test('execaSync() bound options are merged multiple times', () => testMergeMultiple(execaSync));77+test('execaNode() bound options are merged multiple times', () => testMergeMultiple(execaNode));78+test('$ bound options are merged multiple times', () => testMergeMultiple($));79+test('$.sync bound options are merged multiple times', () => testMergeMultiple($.sync));80 79-const 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'));81+const 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 };86 85-test('execa() bound options merge fd-specific ones', testMergeFdSpecific, execa);86-test('execaNode() bound options merge fd-specific ones', testMergeFdSpecific, execaNode);87-test('$ bound options merge fd-specific ones', testMergeFdSpecific, $);87+test('execa() bound options merge fd-specific ones', () => testMergeFdSpecific(execa));88+test('execaNode() bound options merge fd-specific ones', () => testMergeFdSpecific(execaNode));89+test('$ bound options merge fd-specific ones', () => testMergeFdSpecific($));90 89-const testMergeEnvUndefined = async (t, execaMethod) => {91+const 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 };95 94-test('execa() bound options are merged even if undefined', testMergeEnvUndefined, execa);95-test('execaSync() bound options are merged even if undefined', testMergeEnvUndefined, execaSync);96-test('execaNode() bound options are merged even if undefined', testMergeEnvUndefined, execaNode);97-test('$ bound options are merged even if undefined', testMergeEnvUndefined, $);98-test('$.sync bound options are merged even if undefined', testMergeEnvUndefined, $.sync);96+test('execa() bound options are merged even if undefined', () => testMergeEnvUndefined(execa));97+test('execaSync() bound options are merged even if undefined', () => testMergeEnvUndefined(execaSync));98+test('execaNode() bound options are merged even if undefined', () => testMergeEnvUndefined(execaNode));99+test('$ bound options are merged even if undefined', () => testMergeEnvUndefined($));100+test('$.sync bound options are merged even if undefined', () => testMergeEnvUndefined($.sync));101 100-const testMergeSpecific = async (t, execaMethod) => {102+const 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 };106 105-test('execa() bound options only merge specific ones', testMergeSpecific, execa);106-test('execaSync() bound options only merge specific ones', testMergeSpecific, execaSync);107-test('execaNode() bound options only merge specific ones', testMergeSpecific, execaNode);108-test('$ bound options only merge specific ones', testMergeSpecific, $);109-test('$.sync bound options only merge specific ones', testMergeSpecific, $.sync);107+test('execa() bound options only merge specific ones', () => testMergeSpecific(execa));108+test('execaSync() bound options only merge specific ones', () => testMergeSpecific(execaSync));109+test('execaNode() bound options only merge specific ones', () => testMergeSpecific(execaNode));110+test('$ bound options only merge specific ones', () => testMergeSpecific($));111+test('$.sync bound options only merge specific ones', () => testMergeSpecific($.sync));modified:test/methods/command.js+47 added-45 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows} from '../helpers/assert.js';4 import {5 execa,6 execaSync,7 $,9 unmodified lines17 const ECHO_FIXTURE_URL = new URL('echo.js', FIXTURES_DIRECTORY_URL);18 19 const parseAndRunCommand = command => execa`${parseCommandString(command)}`;20 19-test('parseCommandString() + execa()', async t => {21+test('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 });25 24-test('parseCommandString() + execaSync()', t => {26+test('parseCommandString() + execaSync()', () => {27 const {stdout} = execaSync('echo.js', parseCommandString('foo bar'));26- t.is(stdout, 'foo\nbar');28+ assert.equal(stdout, 'foo\nbar');29 });30 29-test('parseCommandString() + execa`...`', async t => {31+test('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 });35 34-test('parseCommandString() + execa`...`, only arguments', async t => {36+test('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 });40 39-test('parseCommandString() + execa`...`, only some arguments', async t => {41+test('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 });45 44-test('parseCommandString() + execaSync`...`', t => {46+test('parseCommandString() + execaSync`...`', () => {47 const {stdout} = execaSync`${parseCommandString('echo.js foo bar')}`;46- t.is(stdout, 'foo\nbar');48+ assert.equal(stdout, 'foo\nbar');49 });50 49-test('parseCommandString() + execaSync`...`, only arguments', t => {51+test('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 });55 54-test('parseCommandString() + execaSync`...`, only some arguments', t => {56+test('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 });60 59-test('parseCommandString() + $', async t => {61+test('parseCommandString() + $', async () => {62 const {stdout} = await $`${parseCommandString('echo.js foo bar')}`;61- t.is(stdout, 'foo\nbar');63+ assert.equal(stdout, 'foo\nbar');64 });65 64-test('parseCommandString() + $.sync', t => {66+test('parseCommandString() + $.sync', () => {67 const {stdout} = $.sync`${parseCommandString('echo.js foo bar')}`;66- t.is(stdout, 'foo\nbar');68+ assert.equal(stdout, 'foo\nbar');69 });70 69-test('parseCommandString() + execaNode', async t => {71+test('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 });75 74-const testInvalidArgumentsParse = (t, command) => {75- t.throws(() => parseCommandString(command), {76+const testInvalidArgumentsParse = command => {77+ assertThrows(() => parseCommandString(command), {78 message: /The command must be a string/,79 });80 };81 80-test('parseCommandString() must not pass a number', testInvalidArgumentsParse, 0);81-test('parseCommandString() must not pass undefined', testInvalidArgumentsParse, undefined);82-test('parseCommandString() must not pass null', testInvalidArgumentsParse, null);83-test('parseCommandString() must not pass a symbol', testInvalidArgumentsParse, Symbol('test'));84-test('parseCommandString() must not pass an object', testInvalidArgumentsParse, {});85-test('parseCommandString() must not pass an array', testInvalidArgumentsParse, []);82+test('parseCommandString() must not pass a number', () => testInvalidArgumentsParse(0));83+test('parseCommandString() must not pass undefined', () => testInvalidArgumentsParse(undefined));84+test('parseCommandString() must not pass null', () => testInvalidArgumentsParse(null));85+test('parseCommandString() must not pass a symbol', () => testInvalidArgumentsParse(Symbol('test')));86+test('parseCommandString() must not pass an object', () => testInvalidArgumentsParse({}));87+test('parseCommandString() must not pass an array', () => testInvalidArgumentsParse([]));88 87-const testParseCommandOutput = async (t, command, expectedOutput, execaMethod) => {89+const testParseCommandOutput = async (command, expectedOutput, execaMethod) => {90 const {stdout} = await execaMethod(command);89- t.is(stdout, expectedOutput);91+ assert.equal(stdout, expectedOutput);92 };93 92-test('parseCommandString() allows escaping spaces in commands', testParseCommandOutput, 'command\\ with\\ space.js foo bar', 'foo\nbar', parseAndRunCommand);93-test('parseCommandString() trims', testParseCommandOutput, ' echo.js foo bar ', 'foo\nbar', parseAndRunCommand);94-test('parseCommandString() ignores consecutive spaces', testParseCommandOutput, 'echo.js foo bar', 'foo\nbar', parseAndRunCommand);95-test('parseCommandString() escapes other whitespaces', testParseCommandOutput, 'echo.js foo\tbar', 'foo\tbar', parseAndRunCommand);96-test('parseCommandString() allows escaping spaces', testParseCommandOutput, 'echo.js foo\\ bar', 'foo bar', parseAndRunCommand);97-test('parseCommandString() allows escaping backslashes before spaces', testParseCommandOutput, 'echo.js foo\\\\ bar', 'foo\\ bar', parseAndRunCommand);98-test('parseCommandString() allows escaping multiple backslashes before spaces', testParseCommandOutput, 'echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', parseAndRunCommand);99-test('parseCommandString() allows escaping backslashes not before spaces', testParseCommandOutput, 'echo.js foo\\bar baz', 'foo\\bar\nbaz', parseAndRunCommand);94+test('parseCommandString() allows escaping spaces in commands', () => testParseCommandOutput('command\\ with\\ space.js foo bar', 'foo\nbar', parseAndRunCommand));95+test('parseCommandString() trims', () => testParseCommandOutput(' echo.js foo bar ', 'foo\nbar', parseAndRunCommand));96+test('parseCommandString() ignores consecutive spaces', () => testParseCommandOutput('echo.js foo bar', 'foo\nbar', parseAndRunCommand));97+test('parseCommandString() escapes other whitespaces', () => testParseCommandOutput('echo.js foo\tbar', 'foo\tbar', parseAndRunCommand));98+test('parseCommandString() allows escaping spaces', () => testParseCommandOutput('echo.js foo\\ bar', 'foo bar', parseAndRunCommand));99+test('parseCommandString() allows escaping backslashes before spaces', () => testParseCommandOutput('echo.js foo\\\\ bar', 'foo\\ bar', parseAndRunCommand));100+test('parseCommandString() allows escaping multiple backslashes before spaces', () => testParseCommandOutput('echo.js foo\\\\\\\\ bar', 'foo\\\\\\ bar', parseAndRunCommand));101+test('parseCommandString() allows escaping backslashes not before spaces', () => testParseCommandOutput('echo.js foo\\bar baz', 'foo\\bar\nbaz', parseAndRunCommand));102 101-test('parseCommandString() can get empty strings', t => {102- t.deepEqual(parseCommandString(''), []);103+test('parseCommandString() can get empty strings', () => {104+ assert.deepEqual(parseCommandString(''), []);105 });106 105-test('parseCommandString() can get only whitespaces', t => {107+test('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
1+import assert from 'node:assert/strict';2 import path from 'node:path';2-import test from 'ava';3+import test from 'node:test';4 import {5 execa,6 execaSync,7 execaNode,5 unmodified lines13 setFixtureDirectory();14 15 const NOOP_PATH = path.join(FIXTURES_DIRECTORY, 'noop.js');16 16-const testTemplate = async (t, execaMethod) => {17+const testTemplate = async execaMethod => {18 const {stdout} = await execaMethod`${NOOP_PATH} ${foobarString}`;18- t.is(stdout, foobarString);19+ assert.equal(stdout, foobarString);20 };21 21-test('execa() can use template strings', testTemplate, execa);22-test('execaNode() can use template strings', testTemplate, execaNode);23-test('$ can use template strings', testTemplate, $);22+test('execa() can use template strings', () => testTemplate(execa));23+test('execaNode() can use template strings', () => testTemplate(execaNode));24+test('$ can use template strings', () => testTemplate($));25 25-const testTemplateSync = (t, execaMethod) => {26+const testTemplateSync = execaMethod => {27 const {stdout} = execaMethod`${NOOP_PATH} ${foobarString}`;27- t.is(stdout, foobarString);28+ assert.equal(stdout, foobarString);29 };30 30-test('execaSync() can use template strings', testTemplateSync, execaSync);31-test('$.sync can use template strings', testTemplateSync, $.sync);31+test('execaSync() can use template strings', () => testTemplateSync(execaSync));32+test('$.sync can use template strings', () => testTemplateSync($.sync));33 33-const testTemplateOptions = async (t, execaMethod) => {34+const 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 };38 38-test('execa() can use template strings with options', testTemplateOptions, execa);39-test('execaNode() can use template strings with options', testTemplateOptions, execaNode);40-test('$ can use template strings with options', testTemplateOptions, $);39+test('execa() can use template strings with options', () => testTemplateOptions(execa));40+test('execaNode() can use template strings with options', () => testTemplateOptions(execaNode));41+test('$ can use template strings with options', () => testTemplateOptions($));42 42-const testTemplateOptionsSync = (t, execaMethod) => {43+const testTemplateOptionsSync = execaMethod => {44 const {stdout} = execaMethod({stripFinalNewline: false})`${NOOP_PATH} ${foobarString}`;44- t.is(stdout, `${foobarString}\n`);45+ assert.equal(stdout, `${foobarString}\n`);46 };47 47-test('execaSync() can use template strings with options', testTemplateOptionsSync, execaSync);48-test('$.sync can use template strings with options', testTemplateOptionsSync, $.sync);48+test('execaSync() can use template strings with options', () => testTemplateOptionsSync(execaSync));49+test('$.sync can use template strings with options', () => testTemplateOptionsSync($.sync));50 50-const testSpacedCommand = async (t, commandArguments, execaMethod) => {51+const 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 };56 56-test('allow commands with spaces and no array arguments', testSpacedCommand, undefined, execa);57-test('allow commands with spaces and array arguments', testSpacedCommand, foobarArray, execa);58-test('allow commands with spaces and no array arguments, execaSync', testSpacedCommand, undefined, execaSync);59-test('allow commands with spaces and array arguments, execaSync', testSpacedCommand, foobarArray, execaSync);60-test('allow commands with spaces and no array arguments, $', testSpacedCommand, undefined, $);61-test('allow commands with spaces and array arguments, $', testSpacedCommand, foobarArray, $);62-test('allow commands with spaces and no array arguments, $.sync', testSpacedCommand, undefined, $.sync);63-test('allow commands with spaces and array arguments, $.sync', testSpacedCommand, foobarArray, $.sync);57+test('allow commands with spaces and no array arguments', () => testSpacedCommand(undefined, execa));58+test('allow commands with spaces and array arguments', () => testSpacedCommand(foobarArray, execa));59+test('allow commands with spaces and no array arguments, execaSync', () => testSpacedCommand(undefined, execaSync));60+test('allow commands with spaces and array arguments, execaSync', () => testSpacedCommand(foobarArray, execaSync));61+test('allow commands with spaces and no array arguments, $', () => testSpacedCommand(undefined, $));62+test('allow commands with spaces and array arguments, $', () => testSpacedCommand(foobarArray, $));63+test('allow commands with spaces and no array arguments, $.sync', () => testSpacedCommand(undefined, $.sync));64+test('allow commands with spaces and array arguments, $.sync', () => testSpacedCommand(foobarArray, $.sync));modified:test/methods/main-async.js+42 added-41 removed
1+import assert from 'node:assert/strict';2 import process from 'node:process';3 import {ChildProcess} from 'node:child_process';3-import test from 'ava';4+import test from 'node:test';5 import {execa} from '../../index.js';6 import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';7 8 setFixtureDirectory();9 10 const isWindows = process.platform === 'win32';11 12 if (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 });17 17- 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 });22 23 // 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 });28 28- 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 });33 34 // 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 }40 40-test('execa() returns a promise with pid', async t => {41+test('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 });46 46-test('execa() returns a promise with nodeChildProcess', async t => {47+test('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);67+68+ assert.equal(subprocess[Symbol.dispose], undefined);69 await subprocess;70 });71 71-test('nodeChildProcess does not include Execa-specific APIs', async t => {72+test('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
1+import assert from 'node:assert/strict';2 import path from 'node:path';3 import process, {version} from 'node:process';4 import {pathToFileURL} from 'node:url';4-import test from 'ava';5+import test from 'node:test';6 import getNode from 'get-node';7+import {assertThrows, assertRejects} from '../helpers/assert.js';8 import {execa, execaSync, execaNode} from '../../index.js';9 import {FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';10 import {identity, fullStdio} from '../helpers/stdio.js';11 import {foobarString} from '../helpers/input.js';8 unmodified lines20 ? execaSync(file, commandArguments, {...options, node: true})21 : execaSync(file, {...options, node: true});22 const runWithIpc = (file, options) => execa('node', [file], {...options, ipc: true});23 22-const testNodeSuccess = async (t, execaMethod) => {24+const 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 };29 28-test('execaNode() succeeds', testNodeSuccess, execaNode);29-test('The "node" option succeeds', testNodeSuccess, runWithNodeOption);30-test('The "node" option succeeds - sync', testNodeSuccess, runWithNodeOptionSync);30+test('execaNode() succeeds', () => testNodeSuccess(execaNode));31+test('The "node" option succeeds', () => testNodeSuccess(runWithNodeOption));32+test('The "node" option succeeds - sync', () => testNodeSuccess(runWithNodeOptionSync));33 32-test('execaNode(options) succeeds', async t => {34+test('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 });38 37-test('execaNode`...` succeeds', async t => {39+test('execaNode`...` succeeds', async () => {40 const {stdout} = await execaNode`noop.js ${foobarString}`;39- t.is(stdout, foobarString);41+ assert.equal(stdout, foobarString);42 });43 42-test('execaNode().pipe(execaNode()) succeeds', async t => {44+test('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 });48 47-test('execaNode().pipe(execa()) requires using "node"', async t => {48- await t.throwsAsync(execaNode('noop.js').pipe(execa('--version')));49+test('execaNode().pipe(execa()) requires using "node"', async () => {50+ await assertRejects(execaNode('noop.js').pipe(execa('--version')));51 });52 51-test('execaNode().pipe(...) requires using "node"', async t => {52- await t.throwsAsync(execaNode('noop.js').pipe('--version'));53+test('execaNode().pipe(...) requires using "node"', async () => {54+ await assertRejects(execaNode('noop.js').pipe('--version'));55 });56 55-test('execaNode().pipe`...` requires using "node"', async t => {56- await t.throwsAsync(execaNode('noop.js').pipe`--version`);57+test('execaNode().pipe`...` requires using "node"', async () => {58+ await assertRejects(execaNode('noop.js').pipe`--version`);59 });60 59-test('execaNode() cannot set the "node" option to false', t => {60- t.throws(() => {61+test('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 });66 65-const testDoubleNode = (t, nodePath, execaMethod) => {66- t.throws(() => {67+const testDoubleNode = (nodePath, execaMethod) => {68+ assertThrows(() => {69 execaMethod(nodePath, ['noop.js']);70 }, {message: /does not need to be "node"/});71 };72 71-test('Cannot use "node" as binary - execaNode()', testDoubleNode, 'node', execaNode);72-test('Cannot use "node" as binary - "node" option', testDoubleNode, 'node', runWithNodeOption);73-test('Cannot use "node" as binary - "node" option sync', testDoubleNode, 'node', runWithNodeOptionSync);74-test('Cannot use path to "node" as binary - execaNode()', testDoubleNode, process.execPath, execaNode);75-test('Cannot use path to "node" as binary - "node" option', testDoubleNode, process.execPath, runWithNodeOption);76-test('Cannot use path to "node" as binary - "node" option sync', testDoubleNode, process.execPath, runWithNodeOptionSync);77-test('Cannot use deno style nodePath as binary - execaNode()', testDoubleNode, getDenoNodePath(), execaNode);78-test('Cannot use deno style nodePath as binary - "node" option', testDoubleNode, getDenoNodePath(), runWithNodeOption);79-test('Cannot use deno style nodePath as binary - "node" option sync', testDoubleNode, getDenoNodePath(), runWithNodeOptionSync);73+test('Cannot use "node" as binary - execaNode()', () => testDoubleNode('node', execaNode));74+test('Cannot use "node" as binary - "node" option', () => testDoubleNode('node', runWithNodeOption));75+test('Cannot use "node" as binary - "node" option sync', () => testDoubleNode('node', runWithNodeOptionSync));76+test('Cannot use path to "node" as binary - execaNode()', () => testDoubleNode(process.execPath, execaNode));77+test('Cannot use path to "node" as binary - "node" option', () => testDoubleNode(process.execPath, runWithNodeOption));78+test('Cannot use path to "node" as binary - "node" option sync', () => testDoubleNode(process.execPath, runWithNodeOptionSync));79+test('Cannot use deno style nodePath as binary - execaNode()', () => testDoubleNode(getDenoNodePath(), execaNode));80+test('Cannot use deno style nodePath as binary - "node" option', () => testDoubleNode(getDenoNodePath(), runWithNodeOption));81+test('Cannot use deno style nodePath as binary - "node" option sync', () => testDoubleNode(getDenoNodePath(), runWithNodeOptionSync));82 83 const getNodePath = async () => {84 const {path} = await getNode(TEST_NODE_VERSION);85 return path;86 };87 88 const TEST_NODE_VERSION = '16.0.0';89 90+// `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.92+const downloadedNodeOptions = {nodeOptions: []};93+88-const testNodePath = async (t, execaMethod, mapPath) => {94+const 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 };99 94-test.serial('The "nodePath" option can be used - execaNode()', testNodePath, execaNode, identity);95-test.serial('The "nodePath" option can be a file URL - execaNode()', testNodePath, execaNode, pathToFileURL);96-test.serial('The "nodePath" option can be used - "node" option', testNodePath, runWithNodeOption, identity);97-test.serial('The "nodePath" option can be a file URL - "node" option', testNodePath, runWithNodeOption, pathToFileURL);98-test.serial('The "nodePath" option can be used - "node" option sync', testNodePath, runWithNodeOptionSync, identity);99-test.serial('The "nodePath" option can be a file URL - "node" option sync', testNodePath, runWithNodeOptionSync, pathToFileURL);100+test('The "nodePath" option can be used - execaNode()', () => testNodePath(execaNode, identity));101+test('The "nodePath" option can be a file URL - execaNode()', () => testNodePath(execaNode, pathToFileURL));102+test('The "nodePath" option can be used - "node" option', () => testNodePath(runWithNodeOption, identity));103+test('The "nodePath" option can be a file URL - "node" option', () => testNodePath(runWithNodeOption, pathToFileURL));104+test('The "nodePath" option can be used - "node" option sync', () => testNodePath(runWithNodeOptionSync, identity));105+test('The "nodePath" option can be a file URL - "node" option sync', () => testNodePath(runWithNodeOptionSync, pathToFileURL));106 101-const testNodePathDefault = async (t, execaMethod) => {107+const testNodePathDefault = async execaMethod => {108 const {stdout} = await execaMethod('--version');103- t.is(stdout, process.version);109+ assert.equal(stdout, process.version);110 };111 106-test('The "nodePath" option defaults to the current Node.js binary - execaNode()', testNodePathDefault, execaNode);107-test('The "nodePath" option defaults to the current Node.js binary - "node" option', testNodePathDefault, runWithNodeOption);108-test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', testNodePathDefault, runWithNodeOptionSync);112+test('The "nodePath" option defaults to the current Node.js binary - execaNode()', () => testNodePathDefault(execaNode));113+test('The "nodePath" option defaults to the current Node.js binary - "node" option', () => testNodePathDefault(runWithNodeOption));114+test('The "nodePath" option defaults to the current Node.js binary - "node" option sync', () => testNodePathDefault(runWithNodeOptionSync));115 110-const testNodePathInvalid = (t, execaMethod) => {111- t.throws(() => {116+const testNodePathInvalid = execaMethod => {117+ assertThrows(() => {118 execaMethod('noop.js', [], {nodePath: true});119 }, {message: /The "nodePath" option must be a string or a file URL/});120 };121 116-test('The "nodePath" option must be a string or URL - execaNode()', testNodePathInvalid, execaNode);117-test('The "nodePath" option must be a string or URL - "node" option', testNodePathInvalid, runWithNodeOption);118-test('The "nodePath" option must be a string or URL - "node" option sync', testNodePathInvalid, runWithNodeOptionSync);122+test('The "nodePath" option must be a string or URL - execaNode()', () => testNodePathInvalid(execaNode));123+test('The "nodePath" option must be a string or URL - "node" option', () => testNodePathInvalid(runWithNodeOption));124+test('The "nodePath" option must be a string or URL - "node" option sync', () => testNodePathInvalid(runWithNodeOptionSync));125 120-const testFormerNodePath = (t, execaMethod) => {121- t.throws(() => {126+const testFormerNodePath = execaMethod => {127+ assertThrows(() => {128 execaMethod('noop.js', [], {execPath: process.execPath});129 }, {message: /The "execPath" option has been removed/});130 };131 126-test('The "execPath" option cannot be used - execaNode()', testFormerNodePath, execaNode);127-test('The "execPath" option cannot be used - "node" option', testFormerNodePath, runWithNodeOption);128-test('The "execPath" option cannot be used - "node" option sync', testFormerNodePath, runWithNodeOptionSync);132+test('The "execPath" option cannot be used - execaNode()', () => testFormerNodePath(execaNode));133+test('The "execPath" option cannot be used - "node" option', () => testFormerNodePath(runWithNodeOption));134+test('The "execPath" option cannot be used - "node" option sync', () => testFormerNodePath(runWithNodeOptionSync));135 136 const nodePathArguments = ['-p', ['process.env.Path || process.env.PATH']];137 132-const testSubprocessNodePath = async (t, execaMethod, mapPath) => {138+const 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 };143 138-test.serial('The "nodePath" option impacts the subprocess - execaNode()', testSubprocessNodePath, execaNode, identity);139-test.serial('The "nodePath" option impacts the subprocess - "node" option', testSubprocessNodePath, runWithNodeOption, identity);140-test.serial('The "nodePath" option impacts the subprocess - "node" option sync', testSubprocessNodePath, runWithNodeOptionSync, identity);144+test('The "nodePath" option impacts the subprocess - execaNode()', () => testSubprocessNodePath(execaNode, identity));145+test('The "nodePath" option impacts the subprocess - "node" option', () => testSubprocessNodePath(runWithNodeOption, identity));146+test('The "nodePath" option impacts the subprocess - "node" option sync', () => testSubprocessNodePath(runWithNodeOptionSync, identity));147 142-const testSubprocessNodePathDefault = async (t, execaMethod) => {148+const 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 };152 147-test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', testSubprocessNodePathDefault, execaNode);148-test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', testSubprocessNodePathDefault, runWithNodeOption);149-test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', testSubprocessNodePathDefault, runWithNodeOptionSync);153+test('The "nodePath" option defaults to the current Node.js binary in the subprocess - execaNode()', () => testSubprocessNodePathDefault(execaNode));154+test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option', () => testSubprocessNodePathDefault(runWithNodeOption));155+test('The "nodePath" option defaults to the current Node.js binary in the subprocess - "node" option sync', () => testSubprocessNodePathDefault(runWithNodeOptionSync));156 151-test.serial('The "nodePath" option requires "node: true" to impact the subprocess', async t => {157+test('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 });162 157-const testSubprocessNodePathCwd = async (t, execaMethod) => {163+const 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 };170 165-test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', testSubprocessNodePathCwd, execaNode);166-test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', testSubprocessNodePathCwd, runWithNodeOption);167-test.serial('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', testSubprocessNodePathCwd, runWithNodeOptionSync);171+test('The "nodePath" option is relative to "cwd" when used in the subprocess - execaNode()', () => testSubprocessNodePathCwd(execaNode));172+test('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option', () => testSubprocessNodePathCwd(runWithNodeOption));173+test('The "nodePath" option is relative to "cwd" when used in the subprocess - "node" option sync', () => testSubprocessNodePathCwd(runWithNodeOptionSync));174 169-const testCwdNodePath = async (t, execaMethod) => {175+const 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 };182 177-test.serial('The "nodePath" option is relative to "cwd" - execaNode()', testCwdNodePath, execaNode);178-test.serial('The "nodePath" option is relative to "cwd" - "node" option', testCwdNodePath, runWithNodeOption);179-test.serial('The "nodePath" option is relative to "cwd" - "node" option sync', testCwdNodePath, runWithNodeOptionSync);183+test('The "nodePath" option is relative to "cwd" - execaNode()', () => testCwdNodePath(execaNode));184+test('The "nodePath" option is relative to "cwd" - "node" option', () => testCwdNodePath(runWithNodeOption));185+test('The "nodePath" option is relative to "cwd" - "node" option sync', () => testCwdNodePath(runWithNodeOptionSync));186 181-const testDenoExecPath = async (t, execaMethod) => {187+const 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 };192 187-test('The deno style "nodePath" option can be used - execaNode()', testDenoExecPath, execaNode);188-test('The deno style "nodePath" option can be used - "node" option', testDenoExecPath, runWithNodeOption);189-test('The deno style "nodePath" option can be used - "node" option sync', testDenoExecPath, runWithNodeOptionSync);193+test('The deno style "nodePath" option can be used - execaNode()', () => testDenoExecPath(execaNode));194+test('The deno style "nodePath" option can be used - "node" option', () => testDenoExecPath(runWithNodeOption));195+test('The deno style "nodePath" option can be used - "node" option sync', () => testDenoExecPath(runWithNodeOptionSync));196 191-const testNodeOptions = async (t, execaMethod) => {197+const 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 };201 196-test('The "nodeOptions" option can be used - execaNode()', testNodeOptions, execaNode);197-test('The "nodeOptions" option can be used - "node" option', testNodeOptions, runWithNodeOption);198-test('The "nodeOptions" option can be used - "node" option sync', testNodeOptions, runWithNodeOptionSync);202+test('The "nodeOptions" option can be used - execaNode()', () => testNodeOptions(execaNode));203+test('The "nodeOptions" option can be used - "node" option', () => testNodeOptions(runWithNodeOption));204+test('The "nodeOptions" option can be used - "node" option sync', () => testNodeOptions(runWithNodeOptionSync));205 206 const 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 );211 206-const testInspectRemoval = async (t, fakeExecArgv, execaMethod) => {212+const 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 };217 212-test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect', 'execaNode');213-test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', testInspectRemoval, '--inspect', 'nodeOption');214-test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect=9222', 'execaNode');215-test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', testInspectRemoval, '--inspect=9222', 'nodeOption');216-test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk', 'execaNode');217-test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk', 'nodeOption');218-test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', testInspectRemoval, '--inspect-brk=9223', 'execaNode');219-test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', testInspectRemoval, '--inspect-brk=9223', 'nodeOption');218+test('The "nodeOptions" option removes --inspect without a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect', 'execaNode'));219+test('The "nodeOptions" option removes --inspect without a port when defined by current process - "node" option', () => testInspectRemoval('--inspect', 'nodeOption'));220+test('The "nodeOptions" option removes --inspect with a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect=9222', 'execaNode'));221+test('The "nodeOptions" option removes --inspect with a port when defined by current process - "node" option', () => testInspectRemoval('--inspect=9222', 'nodeOption'));222+test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect-brk', 'execaNode'));223+test('The "nodeOptions" option removes --inspect-brk without a port when defined by current process - "node" option', () => testInspectRemoval('--inspect-brk', 'nodeOption'));224+test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - execaNode()', () => testInspectRemoval('--inspect-brk=9223', 'execaNode'));225+test('The "nodeOptions" option removes --inspect-brk with a port when defined by current process - "node" option', () => testInspectRemoval('--inspect-brk=9223', 'nodeOption'));226 221-const testInspectDifferentPort = async (t, execaMethod) => {227+const 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 };232 227-test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', testInspectDifferentPort, 'execaNode');228-test.serial('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', testInspectDifferentPort, 'nodeOption');233+test('The "nodeOptions" option allows --inspect with a different port even when defined by current process - execaNode()', () => testInspectDifferentPort('execaNode'));234+test('The "nodeOptions" option allows --inspect with a different port even when defined by current process - "node" option', () => testInspectDifferentPort('nodeOption'));235 230-const testInspectSamePort = async (t, execaMethod) => {236+const 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 };241 236-test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', testInspectSamePort, 'execaNode');237-test.serial('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', testInspectSamePort, 'nodeOption');242+test('The "nodeOptions" option forbids --inspect with the same port when defined by current process - execaNode()', () => testInspectSamePort('execaNode'));243+test('The "nodeOptions" option forbids --inspect with the same port when defined by current process - "node" option', () => testInspectSamePort('nodeOption'));244 239-const testIpc = async (t, execaMethod, options) => {245+const testIpc = async (execaMethod, options) => {246 const subprocess = execaMethod('ipc-echo.js', [], options);247 248 await subprocess.sendMessage(foobarString);243- t.is(await subprocess.getOneMessage(), foobarString);249+ assert.equal(await subprocess.getOneMessage(), foobarString);250 251 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 };255 250-test('execaNode() adds an ipc channel', testIpc, execaNode, {});251-test('The "node" option adds an ipc channel', testIpc, runWithNodeOption, {});252-test('The "ipc" option adds an ipc channel', testIpc, runWithIpc, {});253-test('The "ipc" option works with "stdio: \'pipe\'"', testIpc, runWithIpc, {stdio: 'pipe'});254-test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', testIpc, runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']});255-test('The "ipc" option works with "stdout: \'pipe\'"', testIpc, runWithIpc, {stdout: 'pipe'});256+test('execaNode() adds an ipc channel', () => testIpc(execaNode, {}));257+test('The "node" option adds an ipc channel', () => testIpc(runWithNodeOption, {}));258+test('The "ipc" option adds an ipc channel', () => testIpc(runWithIpc, {}));259+test('The "ipc" option works with "stdio: \'pipe\'"', () => testIpc(runWithIpc, {stdio: 'pipe'}));260+test('The "ipc" option works with "stdio: [\'pipe\', \'pipe\', \'pipe\']"', () => testIpc(runWithIpc, {stdio: ['pipe', 'pipe', 'pipe']}));261+test('The "ipc" option works with "stdout: \'pipe\'"', () => testIpc(runWithIpc, {stdout: 'pipe'}));262 263 const NO_SEND_MESSAGE = 'sendMessage() can only be used';264 259-test('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);265+test('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 });270 265-const testDisableIpc = async (t, execaMethod) => {271+const 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 };277 272-test('Can disable "ipc" - execaNode()', testDisableIpc, execaNode);273-test('Can disable "ipc" - "node" option', testDisableIpc, runWithNodeOption);274-test('Can disable "ipc" - "node" option sync', testDisableIpc, runWithNodeOptionSync);278+test('Can disable "ipc" - execaNode()', () => testDisableIpc(execaNode));279+test('Can disable "ipc" - "node" option', () => testDisableIpc(runWithNodeOption));280+test('Can disable "ipc" - "node" option sync', () => testDisableIpc(runWithNodeOptionSync));281 282 const NO_IPC_MESSAGE = /The "ipc: true" option cannot be used/;283 278-const testNoIpcSync = (t, node) => {279- t.throws(() => {284+const testNoIpcSync = node => {285+ assertThrows(() => {286 execaSync('node', ['ipc-send.js'], {ipc: true, node});287 }, {message: NO_IPC_MESSAGE});288 };289 284-test('Cannot use "ipc: true" with execaSync()', testNoIpcSync, undefined);285-test('Cannot use "ipc: true" with execaSync() - "node: false"', testNoIpcSync, false);290+test('Cannot use "ipc: true" with execaSync()', () => testNoIpcSync(undefined));291+test('Cannot use "ipc: true" with execaSync() - "node: false"', () => testNoIpcSync(false));292 287-test('Cannot use "ipc: true" with execaSync() - "node: true"', t => {288- t.throws(() => {293+test('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 });298 293-const testNoShell = async (t, execaMethod) => {299+const 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 };304 299-test('Cannot use "shell: true" - execaNode()', testNoShell, execaNode);300-test('Cannot use "shell: true" - "node" option', testNoShell, runWithNodeOption);301-test('Cannot use "shell: true" - "node" option sync', testNoShell, runWithNodeOptionSync);305+test('Cannot use "shell: true" - execaNode()', () => testNoShell(execaNode));306+test('Cannot use "shell: true" - "node" option', () => testNoShell(runWithNodeOption));307+test('Cannot use "shell: true" - "node" option sync', () => testNoShell(runWithNodeOptionSync));modified:test/methods/override-promise.js+4 added-3 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 // The helper module overrides Promise on import so has to be imported before `execa`.4 import {restorePromise} from '../helpers/override-promise.js';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 8 restorePromise();9 setFixtureDirectory();10 10-test('should work with third-party Promise', async t => {11+test('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
1-import test from 'ava';1+import test from 'node:test';2+import {assertThrows} from '../helpers/assert.js';3 import {4 execa,5 execaSync,6 execaNode,2 unmodified lines9 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10 11 setFixtureDirectory();12 12-const testInvalidArguments = async (t, execaMethod) => {13- t.throws(() => {13+const testInvalidArguments = async execaMethod => {14+ assertThrows(() => {15 execaMethod('echo', true);16 }, {message: /Second argument must be either/});17 };18 18-test('execa()\'s second argument must be valid', testInvalidArguments, execa);19-test('execaSync()\'s second argument must be valid', testInvalidArguments, execaSync);20-test('execaNode()\'s second argument must be valid', testInvalidArguments, execaNode);21-test('$\'s second argument must be valid', testInvalidArguments, $);22-test('$.sync\'s second argument must be valid', testInvalidArguments, $.sync);19+test('execa()\'s second argument must be valid', () => testInvalidArguments(execa));20+test('execaSync()\'s second argument must be valid', () => testInvalidArguments(execaSync));21+test('execaNode()\'s second argument must be valid', () => testInvalidArguments(execaNode));22+test('$\'s second argument must be valid', () => testInvalidArguments($));23+test('$.sync\'s second argument must be valid', () => testInvalidArguments($.sync));24 24-const testInvalidArgumentsItems = async (t, execaMethod) => {25- t.throws(() => {25+const testInvalidArgumentsItems = async execaMethod => {26+ assertThrows(() => {27 execaMethod('echo', [{}]);28 }, {message: 'Second argument must be an array of strings: [object Object]'});29 };30 30-test('execa()\'s second argument must not be objects', testInvalidArgumentsItems, execa);31-test('execaSync()\'s second argument must not be objects', testInvalidArgumentsItems, execaSync);32-test('execaNode()\'s second argument must not be objects', testInvalidArgumentsItems, execaNode);33-test('$\'s second argument must not be objects', testInvalidArgumentsItems, $);34-test('$.sync\'s second argument must not be objects', testInvalidArgumentsItems, $.sync);31+test('execa()\'s second argument must not be objects', () => testInvalidArgumentsItems(execa));32+test('execaSync()\'s second argument must not be objects', () => testInvalidArgumentsItems(execaSync));33+test('execaNode()\'s second argument must not be objects', () => testInvalidArgumentsItems(execaNode));34+test('$\'s second argument must not be objects', () => testInvalidArgumentsItems($));35+test('$.sync\'s second argument must not be objects', () => testInvalidArgumentsItems($.sync));36 36-const testNullByteArgument = async (t, execaMethod) => {37- t.throws(() => {37+const testNullByteArgument = async execaMethod => {38+ assertThrows(() => {39 execaMethod('echo', ['a\0b']);40 }, {message: /null bytes/});41 };42 42-test('execa()\'s second argument must not include \\0', testNullByteArgument, execa);43-test('execaSync()\'s second argument must not include \\0', testNullByteArgument, execaSync);44-test('execaNode()\'s second argument must not include \\0', testNullByteArgument, execaNode);45-test('$\'s second argument must not include \\0', testNullByteArgument, $);46-test('$.sync\'s second argument must not include \\0', testNullByteArgument, $.sync);43+test('execa()\'s second argument must not include \\0', () => testNullByteArgument(execa));44+test('execaSync()\'s second argument must not include \\0', () => testNullByteArgument(execaSync));45+test('execaNode()\'s second argument must not include \\0', () => testNullByteArgument(execaNode));46+test('$\'s second argument must not include \\0', () => testNullByteArgument($));47+test('$.sync\'s second argument must not include \\0', () => testNullByteArgument($.sync));modified:test/methods/parameters-command.js+41 added-39 removed
1+import assert from 'node:assert/strict';2 import path from 'node:path';3 import {fileURLToPath} from 'node:url';3-import test from 'ava';4+import test from 'node:test';5+import {assertThrows} from '../helpers/assert.js';6 import {7 execa,8 execaSync,9 execaNode,3 unmodified lines13 import {foobarString} from '../helpers/input.js';14 15 setFixtureDirectory();16 15-const testFileUrl = async (t, execaMethod) => {17+const 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 };22 21-test('execa()\'s command argument can be a file URL', testFileUrl, execa);22-test('execaSync()\'s command argument can be a file URL', testFileUrl, execaSync);23-test('execaNode()\'s command argument can be a file URL', testFileUrl, execaNode);24-test('$\'s command argument can be a file URL', testFileUrl, $);25-test('$.sync\'s command argument can be a file URL', testFileUrl, $.sync);23+test('execa()\'s command argument can be a file URL', () => testFileUrl(execa));24+test('execaSync()\'s command argument can be a file URL', () => testFileUrl(execaSync));25+test('execaNode()\'s command argument can be a file URL', () => testFileUrl(execaNode));26+test('$\'s command argument can be a file URL', () => testFileUrl($));27+test('$.sync\'s command argument can be a file URL', () => testFileUrl($.sync));28 27-const testInvalidFileUrl = async (t, execaMethod) => {29+const 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 };35 34-test('execa()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execa);35-test('execaSync()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaSync);36-test('execaNode()\'s command argument cannot be a non-file URL', testInvalidFileUrl, execaNode);37-test('$\'s command argument cannot be a non-file URL', testInvalidFileUrl, $);38-test('$.sync\'s command argument cannot be a non-file URL', testInvalidFileUrl, $.sync);36+test('execa()\'s command argument cannot be a non-file URL', () => testInvalidFileUrl(execa));37+test('execaSync()\'s command argument cannot be a non-file URL', () => testInvalidFileUrl(execaSync));38+test('execaNode()\'s command argument cannot be a non-file URL', () => testInvalidFileUrl(execaNode));39+test('$\'s command argument cannot be a non-file URL', () => testInvalidFileUrl($));40+test('$.sync\'s command argument cannot be a non-file URL', () => testInvalidFileUrl($.sync));41 40-const testInvalidCommand = async (t, commandArgument, execaMethod) => {41- t.throws(() => {42+const testInvalidCommand = async (commandArgument, execaMethod) => {43+ assertThrows(() => {44 execaMethod(commandArgument);45 }, {message: /First argument must be a string or a file URL/});46 };47 46-test('execa()\'s first argument must be defined', testInvalidCommand, undefined, execa);47-test('execaSync()\'s first argument must be defined', testInvalidCommand, undefined, execaSync);48-test('execaNode()\'s first argument must be defined', testInvalidCommand, undefined, execaNode);49-test('$\'s first argument must be defined', testInvalidCommand, undefined, $);50-test('$.sync\'s first argument must be defined', testInvalidCommand, undefined, $.sync);51-test('execa()\'s first argument must be valid', testInvalidCommand, true, execa);52-test('execaSync()\'s first argument must be valid', testInvalidCommand, true, execaSync);53-test('execaNode()\'s first argument must be valid', testInvalidCommand, true, execaNode);54-test('$\'s first argument must be valid', testInvalidCommand, true, $);55-test('$.sync\'s first argument must be valid', testInvalidCommand, true, $.sync);56-test('execa()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execa);57-test('execaSync()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaSync);58-test('execaNode()\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], execaNode);59-test('$\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $);60-test('$.sync\'s command argument must be a string or file URL', testInvalidCommand, ['command', 'arg'], $.sync);48+test('execa()\'s first argument must be defined', () => testInvalidCommand(undefined, execa));49+test('execaSync()\'s first argument must be defined', () => testInvalidCommand(undefined, execaSync));50+test('execaNode()\'s first argument must be defined', () => testInvalidCommand(undefined, execaNode));51+test('$\'s first argument must be defined', () => testInvalidCommand(undefined, $));52+test('$.sync\'s first argument must be defined', () => testInvalidCommand(undefined, $.sync));53+test('execa()\'s first argument must be valid', () => testInvalidCommand(true, execa));54+test('execaSync()\'s first argument must be valid', () => testInvalidCommand(true, execaSync));55+test('execaNode()\'s first argument must be valid', () => testInvalidCommand(true, execaNode));56+test('$\'s first argument must be valid', () => testInvalidCommand(true, $));57+test('$.sync\'s first argument must be valid', () => testInvalidCommand(true, $.sync));58+test('execa()\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], execa));59+test('execaSync()\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], execaSync));60+test('execaNode()\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], execaNode));61+test('$\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], $));62+test('$.sync\'s command argument must be a string or file URL', () => testInvalidCommand(['command', 'arg'], $.sync));63 62-const testRelativePath = async (t, execaMethod) => {64+const 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 };71 70-test('execa() use relative path with \'..\' chars', testRelativePath, execa);71-test('execaSync() use relative path with \'..\' chars', testRelativePath, execaSync);72-test('execaNode() use relative path with \'..\' chars', testRelativePath, execaNode);73-test('$ use relative path with \'..\' chars', testRelativePath, $);74-test('$.sync use relative path with \'..\' chars', testRelativePath, $.sync);72+test('execa() use relative path with \'..\' chars', () => testRelativePath(execa));73+test('execaSync() use relative path with \'..\' chars', () => testRelativePath(execaSync));74+test('execaNode() use relative path with \'..\' chars', () => testRelativePath(execaNode));75+test('$ use relative path with \'..\' chars', () => testRelativePath($));76+test('$.sync use relative path with \'..\' chars', () => testRelativePath($.sync));modified:test/methods/parameters-options.js+52 added-50 removed
1+import assert from 'node:assert/strict';2 import path from 'node:path';2-import test from 'ava';3+import test from 'node:test';4+import {assertThrows} from '../helpers/assert.js';5 import {6 execa,7 execaSync,8 execaNode,4 unmodified lines13 setFixtureDirectory();14 15 const NOOP_PATH = path.join(FIXTURES_DIRECTORY, 'noop.js');16 15-const testSerializeArgument = async (t, commandArgument, execaMethod) => {17+const 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 };21 20-test('execa()\'s arguments can be numbers', testSerializeArgument, 1, execa);21-test('execa()\'s arguments can be booleans', testSerializeArgument, true, execa);22-test('execa()\'s arguments can be NaN', testSerializeArgument, NaN, execa);23-test('execa()\'s arguments can be Infinity', testSerializeArgument, Infinity, execa);24-test('execa()\'s arguments can be null', testSerializeArgument, null, execa);25-test('execa()\'s arguments can be undefined', testSerializeArgument, undefined, execa);26-test('execa()\'s arguments can be bigints', testSerializeArgument, 1n, execa);27-test('execa()\'s arguments can be symbols', testSerializeArgument, Symbol('test'), execa);28-test('execaSync()\'s arguments can be numbers', testSerializeArgument, 1, execaSync);29-test('execaSync()\'s arguments can be booleans', testSerializeArgument, true, execaSync);30-test('execaSync()\'s arguments can be NaN', testSerializeArgument, NaN, execaSync);31-test('execaSync()\'s arguments can be Infinity', testSerializeArgument, Infinity, execaSync);32-test('execaSync()\'s arguments can be null', testSerializeArgument, null, execaSync);33-test('execaSync()\'s arguments can be undefined', testSerializeArgument, undefined, execaSync);34-test('execaSync()\'s arguments can be bigints', testSerializeArgument, 1n, execaSync);35-test('execaSync()\'s arguments can be symbols', testSerializeArgument, Symbol('test'), execaSync);36-test('execaNode()\'s arguments can be numbers', testSerializeArgument, 1, execaNode);37-test('execaNode()\'s arguments can be booleans', testSerializeArgument, true, execaNode);38-test('execaNode()\'s arguments can be NaN', testSerializeArgument, NaN, execaNode);39-test('execaNode()\'s arguments can be Infinity', testSerializeArgument, Infinity, execaNode);40-test('execaNode()\'s arguments can be null', testSerializeArgument, null, execaNode);41-test('execaNode()\'s arguments can be undefined', testSerializeArgument, undefined, execaNode);42-test('execaNode()\'s arguments can be bigints', testSerializeArgument, 1n, execaNode);43-test('execaNode()\'s arguments can be symbols', testSerializeArgument, Symbol('test'), execaNode);44-test('$\'s arguments can be numbers', testSerializeArgument, 1, $);45-test('$\'s arguments can be booleans', testSerializeArgument, true, $);46-test('$\'s arguments can be NaN', testSerializeArgument, NaN, $);47-test('$\'s arguments can be Infinity', testSerializeArgument, Infinity, $);48-test('$\'s arguments can be null', testSerializeArgument, null, $);49-test('$\'s arguments can be undefined', testSerializeArgument, undefined, $);50-test('$\'s arguments can be bigints', testSerializeArgument, 1n, $);51-test('$\'s arguments can be symbols', testSerializeArgument, Symbol('test'), $);52-test('$.sync\'s arguments can be numbers', testSerializeArgument, 1, $.sync);53-test('$.sync\'s arguments can be booleans', testSerializeArgument, true, $.sync);54-test('$.sync\'s arguments can be NaN', testSerializeArgument, NaN, $.sync);55-test('$.sync\'s arguments can be Infinity', testSerializeArgument, Infinity, $.sync);56-test('$.sync\'s arguments can be null', testSerializeArgument, null, $.sync);57-test('$.sync\'s arguments can be undefined', testSerializeArgument, undefined, $.sync);58-test('$.sync\'s arguments can be bigints', testSerializeArgument, 1n, $.sync);59-test('$.sync\'s arguments can be symbols', testSerializeArgument, Symbol('test'), $.sync);22+test('execa()\'s arguments can be numbers', () => testSerializeArgument(1, execa));23+test('execa()\'s arguments can be booleans', () => testSerializeArgument(true, execa));24+test('execa()\'s arguments can be NaN', () => testSerializeArgument(NaN, execa));25+test('execa()\'s arguments can be Infinity', () => testSerializeArgument(Infinity, execa));26+test('execa()\'s arguments can be null', () => testSerializeArgument(null, execa));27+test('execa()\'s arguments can be undefined', () => testSerializeArgument(undefined, execa));28+test('execa()\'s arguments can be bigints', () => testSerializeArgument(1n, execa));29+test('execa()\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), execa));30+test('execaSync()\'s arguments can be numbers', () => testSerializeArgument(1, execaSync));31+test('execaSync()\'s arguments can be booleans', () => testSerializeArgument(true, execaSync));32+test('execaSync()\'s arguments can be NaN', () => testSerializeArgument(NaN, execaSync));33+test('execaSync()\'s arguments can be Infinity', () => testSerializeArgument(Infinity, execaSync));34+test('execaSync()\'s arguments can be null', () => testSerializeArgument(null, execaSync));35+test('execaSync()\'s arguments can be undefined', () => testSerializeArgument(undefined, execaSync));36+test('execaSync()\'s arguments can be bigints', () => testSerializeArgument(1n, execaSync));37+test('execaSync()\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), execaSync));38+test('execaNode()\'s arguments can be numbers', () => testSerializeArgument(1, execaNode));39+test('execaNode()\'s arguments can be booleans', () => testSerializeArgument(true, execaNode));40+test('execaNode()\'s arguments can be NaN', () => testSerializeArgument(NaN, execaNode));41+test('execaNode()\'s arguments can be Infinity', () => testSerializeArgument(Infinity, execaNode));42+test('execaNode()\'s arguments can be null', () => testSerializeArgument(null, execaNode));43+test('execaNode()\'s arguments can be undefined', () => testSerializeArgument(undefined, execaNode));44+test('execaNode()\'s arguments can be bigints', () => testSerializeArgument(1n, execaNode));45+test('execaNode()\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), execaNode));46+test('$\'s arguments can be numbers', () => testSerializeArgument(1, $));47+test('$\'s arguments can be booleans', () => testSerializeArgument(true, $));48+test('$\'s arguments can be NaN', () => testSerializeArgument(NaN, $));49+test('$\'s arguments can be Infinity', () => testSerializeArgument(Infinity, $));50+test('$\'s arguments can be null', () => testSerializeArgument(null, $));51+test('$\'s arguments can be undefined', () => testSerializeArgument(undefined, $));52+test('$\'s arguments can be bigints', () => testSerializeArgument(1n, $));53+test('$\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), $));54+test('$.sync\'s arguments can be numbers', () => testSerializeArgument(1, $.sync));55+test('$.sync\'s arguments can be booleans', () => testSerializeArgument(true, $.sync));56+test('$.sync\'s arguments can be NaN', () => testSerializeArgument(NaN, $.sync));57+test('$.sync\'s arguments can be Infinity', () => testSerializeArgument(Infinity, $.sync));58+test('$.sync\'s arguments can be null', () => testSerializeArgument(null, $.sync));59+test('$.sync\'s arguments can be undefined', () => testSerializeArgument(undefined, $.sync));60+test('$.sync\'s arguments can be bigints', () => testSerializeArgument(1n, $.sync));61+test('$.sync\'s arguments can be symbols', () => testSerializeArgument(Symbol('test'), $.sync));62 61-const testInvalidOptions = async (t, execaMethod) => {62- t.throws(() => {63+const testInvalidOptions = async execaMethod => {64+ assertThrows(() => {65 execaMethod('echo', [], new Map());66 }, {message: /Last argument must be an options object/});67 };68 67-test('execa()\'s third argument must be a plain object', testInvalidOptions, execa);68-test('execaSync()\'s third argument must be a plain object', testInvalidOptions, execaSync);69-test('execaNode()\'s third argument must be a plain object', testInvalidOptions, execaNode);70-test('$\'s third argument must be a plain object', testInvalidOptions, $);71-test('$.sync\'s third argument must be a plain object', testInvalidOptions, $.sync);69+test('execa()\'s third argument must be a plain object', () => testInvalidOptions(execa));70+test('execaSync()\'s third argument must be a plain object', () => testInvalidOptions(execaSync));71+test('execaNode()\'s third argument must be a plain object', () => testInvalidOptions(execaNode));72+test('$\'s third argument must be a plain object', () => testInvalidOptions($));73+test('$.sync\'s third argument must be a plain object', () => testInvalidOptions($.sync));modified:test/methods/promise.js+23 added-21 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 7 setFixtureDirectory();8 7-test('subprocess properties are enumerable', t => {9+test('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 });13 12-test('finally function is executed on success', async t => {14+test('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 });22 21-test('finally function is executed on failure', async t => {23+test('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 });32 31-test('throw in finally function bubbles up on success', async t => {32- const {message} = await t.throwsAsync(execa('noop.js', ['foo']).finally(() => {33+test('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 });39 38-test('throw in finally bubbles up on error', async t => {39- const {message} = await t.throwsAsync(execa('exit.js', ['2']).finally(() => {40+test('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 });46 45-const testNoAwait = async (t, fixtureName, options, message) => {47+const 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 };51 50-test('Throws if promise is not awaited and subprocess fails', testNoAwait, 'fail.js', {}, 'exit code 2');51-test('Throws if promise is not awaited and subprocess times out', testNoAwait, 'forever.js', {timeout: 1}, 'timed out');52+test('Throws if promise is not awaited and subprocess fails', () => testNoAwait('fail.js', {}, 'exit code 2'));53+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {isStream} from 'is-stream';4 import {$} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString} from '../helpers/input.js';7 8 setFixtureDirectory();9 9-const testScriptStdoutSync = (t, getSubprocess, expectedStdout) => {10+const testScriptStdoutSync = (getSubprocess, expectedStdout) => {11 const {stdout} = getSubprocess();11- t.is(stdout, expectedStdout);12+ assert.equal(stdout, expectedStdout);13 };14 14-test('$.sync`...`', testScriptStdoutSync, () => $.sync`echo.js foo bar`, 'foo\nbar');15-test('$.s`...`', testScriptStdoutSync, () => $.s`echo.js foo bar`, 'foo\nbar');16-test('$(options).sync`...`', testScriptStdoutSync, () => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`);17-test('$.sync(options)`...`', testScriptStdoutSync, () => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`);15+test('$.sync`...`', () => testScriptStdoutSync(() => $.sync`echo.js foo bar`, 'foo\nbar'));16+test('$.s`...`', () => testScriptStdoutSync(() => $.s`echo.js foo bar`, 'foo\nbar'));17+test('$(options).sync`...`', () => testScriptStdoutSync(() => $({stripFinalNewline: false}).sync`echo.js ${foobarString}`, `${foobarString}\n`));18+test('$.sync(options)`...`', () => testScriptStdoutSync(() => $.sync({stripFinalNewline: false})`echo.js ${foobarString}`, `${foobarString}\n`));19 19-test('Cannot call $.sync.sync', t => {20- t.false('sync' in $.sync);20+test('Cannot call $.sync.sync', () => {21+ assert.equal('sync' in $.sync, false);22 });23 23-test('Cannot call $.sync(options).sync', t => {24- t.false('sync' in $.sync({}));24+test('Cannot call $.sync(options).sync', () => {25+ assert.equal('sync' in $.sync({}), false);26 });27 27-test('$(options)() stdin defaults to "inherit"', async t => {28+test('$(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 });32 32-test('$.sync(options)() stdin defaults to "inherit"', t => {33+test('$.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 });37 37-test('$(options).sync() stdin defaults to "inherit"', t => {38+test('$(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 });42 42-test('$(options)`...` stdin defaults to "inherit"', async t => {43+test('$(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 });47 47-test('$.sync(options)`...` stdin defaults to "inherit"', t => {48+test('$.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 });52 52-test('$(options).sync`...` stdin defaults to "inherit"', t => {53+test('$(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 });57 57-test('$ stdin has no default value when stdio is set', t => {58- t.true(isStream($({stdio: 'pipe'})`noop.js`.stdin));58+test('$ 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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows} from '../helpers/assert.js';4 import {$} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 7 setFixtureDirectory();4 unmodified lines12 templates.raw = [string];13 return $(templates);14 };15 14-const testScriptStdout = async (t, getSubprocess, expectedStdout) => {16+const testScriptStdout = async (getSubprocess, expectedStdout) => {17 const {stdout} = await getSubprocess();16- t.is(stdout, expectedStdout);18+ assert.equal(stdout, expectedStdout);19 };20 19-test('$ allows number interpolation', testScriptStdout, () => $`echo.js 1 ${2}`, '1\n2');20-test('$ can concatenate multiple tokens', testScriptStdout, () => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo');21-test('$ can use newlines and tab indentations', testScriptStdout, () => $`echo.js foo22- bar`, 'foo\nbar');23-test('$ can use newlines and space indentations', testScriptStdout, () => $`echo.js foo24- bar`, 'foo\nbar');25-test('$ can use escaped newlines and space indentations', testScriptStdout, () => $`echo.js foo\26- bar`, 'foo\nbar');27-test('$ can use escaped newlines and inline tab indentations', testScriptStdout, () => $`echo.js foo\28- bar`, 'foo\nbar');29-test('$ can use escaped newlines and character escaped tab indentations', testScriptStdout, () => $`echo.js foo\30-\tbar`, 'foo\tbar');31-test('$ can use escaped newlines and character escaped newlines', testScriptStdout, () => $`echo.js foo\32-\n\nbar`, 'foo\n\nbar');21+test('$ allows number interpolation', () => testScriptStdout(() => $`echo.js 1 ${2}`, '1\n2'));22+test('$ can concatenate multiple tokens', () => testScriptStdout(() => $`echo.js ${'foo'}bar${'foo'}`, 'foobarfoo'));23+test('$ can use newlines and tab indentations', () => testScriptStdout(() => $`echo.js foo24+ bar`, 'foo\nbar'));25+test('$ can use newlines and space indentations', () => testScriptStdout(() => $`echo.js foo26+ bar`, 'foo\nbar'));27+test('$ can use escaped newlines and space indentations', () => testScriptStdout(() => $`echo.js foo\28+ bar`, 'foo\nbar'));29+test('$ can use escaped newlines and inline tab indentations', () => testScriptStdout(() => $`echo.js foo\30+ bar`, 'foo\nbar'));31+test('$ can use escaped newlines and character escaped tab indentations', () => testScriptStdout(() => $`echo.js foo\32+\tbar`, 'foo\tbar'));33+test('$ 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.35-test('$ can use escaped newlines between tokens', testScriptStdout, () => $`echo.js foo\36-bar`, 'foobar');37-test('$ can use escaped newlines between expressions', testScriptStdout, () => $`echo.js ${'foo'}\38-${'bar'}`, 'foobar');39-test('$ can use multiple escaped newlines between expressions', testScriptStdout, () => $`echo.js ${'foo'}\37+test('$ can use escaped newlines between tokens', () => testScriptStdout(() => $`echo.js foo\38+bar`, 'foobar'));39+test('$ can use escaped newlines between expressions', () => testScriptStdout(() => $`echo.js ${'foo'}\40+${'bar'}`, 'foobar'));41+test('$ can use multiple escaped newlines between expressions', () => testScriptStdout(() => $`echo.js ${'foo'}\42 \41-${'bar'}`, 'foobar');42-test('$ can use escaped newlines and space indentations between expressions', testScriptStdout, () => $`echo.js ${'foo'}\43- ${'bar'}`, 'foo\nbar');44-test('$ can use escaped newlines and tab indentations between expressions', testScriptStdout, () => $`echo.js ${'foo'}\45- ${'bar'}`, 'foo\nbar');46-test('$ can use escaped newlines and space indentations after an expression', testScriptStdout, () => $`echo.js ${'foo'}\47- bar`, 'foo\nbar');48-test('$ can use escaped newlines and tab indentations after an expression', testScriptStdout, () => $`echo.js ${'foo'}\49- bar`, 'foo\nbar');50-test('$ can use escaped newlines before an expression', testScriptStdout, () => $`echo.js foo\51-${'bar'}`, 'foobar');52-test('$ can use Windows newlines and tab indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar');53-test('$ can use Windows newlines and space indentations', testScriptStdout, () => escapedCall('echo.js foo\r\n bar'), 'foo\nbar');54-test('$ does not ignore comments in expressions', testScriptStdout, () => $`echo.js foo43+${'bar'}`, 'foobar'));44+test('$ can use escaped newlines and space indentations between expressions', () => testScriptStdout(() => $`echo.js ${'foo'}\45+ ${'bar'}`, 'foo\nbar'));46+test('$ can use escaped newlines and tab indentations between expressions', () => testScriptStdout(() => $`echo.js ${'foo'}\47+ ${'bar'}`, 'foo\nbar'));48+test('$ can use escaped newlines and space indentations after an expression', () => testScriptStdout(() => $`echo.js ${'foo'}\49+ bar`, 'foo\nbar'));50+test('$ can use escaped newlines and tab indentations after an expression', () => testScriptStdout(() => $`echo.js ${'foo'}\51+ bar`, 'foo\nbar'));52+test('$ can use escaped newlines before an expression', () => testScriptStdout(() => $`echo.js foo\53+${'bar'}`, 'foobar'));54+test('$ can use Windows newlines and tab indentations', () => testScriptStdout(() => escapedCall('echo.js foo\r\n\tbar'), 'foo\nbar'));55+test('$ can use Windows newlines and space indentations', () => testScriptStdout(() => escapedCall('echo.js foo\r\n bar'), 'foo\nbar'));56+test('$ 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');60-test('$ allows escaping spaces with interpolation', testScriptStdout, () => $`echo.js ${'foo bar'}`, 'foo bar');61-test('$ allows escaping spaces in commands with interpolation', testScriptStdout, () => $`${'command with space.js'} foo bar`, 'foo\nbar');62-test('$ trims', testScriptStdout, () => $` echo.js foo bar `, 'foo\nbar');63-test('$ allows array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar']}`, 'foo\nbar');64-test('$ allows empty array interpolation', testScriptStdout, () => $`echo.js foo ${[]} bar`, 'foo\nbar');65-test('$ allows space escaped values in array interpolation', testScriptStdout, () => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz');66-test('$ can concatenate at the end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo');67-test('$ can concatenate at the start of tokens followed by an array', testScriptStdout, () => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo');68-test('$ can concatenate at the start and end of tokens followed by an array', testScriptStdout, () => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar');69-test('$ handles escaped newlines', testScriptStdout, () => $`echo.js a\70-b`, 'ab');71-test('$ handles backslashes at end of lines', testScriptStdout, () => $`echo.js a\\72- b`, 'a\\\nb');73-test('$ handles double backslashes at end of lines', testScriptStdout, () => $`echo.js a\\\\74- b`, 'a\\\\\nb');75-test('$ handles tokens - a', testScriptStdout, () => $`echo.js a`, 'a');76-test('$ handles expressions - a', testScriptStdout, () => $`echo.js ${'a'}`, 'a');77-test('$ handles tokens - abc', testScriptStdout, () => $`echo.js abc`, 'abc');78-test('$ handles expressions - abc', testScriptStdout, () => $`echo.js ${'abc'}`, 'abc');79-test('$ handles tokens - ""', testScriptStdout, () => $`echo.js`, '');80-test('$ handles expressions - ""', testScriptStdout, () => $`echo.js a ${''} b`, 'a\n\nb');81-test('$ splits tokens - ""', testScriptStdout, () => $`echo.js ab`, 'ab');82-test('$ splits expressions - ""', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'ab');83-test('$ concatenates expressions - ""', testScriptStdout, () => $`echo.js a${'b'}c`, 'abc');84-test('$ handles tokens - " "', testScriptStdout, () => $`echo.js `, '');85-test('$ handles expressions - " "', testScriptStdout, () => $`echo.js ${' '}`, ' ');86-test('$ splits tokens - " "', testScriptStdout, () => $`echo.js a b`, 'a\nb');87-test('$ splits expressions - " "', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');88-test('$ concatenates tokens - " "', testScriptStdout, () => $`echo.js a `, 'a');89-test('$ concatenates expressions - " "', testScriptStdout, () => $`echo.js ${'a'} `, 'a');90-test('$ handles tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js `, '');91-test('$ handles expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');92-test('$ splits tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');93-test('$ splits expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');94-test('$ concatenates tokens - " " (2 spaces)', testScriptStdout, () => $`echo.js a `, 'a');95-test('$ concatenates expressions - " " (2 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');96-test('$ handles tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js `, '');61+`, 'foo\n\nbar\n\nbaz'));62+test('$ allows escaping spaces with interpolation', () => testScriptStdout(() => $`echo.js ${'foo bar'}`, 'foo bar'));63+test('$ allows escaping spaces in commands with interpolation', () => testScriptStdout(() => $`${'command with space.js'} foo bar`, 'foo\nbar'));64+test('$ trims', () => testScriptStdout(() => $` echo.js foo bar `, 'foo\nbar'));65+test('$ allows array interpolation', () => testScriptStdout(() => $`echo.js ${['foo', 'bar']}`, 'foo\nbar'));66+test('$ allows empty array interpolation', () => testScriptStdout(() => $`echo.js foo ${[]} bar`, 'foo\nbar'));67+test('$ allows space escaped values in array interpolation', () => testScriptStdout(() => $`echo.js ${['foo', 'bar baz']}`, 'foo\nbar baz'));68+test('$ can concatenate at the end of tokens followed by an array', () => testScriptStdout(() => $`echo.js foo${['bar', 'foo']}`, 'foobar\nfoo'));69+test('$ can concatenate at the start of tokens followed by an array', () => testScriptStdout(() => $`echo.js ${['foo', 'bar']}foo`, 'foo\nbarfoo'));70+test('$ can concatenate at the start and end of tokens followed by an array', () => testScriptStdout(() => $`echo.js foo${['bar', 'foo']}bar`, 'foobar\nfoobar'));71+test('$ handles escaped newlines', () => testScriptStdout(() => $`echo.js a\72+b`, 'ab'));73+test('$ handles backslashes at end of lines', () => testScriptStdout(() => $`echo.js a\\74+ b`, 'a\\\nb'));75+test('$ handles double backslashes at end of lines', () => testScriptStdout(() => $`echo.js a\\\\76+ b`, 'a\\\\\nb'));77+test('$ handles tokens - a', () => testScriptStdout(() => $`echo.js a`, 'a'));78+test('$ handles expressions - a', () => testScriptStdout(() => $`echo.js ${'a'}`, 'a'));79+test('$ handles tokens - abc', () => testScriptStdout(() => $`echo.js abc`, 'abc'));80+test('$ handles expressions - abc', () => testScriptStdout(() => $`echo.js ${'abc'}`, 'abc'));81+test('$ handles tokens - ""', () => testScriptStdout(() => $`echo.js`, ''));82+test('$ handles expressions - ""', () => testScriptStdout(() => $`echo.js a ${''} b`, 'a\n\nb'));83+test('$ splits tokens - ""', () => testScriptStdout(() => $`echo.js ab`, 'ab'));84+test('$ splits expressions - ""', () => testScriptStdout(() => $`echo.js ${'a'}${'b'}`, 'ab'));85+test('$ concatenates expressions - ""', () => testScriptStdout(() => $`echo.js a${'b'}c`, 'abc'));86+test('$ handles tokens - " "', () => testScriptStdout(() => $`echo.js `, ''));87+test('$ handles expressions - " "', () => testScriptStdout(() => $`echo.js ${' '}`, ' '));88+test('$ splits tokens - " "', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));89+test('$ splits expressions - " "', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\nb'));90+test('$ concatenates tokens - " "', () => testScriptStdout(() => $`echo.js a `, 'a'));91+test('$ concatenates expressions - " "', () => testScriptStdout(() => $`echo.js ${'a'} `, 'a'));92+test('$ handles tokens - " " (2 spaces)', () => testScriptStdout(() => $`echo.js `, ''));93+test('$ handles expressions - " " (2 spaces)', () => testScriptStdout(() => $`echo.js ${' '}`, ' '));94+test('$ splits tokens - " " (2 spaces)', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));95+test('$ splits expressions - " " (2 spaces)', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\nb'));96+test('$ concatenates tokens - " " (2 spaces)', () => testScriptStdout(() => $`echo.js a `, 'a'));97+test('$ concatenates expressions - " " (2 spaces)', () => testScriptStdout(() => $`echo.js ${'a'} `, 'a'));98+test('$ handles tokens - " " (3 spaces)', () => testScriptStdout(() => $`echo.js `, ''));99 // eslint-disable-next-line unicorn/prefer-string-repeat98-test('$ handles expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${' '}`, ' ');99-test('$ splits tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a b`, 'a\nb');100-test('$ splits expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');101-test('$ concatenates tokens - " " (3 spaces)', testScriptStdout, () => $`echo.js a `, 'a');102-test('$ concatenates expressions - " " (3 spaces)', testScriptStdout, () => $`echo.js ${'a'} `, 'a');103-test('$ handles tokens - \\t (no escape)', testScriptStdout, () => $`echo.js `, '');104-test('$ handles expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${' '}`, '\t');105-test('$ splits tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');106-test('$ splits expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} ${'b'}`, 'a\nb');107-test('$ concatenates tokens - \\t (no escape)', testScriptStdout, () => $`echo.js a b`, 'a\nb');108-test('$ concatenates expressions - \\t (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, 'a\nb');109-test('$ handles tokens - \\t (escape)', testScriptStdout, () => $`echo.js \t`, '\t');110-test('$ handles expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'\t'}`, '\t');111-test('$ splits tokens - \\t (escape)', testScriptStdout, () => $`echo.js a\tb`, 'a\tb');112-test('$ splits expressions - \\t (escape)', testScriptStdout, () => $`echo.js ${'a'}\t${'b'}`, 'a\tb');113-test('$ concatenates tokens - \\t (escape)', testScriptStdout, () => $`echo.js \ta\t b`, '\ta\t\nb');114-test('$ concatenates expressions - \\t (escape)', testScriptStdout, () => $`echo.js \t${'a'}\t b`, '\ta\t\nb');115-test('$ handles tokens - \\n (no escape)', testScriptStdout, () => $`echo.js116- `, '');117-test('$ handles expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${`118-`} `, '\n');119-test('$ splits tokens - \\n (no escape)', testScriptStdout, () => $`echo.js a120- b`, 'a\nb');121-test('$ splits expressions - \\n (no escape)', testScriptStdout, () => $`echo.js ${'a'}122- ${'b'}`, 'a\nb');123-test('$ concatenates tokens - \\n (no escape)', testScriptStdout, () => $`echo.js100+test('$ handles expressions - " " (3 spaces)', () => testScriptStdout(() => $`echo.js ${' '}`, ' '));101+test('$ splits tokens - " " (3 spaces)', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));102+test('$ splits expressions - " " (3 spaces)', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\nb'));103+test('$ concatenates tokens - " " (3 spaces)', () => testScriptStdout(() => $`echo.js a `, 'a'));104+test('$ concatenates expressions - " " (3 spaces)', () => testScriptStdout(() => $`echo.js ${'a'} `, 'a'));105+test('$ handles tokens - \\t (no escape)', () => testScriptStdout(() => $`echo.js `, ''));106+test('$ handles expressions - \\t (no escape)', () => testScriptStdout(() => $`echo.js ${' '}`, '\t'));107+test('$ splits tokens - \\t (no escape)', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));108+test('$ splits expressions - \\t (no escape)', () => testScriptStdout(() => $`echo.js ${'a'} ${'b'}`, 'a\nb'));109+test('$ concatenates tokens - \\t (no escape)', () => testScriptStdout(() => $`echo.js a b`, 'a\nb'));110+test('$ concatenates expressions - \\t (no escape)', () => testScriptStdout(() => $`echo.js ${'a'} b`, 'a\nb'));111+test('$ handles tokens - \\t (escape)', () => testScriptStdout(() => $`echo.js \t`, '\t'));112+test('$ handles expressions - \\t (escape)', () => testScriptStdout(() => $`echo.js ${'\t'}`, '\t'));113+test('$ splits tokens - \\t (escape)', () => testScriptStdout(() => $`echo.js a\tb`, 'a\tb'));114+test('$ splits expressions - \\t (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\t${'b'}`, 'a\tb'));115+test('$ concatenates tokens - \\t (escape)', () => testScriptStdout(() => $`echo.js \ta\t b`, '\ta\t\nb'));116+test('$ concatenates expressions - \\t (escape)', () => testScriptStdout(() => $`echo.js \t${'a'}\t b`, '\ta\t\nb'));117+test('$ handles tokens - \\n (no escape)', () => testScriptStdout(() => $`echo.js118+ `, ''));119+test('$ handles expressions - \\n (no escape)', () => testScriptStdout(() => $`echo.js ${`120+`} `, '\n'));121+test('$ splits tokens - \\n (no escape)', () => testScriptStdout(() => $`echo.js a122+ b`, 'a\nb'));123+test('$ splits expressions - \\n (no escape)', () => testScriptStdout(() => $`echo.js ${'a'}124+ ${'b'}`, 'a\nb'));125+test('$ concatenates tokens - \\n (no escape)', () => testScriptStdout(() => $`echo.js126 a125- b`, 'a\nb');126-test('$ concatenates expressions - \\n (no escape)', testScriptStdout, () => $`echo.js127+ b`, 'a\nb'));128+test('$ concatenates expressions - \\n (no escape)', () => testScriptStdout(() => $`echo.js129 ${'a'}128- b`, 'a\nb');129-test('$ handles tokens - \\n (escape)', testScriptStdout, () => $`echo.js \n `, '\n');130-test('$ handles expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'\n'} `, '\n');131-test('$ splits tokens - \\n (escape)', testScriptStdout, () => $`echo.js a\n b`, 'a\n\nb');132-test('$ splits expressions - \\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb');133-test('$ concatenates tokens - \\n (escape)', testScriptStdout, () => $`echo.js \na\n b`, '\na\n\nb');134-test('$ concatenates expressions - \\n (escape)', testScriptStdout, () => $`echo.js \n${'a'}\n b`, '\na\n\nb');135-test('$ handles tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \r '), '');136-test('$ splits tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');137-test('$ splits expressions - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js a\rb'), 'a\nb');138-test('$ concatenates tokens - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');139-test('$ concatenates expressions - \\r (no escape)', testScriptStdout, () => escapedCall('echo.js \ra\r b'), 'a\nb');140-test('$ splits tokens - \\r (escape)', testScriptStdout, () => $`echo.js a\r b`, 'a\r\nb');141-test('$ splits expressions - \\r (escape)', testScriptStdout, () => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb');142-test('$ concatenates tokens - \\r (escape)', testScriptStdout, () => $`echo.js \ra\r b`, '\ra\r\nb');143-test('$ concatenates expressions - \\r (escape)', testScriptStdout, () => $`echo.js \r${'a'}\r b`, '\ra\r\nb');144-test('$ handles tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\n '), '');145-test('$ splits tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');146-test('$ splits expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js a\r\nb'), 'a\nb');147-test('$ concatenates tokens - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');148-test('$ concatenates expressions - \\r\\n (no escape)', testScriptStdout, () => escapedCall('echo.js \r\na\r\n b'), 'a\nb');149-test('$ handles tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n `, '\r\n');150-test('$ handles expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'\r\n'} `, '\r\n');151-test('$ splits tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js a\r\n b`, 'a\r\n\nb');152-test('$ splits expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb');153-test('$ concatenates tokens - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb');154-test('$ concatenates expressions - \\r\\n (escape)', testScriptStdout, () => $`echo.js \r\n${'a'}\r\n b`, '\r\na\r\n\nb');130+ b`, 'a\nb'));131+test('$ handles tokens - \\n (escape)', () => testScriptStdout(() => $`echo.js \n `, '\n'));132+test('$ handles expressions - \\n (escape)', () => testScriptStdout(() => $`echo.js ${'\n'} `, '\n'));133+test('$ splits tokens - \\n (escape)', () => testScriptStdout(() => $`echo.js a\n b`, 'a\n\nb'));134+test('$ splits expressions - \\n (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\n ${'b'}`, 'a\n\nb'));135+test('$ concatenates tokens - \\n (escape)', () => testScriptStdout(() => $`echo.js \na\n b`, '\na\n\nb'));136+test('$ concatenates expressions - \\n (escape)', () => testScriptStdout(() => $`echo.js \n${'a'}\n b`, '\na\n\nb'));137+test('$ handles tokens - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js \r '), ''));138+test('$ splits tokens - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js a\rb'), 'a\nb'));139+test('$ splits expressions - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js a\rb'), 'a\nb'));140+test('$ concatenates tokens - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js \ra\r b'), 'a\nb'));141+test('$ concatenates expressions - \\r (no escape)', () => testScriptStdout(() => escapedCall('echo.js \ra\r b'), 'a\nb'));142+test('$ splits tokens - \\r (escape)', () => testScriptStdout(() => $`echo.js a\r b`, 'a\r\nb'));143+test('$ splits expressions - \\r (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\r ${'b'}`, 'a\r\nb'));144+test('$ concatenates tokens - \\r (escape)', () => testScriptStdout(() => $`echo.js \ra\r b`, '\ra\r\nb'));145+test('$ concatenates expressions - \\r (escape)', () => testScriptStdout(() => $`echo.js \r${'a'}\r b`, '\ra\r\nb'));146+test('$ handles tokens - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js \r\n '), ''));147+test('$ splits tokens - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js a\r\nb'), 'a\nb'));148+test('$ splits expressions - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js a\r\nb'), 'a\nb'));149+test('$ concatenates tokens - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js \r\na\r\n b'), 'a\nb'));150+test('$ concatenates expressions - \\r\\n (no escape)', () => testScriptStdout(() => escapedCall('echo.js \r\na\r\n b'), 'a\nb'));151+test('$ handles tokens - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js \r\n `, '\r\n'));152+test('$ handles expressions - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js ${'\r\n'} `, '\r\n'));153+test('$ splits tokens - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js a\r\n b`, 'a\r\n\nb'));154+test('$ splits expressions - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\r\n ${'b'}`, 'a\r\n\nb'));155+test('$ concatenates tokens - \\r\\n (escape)', () => testScriptStdout(() => $`echo.js \r\na\r\n b`, '\r\na\r\n\nb'));156+test('$ 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 */156-test('$ handles expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${''}`, '\f');157-test('$ splits tokens - \\f (no escape)', testScriptStdout, () => $`echo.js ab`, 'a\fb');158-test('$ splits expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'}${'b'}`, 'a\fb');159-test('$ concatenates tokens - \\f (no escape)', testScriptStdout, () => $`echo.js a b`, '\fa\f\nb');160-test('$ concatenates expressions - \\f (no escape)', testScriptStdout, () => $`echo.js ${'a'} b`, '\fa\f\nb');158+test('$ handles expressions - \\f (no escape)', () => testScriptStdout(() => $`echo.js ${''}`, '\f'));159+test('$ splits tokens - \\f (no escape)', () => testScriptStdout(() => $`echo.js ab`, 'a\fb'));160+test('$ splits expressions - \\f (no escape)', () => testScriptStdout(() => $`echo.js ${'a'}${'b'}`, 'a\fb'));161+test('$ concatenates tokens - \\f (no escape)', () => testScriptStdout(() => $`echo.js a b`, '\fa\f\nb'));162+test('$ concatenates expressions - \\f (no escape)', () => testScriptStdout(() => $`echo.js ${'a'} b`, '\fa\f\nb'));163 /* eslint-enable no-irregular-whitespace */162-test('$ handles tokens - \\f (escape)', testScriptStdout, () => $`echo.js \f`, '\f');163-test('$ handles expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'\f'}`, '\f');164-test('$ splits tokens - \\f (escape)', testScriptStdout, () => $`echo.js a\fb`, 'a\fb');165-test('$ splits expressions - \\f (escape)', testScriptStdout, () => $`echo.js ${'a'}\f${'b'}`, 'a\fb');166-test('$ concatenates tokens - \\f (escape)', testScriptStdout, () => $`echo.js \fa\f b`, '\fa\f\nb');167-test('$ concatenates expressions - \\f (escape)', testScriptStdout, () => $`echo.js \f${'a'}\f b`, '\fa\f\nb');168-test('$ handles tokens - \\', testScriptStdout, () => $`echo.js \\`, '\\');169-test('$ handles expressions - \\', testScriptStdout, () => $`echo.js ${'\\'}`, '\\');170-test('$ splits tokens - \\', testScriptStdout, () => $`echo.js a\\b`, 'a\\b');171-test('$ splits expressions - \\', testScriptStdout, () => $`echo.js ${'a'}\\${'b'}`, 'a\\b');172-test('$ concatenates tokens - \\', testScriptStdout, () => $`echo.js \\a\\ b`, '\\a\\\nb');173-test('$ concatenates expressions - \\', testScriptStdout, () => $`echo.js \\${'a'}\\ b`, '\\a\\\nb');174-test('$ handles tokens - \\\\', testScriptStdout, () => $`echo.js \\\\`, '\\\\');175-test('$ handles expressions - \\\\', testScriptStdout, () => $`echo.js ${'\\\\'}`, '\\\\');176-test('$ splits tokens - \\\\', testScriptStdout, () => $`echo.js a\\\\b`, 'a\\\\b');177-test('$ splits expressions - \\\\', testScriptStdout, () => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b');178-test('$ concatenates tokens - \\\\', testScriptStdout, () => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb');179-test('$ concatenates expressions - \\\\', testScriptStdout, () => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb');180-test('$ handles tokens - `', testScriptStdout, () => $`echo.js \``, '`');181-test('$ handles expressions - `', testScriptStdout, () => $`echo.js ${'`'}`, '`');182-test('$ splits tokens - `', testScriptStdout, () => $`echo.js a\`b`, 'a`b');183-test('$ splits expressions - `', testScriptStdout, () => $`echo.js ${'a'}\`${'b'}`, 'a`b');184-test('$ concatenates tokens - `', testScriptStdout, () => $`echo.js \`a\` b`, '`a`\nb');185-test('$ concatenates expressions - `', testScriptStdout, () => $`echo.js \`${'a'}\` b`, '`a`\nb');186-test('$ handles tokens - \\v', testScriptStdout, () => $`echo.js \v`, '\v');187-test('$ handles expressions - \\v', testScriptStdout, () => $`echo.js ${'\v'}`, '\v');188-test('$ splits tokens - \\v', testScriptStdout, () => $`echo.js a\vb`, 'a\vb');189-test('$ splits expressions - \\v', testScriptStdout, () => $`echo.js ${'a'}\v${'b'}`, 'a\vb');190-test('$ concatenates tokens - \\v', testScriptStdout, () => $`echo.js \va\v b`, '\va\v\nb');191-test('$ concatenates expressions - \\v', testScriptStdout, () => $`echo.js \v${'a'}\v b`, '\va\v\nb');192-test('$ handles tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028`, '\u{2028}');193-test('$ handles expressions - \\u2028', testScriptStdout, () => $`echo.js ${'\u{2028}'}`, '\u{2028}');194-test('$ splits tokens - \\u2028', testScriptStdout, () => $`echo.js a\u2028b`, 'a\u{2028}b');195-test('$ splits expressions - \\u2028', testScriptStdout, () => $`echo.js ${'a'}\u2028${'b'}`, 'a\u{2028}b');196-test('$ concatenates tokens - \\u2028', testScriptStdout, () => $`echo.js \u2028a\u2028 b`, '\u{2028}a\u{2028}\nb');197-test('$ concatenates expressions - \\u2028', testScriptStdout, () => $`echo.js \u2028${'a'}\u2028 b`, '\u{2028}a\u{2028}\nb');198-test('$ handles tokens - \\a', testScriptStdout, () => $`echo.js \a`, 'a');199-test('$ splits tokens - \\a', testScriptStdout, () => $`echo.js a\ab`, 'aab');200-test('$ splits expressions - \\a', testScriptStdout, () => $`echo.js ${'a'}\a${'b'}`, 'aab');201-test('$ concatenates tokens - \\a', testScriptStdout, () => $`echo.js \aa\a b`, 'aaa\nb');202-test('$ concatenates expressions - \\a', testScriptStdout, () => $`echo.js \a${'a'}\a b`, 'aaa\nb');203-test('$ handles tokens - \\cJ', testScriptStdout, () => $`echo.js \cJ`, 'cJ');204-test('$ splits tokens - \\cJ', testScriptStdout, () => $`echo.js a\cJb`, 'acJb');205-test('$ splits expressions - \\cJ', testScriptStdout, () => $`echo.js ${'a'}\cJ${'b'}`, 'acJb');206-test('$ concatenates tokens - \\cJ', testScriptStdout, () => $`echo.js \cJa\cJ b`, 'cJacJ\nb');207-test('$ concatenates expressions - \\cJ', testScriptStdout, () => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb');208-test('$ handles tokens - \\.', testScriptStdout, () => $`echo.js \.`, '.');209-test('$ splits tokens - \\.', testScriptStdout, () => $`echo.js a\.b`, 'a.b');210-test('$ splits expressions - \\.', testScriptStdout, () => $`echo.js ${'a'}\.${'b'}`, 'a.b');211-test('$ concatenates tokens - \\.', testScriptStdout, () => $`echo.js \.a\. b`, '.a.\nb');212-test('$ concatenates expressions - \\.', testScriptStdout, () => $`echo.js \.${'a'}\. b`, '.a.\nb');164+test('$ handles tokens - \\f (escape)', () => testScriptStdout(() => $`echo.js \f`, '\f'));165+test('$ handles expressions - \\f (escape)', () => testScriptStdout(() => $`echo.js ${'\f'}`, '\f'));166+test('$ splits tokens - \\f (escape)', () => testScriptStdout(() => $`echo.js a\fb`, 'a\fb'));167+test('$ splits expressions - \\f (escape)', () => testScriptStdout(() => $`echo.js ${'a'}\f${'b'}`, 'a\fb'));168+test('$ concatenates tokens - \\f (escape)', () => testScriptStdout(() => $`echo.js \fa\f b`, '\fa\f\nb'));169+test('$ concatenates expressions - \\f (escape)', () => testScriptStdout(() => $`echo.js \f${'a'}\f b`, '\fa\f\nb'));170+test('$ handles tokens - \\', () => testScriptStdout(() => $`echo.js \\`, '\\'));171+test('$ handles expressions - \\', () => testScriptStdout(() => $`echo.js ${'\\'}`, '\\'));172+test('$ splits tokens - \\', () => testScriptStdout(() => $`echo.js a\\b`, 'a\\b'));173+test('$ splits expressions - \\', () => testScriptStdout(() => $`echo.js ${'a'}\\${'b'}`, 'a\\b'));174+test('$ concatenates tokens - \\', () => testScriptStdout(() => $`echo.js \\a\\ b`, '\\a\\\nb'));175+test('$ concatenates expressions - \\', () => testScriptStdout(() => $`echo.js \\${'a'}\\ b`, '\\a\\\nb'));176+test('$ handles tokens - \\\\', () => testScriptStdout(() => $`echo.js \\\\`, '\\\\'));177+test('$ handles expressions - \\\\', () => testScriptStdout(() => $`echo.js ${'\\\\'}`, '\\\\'));178+test('$ splits tokens - \\\\', () => testScriptStdout(() => $`echo.js a\\\\b`, 'a\\\\b'));179+test('$ splits expressions - \\\\', () => testScriptStdout(() => $`echo.js ${'a'}\\\\${'b'}`, 'a\\\\b'));180+test('$ concatenates tokens - \\\\', () => testScriptStdout(() => $`echo.js \\\\a\\\\ b`, '\\\\a\\\\\nb'));181+test('$ concatenates expressions - \\\\', () => testScriptStdout(() => $`echo.js \\\\${'a'}\\\\ b`, '\\\\a\\\\\nb'));182+test('$ handles tokens - `', () => testScriptStdout(() => $`echo.js \``, '`'));183+test('$ handles expressions - `', () => testScriptStdout(() => $`echo.js ${'`'}`, '`'));184+test('$ splits tokens - `', () => testScriptStdout(() => $`echo.js a\`b`, 'a`b'));185+test('$ splits expressions - `', () => testScriptStdout(() => $`echo.js ${'a'}\`${'b'}`, 'a`b'));186+test('$ concatenates tokens - `', () => testScriptStdout(() => $`echo.js \`a\` b`, '`a`\nb'));187+test('$ concatenates expressions - `', () => testScriptStdout(() => $`echo.js \`${'a'}\` b`, '`a`\nb'));188+test('$ handles tokens - \\v', () => testScriptStdout(() => $`echo.js \v`, '\v'));189+test('$ handles expressions - \\v', () => testScriptStdout(() => $`echo.js ${'\v'}`, '\v'));190+test('$ splits tokens - \\v', () => testScriptStdout(() => $`echo.js a\vb`, 'a\vb'));191+test('$ splits expressions - \\v', () => testScriptStdout(() => $`echo.js ${'a'}\v${'b'}`, 'a\vb'));192+test('$ concatenates tokens - \\v', () => testScriptStdout(() => $`echo.js \va\v b`, '\va\v\nb'));193+test('$ concatenates expressions - \\v', () => testScriptStdout(() => $`echo.js \v${'a'}\v b`, '\va\v\nb'));194+test('$ handles tokens - \\u2028', () => testScriptStdout(() => $`echo.js \u2028`, '\u{2028}'));195+test('$ handles expressions - \\u2028', () => testScriptStdout(() => $`echo.js ${'\u{2028}'}`, '\u{2028}'));196+test('$ splits tokens - \\u2028', () => testScriptStdout(() => $`echo.js a\u2028b`, 'a\u{2028}b'));197+test('$ splits expressions - \\u2028', () => testScriptStdout(() => $`echo.js ${'a'}\u2028${'b'}`, 'a\u{2028}b'));198+test('$ concatenates tokens - \\u2028', () => testScriptStdout(() => $`echo.js \u2028a\u2028 b`, '\u{2028}a\u{2028}\nb'));199+test('$ concatenates expressions - \\u2028', () => testScriptStdout(() => $`echo.js \u2028${'a'}\u2028 b`, '\u{2028}a\u{2028}\nb'));200+test('$ handles tokens - \\a', () => testScriptStdout(() => $`echo.js \a`, 'a'));201+test('$ splits tokens - \\a', () => testScriptStdout(() => $`echo.js a\ab`, 'aab'));202+test('$ splits expressions - \\a', () => testScriptStdout(() => $`echo.js ${'a'}\a${'b'}`, 'aab'));203+test('$ concatenates tokens - \\a', () => testScriptStdout(() => $`echo.js \aa\a b`, 'aaa\nb'));204+test('$ concatenates expressions - \\a', () => testScriptStdout(() => $`echo.js \a${'a'}\a b`, 'aaa\nb'));205+test('$ handles tokens - \\cJ', () => testScriptStdout(() => $`echo.js \cJ`, 'cJ'));206+test('$ splits tokens - \\cJ', () => testScriptStdout(() => $`echo.js a\cJb`, 'acJb'));207+test('$ splits expressions - \\cJ', () => testScriptStdout(() => $`echo.js ${'a'}\cJ${'b'}`, 'acJb'));208+test('$ concatenates tokens - \\cJ', () => testScriptStdout(() => $`echo.js \cJa\cJ b`, 'cJacJ\nb'));209+test('$ concatenates expressions - \\cJ', () => testScriptStdout(() => $`echo.js \cJ${'a'}\cJ b`, 'cJacJ\nb'));210+test('$ handles tokens - \\.', () => testScriptStdout(() => $`echo.js \.`, '.'));211+test('$ splits tokens - \\.', () => testScriptStdout(() => $`echo.js a\.b`, 'a.b'));212+test('$ splits expressions - \\.', () => testScriptStdout(() => $`echo.js ${'a'}\.${'b'}`, 'a.b'));213+test('$ concatenates tokens - \\.', () => testScriptStdout(() => $`echo.js \.a\. b`, '.a.\nb'));214+test('$ concatenates expressions - \\.', () => testScriptStdout(() => $`echo.js \.${'a'}\. b`, '.a.\nb'));215 214-test('$ handles tokens - \\x63', testScriptStdout, () => $`echo.js \x63`, 'c');215-test('$ splits tokens - \\x63', testScriptStdout, () => $`echo.js a\x63b`, 'acb');216-test('$ splits expressions - \\x63', testScriptStdout, () => $`echo.js ${'a'}\x63${'b'}`, 'acb');217-test('$ concatenates tokens - \\x63', testScriptStdout, () => $`echo.js \x63a\x63 b`, 'cac\nb');218-test('$ concatenates expressions - \\x63', testScriptStdout, () => $`echo.js \x63${'a'}\x63 b`, 'cac\nb');216+test('$ handles tokens - \\x63', () => testScriptStdout(() => $`echo.js \x63`, 'c'));217+test('$ splits tokens - \\x63', () => testScriptStdout(() => $`echo.js a\x63b`, 'acb'));218+test('$ splits expressions - \\x63', () => testScriptStdout(() => $`echo.js ${'a'}\x63${'b'}`, 'acb'));219+test('$ concatenates tokens - \\x63', () => testScriptStdout(() => $`echo.js \x63a\x63 b`, 'cac\nb'));220+test('$ concatenates expressions - \\x63', () => testScriptStdout(() => $`echo.js \x63${'a'}\x63 b`, 'cac\nb'));221 220-test('$ handles tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063`, 'c');221-test('$ splits tokens - \\u0063', testScriptStdout, () => $`echo.js a\u0063b`, 'acb');222-test('$ splits expressions - \\u0063', testScriptStdout, () => $`echo.js ${'a'}\u0063${'b'}`, 'acb');223-test('$ concatenates tokens - \\u0063', testScriptStdout, () => $`echo.js \u0063a\u0063 b`, 'cac\nb');224-test('$ concatenates expressions - \\u0063', testScriptStdout, () => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb');225-test('$ handles tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}`, '\u{1}');226-test('$ splits tokens - \\u{1}', testScriptStdout, () => $`echo.js a\u{1}b`, 'a\u{1}b');227-test('$ splits expressions - \\u{1}', testScriptStdout, () => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u{1}b');228-test('$ concatenates tokens - \\u{1}', testScriptStdout, () => $`echo.js \u{1}a\u{1} b`, '\u{1}a\u{1}\nb');229-test('$ concatenates expressions - \\u{1}', testScriptStdout, () => $`echo.js \u{1}${'a'}\u{1} b`, '\u{1}a\u{1}\nb');230-test('$ handles tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}`, 'c');231-test('$ splits tokens - \\u{63}', testScriptStdout, () => $`echo.js a\u{63}b`, 'acb');232-test('$ splits expressions - \\u{63}', testScriptStdout, () => $`echo.js ${'a'}\u{63}${'b'}`, 'acb');233-test('$ concatenates tokens - \\u{63}', testScriptStdout, () => $`echo.js \u{63}a\u{63} b`, 'cac\nb');234-test('$ concatenates expressions - \\u{63}', testScriptStdout, () => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb');235-test('$ handles tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}`, 'c');236-test('$ splits tokens - \\u{063}', testScriptStdout, () => $`echo.js a\u{063}b`, 'acb');237-test('$ splits expressions - \\u{063}', testScriptStdout, () => $`echo.js ${'a'}\u{063}${'b'}`, 'acb');238-test('$ concatenates tokens - \\u{063}', testScriptStdout, () => $`echo.js \u{063}a\u{063} b`, 'cac\nb');239-test('$ concatenates expressions - \\u{063}', testScriptStdout, () => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb');240-test('$ handles tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}`, 'c');241-test('$ splits tokens - \\u{0063}', testScriptStdout, () => $`echo.js a\u{0063}b`, 'acb');242-test('$ splits expressions - \\u{0063}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb');243-test('$ concatenates tokens - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb');244-test('$ concatenates expressions - \\u{0063}', testScriptStdout, () => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb');245-test('$ handles tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}`, 'c');246-test('$ splits tokens - \\u{00063}', testScriptStdout, () => $`echo.js a\u{00063}b`, 'acb');247-test('$ splits expressions - \\u{00063}', testScriptStdout, () => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb');248-test('$ concatenates tokens - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb');249-test('$ concatenates expressions - \\u{00063}', testScriptStdout, () => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb');250-test('$ handles tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}`, 'c');251-test('$ splits tokens - \\u{000063}', testScriptStdout, () => $`echo.js a\u{000063}b`, 'acb');252-test('$ splits expressions - \\u{000063}', testScriptStdout, () => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb');253-test('$ concatenates tokens - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb');254-test('$ concatenates expressions - \\u{000063}', testScriptStdout, () => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb');255-test('$ handles tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}`, 'c');256-test('$ splits tokens - \\u{0000063}', testScriptStdout, () => $`echo.js a\u{0000063}b`, 'acb');257-test('$ splits expressions - \\u{0000063}', testScriptStdout, () => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb');258-test('$ concatenates tokens - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb');259-test('$ concatenates expressions - \\u{0000063}', testScriptStdout, () => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb');222+test('$ handles tokens - \\u0063', () => testScriptStdout(() => $`echo.js \u0063`, 'c'));223+test('$ splits tokens - \\u0063', () => testScriptStdout(() => $`echo.js a\u0063b`, 'acb'));224+test('$ splits expressions - \\u0063', () => testScriptStdout(() => $`echo.js ${'a'}\u0063${'b'}`, 'acb'));225+test('$ concatenates tokens - \\u0063', () => testScriptStdout(() => $`echo.js \u0063a\u0063 b`, 'cac\nb'));226+test('$ concatenates expressions - \\u0063', () => testScriptStdout(() => $`echo.js \u0063${'a'}\u0063 b`, 'cac\nb'));227+test('$ handles tokens - \\u{1}', () => testScriptStdout(() => $`echo.js \u{1}`, '\u{1}'));228+test('$ splits tokens - \\u{1}', () => testScriptStdout(() => $`echo.js a\u{1}b`, 'a\u{1}b'));229+test('$ splits expressions - \\u{1}', () => testScriptStdout(() => $`echo.js ${'a'}\u{1}${'b'}`, 'a\u{1}b'));230+test('$ concatenates tokens - \\u{1}', () => testScriptStdout(() => $`echo.js \u{1}a\u{1} b`, '\u{1}a\u{1}\nb'));231+test('$ concatenates expressions - \\u{1}', () => testScriptStdout(() => $`echo.js \u{1}${'a'}\u{1} b`, '\u{1}a\u{1}\nb'));232+test('$ handles tokens - \\u{63}', () => testScriptStdout(() => $`echo.js \u{63}`, 'c'));233+test('$ splits tokens - \\u{63}', () => testScriptStdout(() => $`echo.js a\u{63}b`, 'acb'));234+test('$ splits expressions - \\u{63}', () => testScriptStdout(() => $`echo.js ${'a'}\u{63}${'b'}`, 'acb'));235+test('$ concatenates tokens - \\u{63}', () => testScriptStdout(() => $`echo.js \u{63}a\u{63} b`, 'cac\nb'));236+test('$ concatenates expressions - \\u{63}', () => testScriptStdout(() => $`echo.js \u{63}${'a'}\u{63} b`, 'cac\nb'));237+test('$ handles tokens - \\u{063}', () => testScriptStdout(() => $`echo.js \u{063}`, 'c'));238+test('$ splits tokens - \\u{063}', () => testScriptStdout(() => $`echo.js a\u{063}b`, 'acb'));239+test('$ splits expressions - \\u{063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{063}${'b'}`, 'acb'));240+test('$ concatenates tokens - \\u{063}', () => testScriptStdout(() => $`echo.js \u{063}a\u{063} b`, 'cac\nb'));241+test('$ concatenates expressions - \\u{063}', () => testScriptStdout(() => $`echo.js \u{063}${'a'}\u{063} b`, 'cac\nb'));242+test('$ handles tokens - \\u{0063}', () => testScriptStdout(() => $`echo.js \u{0063}`, 'c'));243+test('$ splits tokens - \\u{0063}', () => testScriptStdout(() => $`echo.js a\u{0063}b`, 'acb'));244+test('$ splits expressions - \\u{0063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{0063}${'b'}`, 'acb'));245+test('$ concatenates tokens - \\u{0063}', () => testScriptStdout(() => $`echo.js \u{0063}a\u{0063} b`, 'cac\nb'));246+test('$ concatenates expressions - \\u{0063}', () => testScriptStdout(() => $`echo.js \u{0063}${'a'}\u{0063} b`, 'cac\nb'));247+test('$ handles tokens - \\u{00063}', () => testScriptStdout(() => $`echo.js \u{00063}`, 'c'));248+test('$ splits tokens - \\u{00063}', () => testScriptStdout(() => $`echo.js a\u{00063}b`, 'acb'));249+test('$ splits expressions - \\u{00063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{00063}${'b'}`, 'acb'));250+test('$ concatenates tokens - \\u{00063}', () => testScriptStdout(() => $`echo.js \u{00063}a\u{00063} b`, 'cac\nb'));251+test('$ concatenates expressions - \\u{00063}', () => testScriptStdout(() => $`echo.js \u{00063}${'a'}\u{00063} b`, 'cac\nb'));252+test('$ handles tokens - \\u{000063}', () => testScriptStdout(() => $`echo.js \u{000063}`, 'c'));253+test('$ splits tokens - \\u{000063}', () => testScriptStdout(() => $`echo.js a\u{000063}b`, 'acb'));254+test('$ splits expressions - \\u{000063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{000063}${'b'}`, 'acb'));255+test('$ concatenates tokens - \\u{000063}', () => testScriptStdout(() => $`echo.js \u{000063}a\u{000063} b`, 'cac\nb'));256+test('$ concatenates expressions - \\u{000063}', () => testScriptStdout(() => $`echo.js \u{000063}${'a'}\u{000063} b`, 'cac\nb'));257+test('$ handles tokens - \\u{0000063}', () => testScriptStdout(() => $`echo.js \u{0000063}`, 'c'));258+test('$ splits tokens - \\u{0000063}', () => testScriptStdout(() => $`echo.js a\u{0000063}b`, 'acb'));259+test('$ splits expressions - \\u{0000063}', () => testScriptStdout(() => $`echo.js ${'a'}\u{0000063}${'b'}`, 'acb'));260+test('$ concatenates tokens - \\u{0000063}', () => testScriptStdout(() => $`echo.js \u{0000063}a\u{0000063} b`, 'cac\nb'));261+test('$ concatenates expressions - \\u{0000063}', () => testScriptStdout(() => $`echo.js \u{0000063}${'a'}\u{0000063} b`, 'cac\nb'));262 263 // 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.263-test('$ handles tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}`, '\u{1F600}');264-test('$ splits tokens - \\u{1F600}', testScriptStdout, () => $`echo.js a\u{1F600}b`, 'a\u{1F600}b');265-test('$ splits expressions - \\u{1F600}', testScriptStdout, () => $`echo.js ${'a'}\u{1F600}${'b'}`, 'a\u{1F600}b');266-test('$ concatenates tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}a\u{1F600} b`, '\u{1F600}a\u{1F600}\nb');267-test('$ concatenates expressions - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}${'a'}\u{1F600} b`, '\u{1F600}a\u{1F600}\nb');268-test('$ handles multiple tokens - \\u{1F600}', testScriptStdout, () => $`echo.js \u{1F600}\u{1F600} b c`, '\u{1F600}\u{1F600}\nb\nc');269-test('$ handles the highest code point - \\u{10FFFF}', testScriptStdout, () => $`echo.js \u{10FFFF} b`, '\u{10FFFF}\nb');265+test('$ handles tokens - \\u{1F600}', () => testScriptStdout(() => $`echo.js \u{1F600}`, '\u{1F600}'));266+test('$ splits tokens - \\u{1F600}', () => testScriptStdout(() => $`echo.js a\u{1F600}b`, 'a\u{1F600}b'));267+test('$ splits expressions - \\u{1F600}', () => testScriptStdout(() => $`echo.js ${'a'}\u{1F600}${'b'}`, 'a\u{1F600}b'));268+test('$ concatenates tokens - \\u{1F600}', () => testScriptStdout(() => $`echo.js \u{1F600}a\u{1F600} b`, '\u{1F600}a\u{1F600}\nb'));269+test('$ concatenates expressions - \\u{1F600}', () => testScriptStdout(() => $`echo.js \u{1F600}${'a'}\u{1F600} b`, '\u{1F600}a\u{1F600}\nb'));270+test('$ handles multiple tokens - \\u{1F600}', () => testScriptStdout(() => $`echo.js \u{1F600}\u{1F600} b c`, '\u{1F600}\u{1F600}\nb\nc'));271+test('$ 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 changes271-test('$ handles the last BMP code point - \\u{FFFF}', testScriptStdout, () => $`echo.js \u{FFFF} b`, '\u{FFFF}\nb');272-test('$ handles the first astral code point - \\u{10000}', testScriptStdout, () => $`echo.js \u{10000} b`, '\u{10000}\nb');273-test('$ handles tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}`, 'c}');274-test('$ splits tokens - \\u{0063}}', testScriptStdout, () => $`echo.js a\u{0063}}b`, 'ac}b');275-test('$ splits expressions - \\u{0063}}', testScriptStdout, () => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b');276-test('$ concatenates tokens - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb');277-test('$ concatenates expressions - \\u{0063}}', testScriptStdout, () => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb');273+test('$ handles the last BMP code point - \\u{FFFF}', () => testScriptStdout(() => $`echo.js \u{FFFF} b`, '\u{FFFF}\nb'));274+test('$ handles the first astral code point - \\u{10000}', () => testScriptStdout(() => $`echo.js \u{10000} b`, '\u{10000}\nb'));275+test('$ handles tokens - \\u{0063}}', () => testScriptStdout(() => $`echo.js \u{0063}}`, 'c}'));276+test('$ splits tokens - \\u{0063}}', () => testScriptStdout(() => $`echo.js a\u{0063}}b`, 'ac}b'));277+test('$ splits expressions - \\u{0063}}', () => testScriptStdout(() => $`echo.js ${'a'}\u{0063}}${'b'}`, 'ac}b'));278+test('$ concatenates tokens - \\u{0063}}', () => testScriptStdout(() => $`echo.js \u{0063}}a\u{0063}} b`, 'c}ac}\nb'));279+test('$ concatenates expressions - \\u{0063}}', () => testScriptStdout(() => $`echo.js \u{0063}}${'a'}\u{0063}} b`, 'c}ac}\nb'));280 279-const testScriptErrorStdout = async (t, getSubprocess) => {280- t.throws(getSubprocess, {message: /null bytes/});281+const testScriptErrorStdout = async getSubprocess => {282+ assertThrows(getSubprocess, {message: /null bytes/});283 };284 283-test('$ handles tokens - \\0', testScriptErrorStdout, () => $`echo.js \0`);284-test('$ splits tokens - \\0', testScriptErrorStdout, () => $`echo.js a\0b`);285-test('$ splits expressions - \\0', testScriptErrorStdout, () => $`echo.js ${'a'}\0${'b'}`);286-test('$ concatenates tokens - \\0', testScriptErrorStdout, () => $`echo.js \0a\0 b`);287-test('$ concatenates expressions - \\0', testScriptErrorStdout, () => $`echo.js \0${'a'}\0 b`);285+test('$ handles tokens - \\0', () => testScriptErrorStdout(() => $`echo.js \0`));286+test('$ splits tokens - \\0', () => testScriptErrorStdout(() => $`echo.js a\0b`));287+test('$ splits expressions - \\0', () => testScriptErrorStdout(() => $`echo.js ${'a'}\0${'b'}`));288+test('$ concatenates tokens - \\0', () => testScriptErrorStdout(() => $`echo.js \0a\0 b`));289+test('$ concatenates expressions - \\0', () => testScriptErrorStdout(() => $`echo.js \0${'a'}\0 b`));290 289-const testReturnInterpolate = async (t, getSubprocess, expectedStdout, options = {}) => {291+const 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 };296 295-test('$ allows execa return value interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar');296-test('$ allows execa return value buffer interpolation', testReturnInterpolate, foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});297-test('$ allows execa return value array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar');298-test('$ allows execa return value buffer array interpolation', testReturnInterpolate, foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});297+test('$ allows execa return value interpolation', () => testReturnInterpolate(foo => $`echo.js ${foo} bar`, 'foo\nbar'));298+test('$ allows execa return value buffer interpolation', () => testReturnInterpolate(foo => $`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'}));299+test('$ allows execa return value array interpolation', () => testReturnInterpolate(foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar'));300+test('$ allows execa return value buffer array interpolation', () => testReturnInterpolate(foo => $`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'}));301 300-const testReturnInterpolateSync = (t, getSubprocess, expectedStdout, options = {}) => {302+const 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 };307 306-test('$.sync allows execa return value interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar');307-test('$.sync allows execa return value buffer interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'});308-test('$.sync allows execa return value array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar');309-test('$.sync allows execa return value buffer array interpolation', testReturnInterpolateSync, foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'});308+test('$.sync allows execa return value interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${foo} bar`, 'foo\nbar'));309+test('$.sync allows execa return value buffer interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${foo} bar`, 'foo\nbar', {encoding: 'buffer'}));310+test('$.sync allows execa return value array interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar'));311+test('$.sync allows execa return value buffer array interpolation', () => testReturnInterpolateSync(foo => $.sync`echo.js ${[foo, 'bar']}`, 'foo\nbar', {encoding: 'buffer'}));312 311-const testInvalidSequence = (t, getSubprocess) => {312- t.throws(getSubprocess, {message: /Invalid backslash sequence/});313+const testInvalidSequence = getSubprocess => {314+ assertThrows(getSubprocess, {message: /Invalid backslash sequence/});315 };316 315-test('$ handles invalid escape sequence - \\1', testInvalidSequence, () => $`echo.js \1`);316-test('$ handles invalid escape sequence - \\u', testInvalidSequence, () => $`echo.js \u`);317-test('$ handles invalid escape sequence - \\u0', testInvalidSequence, () => $`echo.js \u0`);318-test('$ handles invalid escape sequence - \\u00', testInvalidSequence, () => $`echo.js \u00`);319-test('$ handles invalid escape sequence - \\u000', testInvalidSequence, () => $`echo.js \u000`);320-test('$ handles invalid escape sequence - \\ug', testInvalidSequence, () => $`echo.js \ug`);321-test('$ handles invalid escape sequence - \\u{', testInvalidSequence, () => $`echo.js \u{`);322-test('$ handles invalid escape sequence - \\u{0000', testInvalidSequence, () => $`echo.js \u{0000`);323-test('$ handles invalid escape sequence - \\u{g}', testInvalidSequence, () => $`echo.js \u{g}`);317+test('$ handles invalid escape sequence - \\1', () => testInvalidSequence(() => $`echo.js \1`));318+test('$ handles invalid escape sequence - \\u', () => testInvalidSequence(() => $`echo.js \u`));319+test('$ handles invalid escape sequence - \\u0', () => testInvalidSequence(() => $`echo.js \u0`));320+test('$ handles invalid escape sequence - \\u00', () => testInvalidSequence(() => $`echo.js \u00`));321+test('$ handles invalid escape sequence - \\u000', () => testInvalidSequence(() => $`echo.js \u000`));322+test('$ handles invalid escape sequence - \\ug', () => testInvalidSequence(() => $`echo.js \ug`));323+test('$ handles invalid escape sequence - \\u{', () => testInvalidSequence(() => $`echo.js \u{`));324+test('$ handles invalid escape sequence - \\u{0000', () => testInvalidSequence(() => $`echo.js \u{0000`));325+test('$ handles invalid escape sequence - \\u{g}', () => testInvalidSequence(() => $`echo.js \u{g}`));326 325-test('$ handles invalid escape sequence - \\x', testInvalidSequence, () => $`echo.js \x`);326-test('$ handles invalid escape sequence - \\x0', testInvalidSequence, () => $`echo.js \x0`);327-test('$ handles invalid escape sequence - \\xgg', testInvalidSequence, () => $`echo.js \xgg`);327+test('$ handles invalid escape sequence - \\x', () => testInvalidSequence(() => $`echo.js \x`));328+test('$ handles invalid escape sequence - \\x0', () => testInvalidSequence(() => $`echo.js \x0`));329+test('$ handles invalid escape sequence - \\xgg', () => testInvalidSequence(() => $`echo.js \xgg`));330 329-const testEmptyScript = (t, getSubprocess) => {330- t.throws(getSubprocess, {message: /Template script must not be empty/});331+const testEmptyScript = getSubprocess => {332+ assertThrows(getSubprocess, {message: /Template script must not be empty/});333 };334 333-test('$``', testEmptyScript, () => $``);334-test('$` `', testEmptyScript, () => $` `);335-test('$` ` (2 spaces)', testEmptyScript, () => $` `);336-test('$`\\t`', testEmptyScript, () => $` `);337-test('$`\\n`', testEmptyScript, () => $`338-`);335+test('$``', () => testEmptyScript(() => $``));336+test('$` `', () => testEmptyScript(() => $` `));337+test('$` ` (2 spaces)', () => testEmptyScript(() => $` `));338+test('$`\\t`', () => testEmptyScript(() => $` `));339+test('$`\\n`', () => testEmptyScript(() => $`340+`));341 340-const testInvalidExpression = (t, invalidExpression) => {341- t.throws(342+const testInvalidExpression = invalidExpression => {343+ assertThrows(344 () => $`echo.js ${invalidExpression}`,345 {message: /in template expression/},346 );347 };348 347-test('$ throws on invalid expression - undefined', testInvalidExpression, undefined);348-test('$ throws on invalid expression - null', testInvalidExpression, null);349-test('$ throws on invalid expression - true', testInvalidExpression, true);350-test('$ throws on invalid expression - {}', testInvalidExpression, {});351-test('$ throws on invalid expression - {foo: "bar"}', testInvalidExpression, {foo: 'bar'});352-test('$ throws on invalid expression - {stdout: 1}', testInvalidExpression, {stdout: 1});353-test('$ throws on invalid expression - [undefined]', testInvalidExpression, [undefined]);354-test('$ throws on invalid expression - [null]', testInvalidExpression, [null]);355-test('$ throws on invalid expression - [true]', testInvalidExpression, [true]);356-test('$ throws on invalid expression - [{}]', testInvalidExpression, [{}]);357-test('$ throws on invalid expression - [{foo: "bar"}]', testInvalidExpression, [{foo: 'bar'}]);358-test('$ throws on invalid expression - [{stdout: 1}]', testInvalidExpression, [{stdout: 1}]);349+test('$ throws on invalid expression - undefined', () => testInvalidExpression(undefined));350+test('$ throws on invalid expression - null', () => testInvalidExpression(null));351+test('$ throws on invalid expression - true', () => testInvalidExpression(true));352+test('$ throws on invalid expression - {}', () => testInvalidExpression({}));353+test('$ throws on invalid expression - {foo: "bar"}', () => testInvalidExpression({foo: 'bar'}));354+test('$ throws on invalid expression - {stdout: 1}', () => testInvalidExpression({stdout: 1}));355+test('$ throws on invalid expression - [undefined]', () => testInvalidExpression([undefined]));356+test('$ throws on invalid expression - [null]', () => testInvalidExpression([null]));357+test('$ throws on invalid expression - [true]', () => testInvalidExpression([true]));358+test('$ throws on invalid expression - [{}]', () => testInvalidExpression([{}]));359+test('$ throws on invalid expression - [{foo: "bar"}]', () => testInvalidExpression([{foo: 'bar'}]));360+test('$ throws on invalid expression - [{stdout: 1}]', () => testInvalidExpression([{stdout: 1}]));361 360-const testMissingOutput = (t, invalidExpression) => {361- t.throws(362+const testMissingOutput = invalidExpression => {363+ assertThrows(364 () => $`echo.js ${invalidExpression()}`,365 {message: /Missing result.stdout/},366 );367 };368 367-test('$ throws on invalid expression - {stdout: undefined}', testMissingOutput, () => ({stdout: undefined}));368-test('$ throws on invalid expression - [{stdout: undefined}]', testMissingOutput, () => [{stdout: undefined}]);369-test('$ throws on invalid expression - $(options).sync', testMissingOutput, () => $({stdio: 'ignore'}).sync`noop.js`);370-test('$ throws on invalid expression - [$(options).sync]', testMissingOutput, () => [$({stdio: 'ignore'}).sync`noop.js`]);369+test('$ throws on invalid expression - {stdout: undefined}', () => testMissingOutput(() => ({stdout: undefined})));370+test('$ throws on invalid expression - [{stdout: undefined}]', () => testMissingOutput(() => [{stdout: undefined}]));371+test('$ throws on invalid expression - $(options).sync', () => testMissingOutput(() => $({stdio: 'ignore'}).sync`noop.js`));372+test('$ throws on invalid expression - [$(options).sync]', () => testMissingOutput(() => [$({stdio: 'ignore'}).sync`noop.js`]));373 372-const testInvalidPromise = (t, invalidExpression) => {373- t.throws(374+const testInvalidPromise = invalidExpression => {375+ assertThrows(376 () => $`echo.js ${invalidExpression()}`,377 {message: /Please use \${await subprocess}/},378 );379 };380 379-test('$ throws on invalid expression - Promise.resolve()', testInvalidPromise, async () => ({}));380-test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', testInvalidPromise, async () => ({foo: 'bar'}));381-test('$ throws on invalid expression - [Promise.resolve()]', testInvalidPromise, () => [Promise.resolve()]);382-test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', testInvalidPromise, () => [Promise.resolve({stdout: 'foo'})]);383-test('$ throws on invalid expression - $', testInvalidPromise, () => $`noop.js`);384-test('$ throws on invalid expression - [$]', testInvalidPromise, () => [$`noop.js`]);381+test('$ throws on invalid expression - Promise.resolve()', () => testInvalidPromise(async () => ({})));382+test('$ throws on invalid expression - Promise.resolve({stdout: "foo"})', () => testInvalidPromise(async () => ({foo: 'bar'})));383+test('$ throws on invalid expression - [Promise.resolve()]', () => testInvalidPromise(() => [Promise.resolve()]));384+test('$ throws on invalid expression - [Promise.resolve({stdout: "foo"})]', () => testInvalidPromise(() => [Promise.resolve({stdout: 'foo'})]));385+test('$ throws on invalid expression - $', () => testInvalidPromise(() => $`noop.js`));386+test('$ throws on invalid expression - [$]', () => testInvalidPromise(() => [$`noop.js`]));modified:test/pipe/abort.js+60 added-58 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';2-import test from 'ava';3+import test from 'node:test';4+import {assertRejects, assertLike} from '../helpers/assert.js';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {foobarString} from '../helpers/input.js';8 9 setFixtureDirectory();10 9-const assertUnPipeError = async (t, pipePromise) => {10- const error = await t.throwsAsync(pipePromise);11+const assertUnPipeError = async pipePromise => {12+ const error = await assertRejects(pipePromise);13 12- 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);16 15- 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, []);30 29- 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 };36 35-test('Can unpipe a single subprocess', async t => {37+test('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});42 43 abortController.abort();42- await assertUnPipeError(t, pipePromise);44+ await assertUnPipeError(pipePromise);45 46 source.stdin.end(foobarString);47 destination.stdin.end('.');48 47- t.like(await destination, {stdout: '.'});48- t.like(await source, {stdout: foobarString});49+ assertLike(await destination, {stdout: '.'});50+ assertLike(await source, {stdout: foobarString});51 });52 51-test('Can use an already aborted signal', async t => {53+test('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});59 58- await assertUnPipeError(t, pipePromise);60+ await assertUnPipeError(pipePromise);61 });62 61-test('Can unpipe a subprocess among other sources', async t => {63+test('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);70 71 abortController.abort();70- await assertUnPipeError(t, pipePromise);72+ await assertUnPipeError(pipePromise);73 74 source.stdin.end('.');75 74- 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 });81 80-test('Can unpipe a subprocess among other sources on the same subprocess', async t => {82+test('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'});88 89 abortController.abort();88- await assertUnPipeError(t, pipePromise);90+ await assertUnPipeError(pipePromise);91 92 source.stdin.end(foobarString);93 92- 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 });98 97-test('Can unpipe a subprocess among other destinations', async t => {99+test('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);106 107 abortController.abort();106- await assertUnPipeError(t, pipePromise);108+ await assertUnPipeError(pipePromise);109 110 source.stdin.end(foobarString);111 destination.stdin.end('.');112 111- 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 });118 117-test('Can unpipe then re-pipe a subprocess', async t => {119+test('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});124 125 source.stdin.write('.');126 const [firstWrite] = await once(source.stdout, 'data');125- t.is(firstWrite.toString(), '.');127+ assert.equal(firstWrite.toString(), '.');128 129 abortController.abort();128- await assertUnPipeError(t, pipePromise);130+ await assertUnPipeError(pipePromise);131 132 source.pipe(destination);133 source.stdin.end('.');134 133- t.like(await destination, {stdout: '..'});134- t.like(await source, {stdout: '..'});135+ assertLike(await destination, {stdout: '..'});136+ assertLike(await source, {stdout: '..'});137 });138 137-test('Can unpipe to prevent termination to propagate to source', async t => {139+test('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});144 145 abortController.abort();144- await assertUnPipeError(t, pipePromise);146+ await assertUnPipeError(pipePromise);147 148 destination.kill();147- t.like(await t.throwsAsync(destination), {signal: 'SIGTERM'});149+ assertLike(await assertRejects(destination), {signal: 'SIGTERM'});150 151 source.stdin.end(foobarString);150- t.like(await source, {stdout: foobarString});152+ assertLike(await source, {stdout: foobarString});153 });154 153-test('Can unpipe to prevent termination to propagate to destination', async t => {155+test('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});160 161 abortController.abort();160- await assertUnPipeError(t, pipePromise);162+ await assertUnPipeError(pipePromise);163 164 source.kill();163- t.like(await t.throwsAsync(source), {signal: 'SIGTERM'});165+ assertLike(await assertRejects(source), {signal: 'SIGTERM'});166 167 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
1+import assert from 'node:assert/strict';2 import {setTimeout} from 'node:timers/promises';3 import {Readable} from 'node:stream';4 import {text} from 'node:stream/consumers';4-import test from 'ava';5+import test from 'node:test';6+import {assertThrows, assertRejects} from '../helpers/assert.js';7 import {execa} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 import {simpleFull, noNewlinesFull, noNewlinesChunks} from '../helpers/lines.js';10 import {foobarString, foobarArray} from '../helpers/input.js';11+/* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */12 13 setFixtureDirectory();14 15 const timeoutSymbol = Symbol('timeout');2 unmodified lines18 const pipeSimple = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js');19 const pipeAll = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin.js', {all: true});20 const pipeDistinctBoth = () => execa('noop-fd.js', ['1', simpleFull]).pipe('stdin-distinct-both.js');21 19-const assertSettles = async (t, promise, timeout = 1000) => {22+const 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 ]);28 26- t.not(result, timeoutSymbol);29+ assert.notEqual(result, timeoutSymbol);30 return result;31 };32 33 const cleanupSubprocesses = async (...subprocesses) => {9 unmodified lines43 44 return messages;45 };46 44-test('The .pipe() return value can be iterated', async t => {47+test('The .pipe() return value can be iterated', async () => {48 const lines = await Array.fromAsync(pipeSimple());49 47- t.deepEqual(lines, noNewlinesChunks);50+ assert.deepEqual(lines, noNewlinesChunks);51 });52 50-test('The .pipe() return value has an .iterable() method', async t => {53+test('The .pipe() return value has an .iterable() method', async () => {54 const lines = await Array.fromAsync(pipeSimple().iterable());55 53- t.deepEqual(lines, noNewlinesChunks);56+ assert.deepEqual(lines, noNewlinesChunks);57 });58 56-test('The .pipe() return value has a .readable() method', async t => {57- t.is(await text(pipeSimple().readable()), simpleFull);59+test('The .pipe() return value has a .readable() method', async () => {60+ assert.equal(await text(pipeSimple().readable()), simpleFull);61 });62 60-test('The .pipe() return value has a .readableStream() method', async t => {61- t.is(await text(pipeSimple().readableStream()), simpleFull);63+test('The .pipe() return value has a .readableStream() method', async () => {64+ assert.equal(await text(pipeSimple().readableStream()), simpleFull);65 });66 64-test('The .pipe() return value .readable() can be called multiple times', async t => {67+test('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 ]);73 71- t.is(output, simpleFull);72- t.is(secondOutput, simpleFull);74+ assert.equal(output, simpleFull);75+ assert.equal(secondOutput, simpleFull);76 });77 75-test('The .pipe() return value .readable() keeps conversion options', async t => {78+test('The .pipe() return value .readable() keeps conversion options', async () => {79 const chunks = await Array.fromAsync(pipeSimple().readable({binary: false, preserveNewlines: false}));80 78- t.deepEqual(chunks, noNewlinesChunks);79- t.is(chunks.join(''), noNewlinesFull);81+ assert.deepEqual(chunks, noNewlinesChunks);82+ assert.equal(chunks.join(''), noNewlinesFull);83 });84 82-test('The .pipe() return value does not have a .writable() method', async t => {85+test('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 });93 91-test('The .pipe() return value does not have .all unless destination uses the "all" option', async t => {94+test('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');97 95- 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 });103 101-test('The .pipe() return value has an .all property', async t => {104+test('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 });110 108-test('The .pipe() return value .all is created lazily and cached', async t => {111+test('The .pipe() return value .all is created lazily and cached', async () => {112 const piped = pipeAll();113 const descriptor = Object.getOwnPropertyDescriptor(piped, 'all');114 112- 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 });123 121-test('The .pipe() return value .readable() can read destination stderr', async t => {124+test('The .pipe() return value .readable() can read destination stderr', async () => {125 const piped = pipeDistinctBoth();126 124- 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 });130 128-test('The .pipe() return value .iterable() can read destination stderr', async t => {131+test('The .pipe() return value .iterable() can read destination stderr', async () => {132 const piped = pipeDistinctBoth();133 const lines = await Array.fromAsync(piped.iterable({from: 'stderr'}));134 132- t.deepEqual(lines, ['aaa', 'bbb', 'ccc:stderr']);135+ assert.deepEqual(lines, ['aaa', 'bbb', 'ccc:stderr']);136 await piped;137 });138 136-test('The .pipe() return value has IPC methods', async t => {139+test('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 });145 143-test('The .pipe() return value .getEachMessage() can be called twice at the same time', async t => {146+test('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});148 146- t.deepEqual(149+ assert.deepEqual(150 await Promise.all([getPipeMessages(piped), getPipeMessages(piped)]),151 [foobarArray, foobarArray],152 );153 154 const {ipcOutput} = await piped;152- t.deepEqual(ipcOutput, foobarArray);155+ assert.deepEqual(ipcOutput, foobarArray);156 });157 155-test('The .pipe() return value .getEachMessage() preserves setup errors', async t => {158+test('The .pipe() return value .getEachMessage() preserves setup errors', async () => {159 const piped = execa('empty.js').pipe('ipc-send-twice.js', {ipc: true});160 158- t.throws(() => {161+ assertThrows(() => {162 piped.getEachMessage(null);163 }, {instanceOf: TypeError});164 165 await piped;166 });167 165-test('The .pipe() return value .getEachMessage() waits for source failure', async t => {168+test('The .pipe() return value .getEachMessage() waits for source failure', async () => {169 const piped = execa('fail.js').pipe('ipc-send-twice.js', {ipc: true});170 168- 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 });177 178 test('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 });185 186 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});189 187- 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 });194 195 test('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 });202 203 const piped = source.pipe(destination, {unpipeSignal: abortController.signal});1 unmodified line205 piped.getEachMessage(),206 piped.getEachMessage(),207 ];208 206- 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 );216 214- 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 });221 222 const assertCanceledPipeMessageReader = async (t, getReader, shouldAbortBeforePipe = false) => {223 const abortController = new AbortController();2 unmodified lines226 }227 228 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 });233 234 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/});236 237 if (!shouldAbortBeforePipe) {238 abortController.abort();239 }240 238- await assertSettles(t, readerPromise);239- await t.throwsAsync(piped, {message: /Pipe canceled/});241+ await assertSettles(readerPromise);242+ await assertRejects(piped, {message: /Pipe canceled/});243 };244 245 test('The .pipe() return value .getEachMessage() waits for pipe cancellation before IPC messages', async t => {246 await assertCanceledPipeMessageReader(t, piped => piped.getEachMessage().next());13 unmodified lines260 261 test('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 });267 268 const piped = source.pipe(destination);269 const iterator = piped.getEachMessage();270 268- 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 });278 276-test('The .pipe() return value .getEachMessage() propagates source failure when the iterator is returned', async t => {279+test('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();283 281- 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 });289 287-test('The .pipe() return value .getEachMessage() propagates destination failure', async t => {290+test('The .pipe() return value .getEachMessage() propagates destination failure', async () => {291 const piped = execa('empty.js').pipe('ipc-send-fail.js', {ipc: true});292 290- 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/});298 296- const {ipcOutput} = await t.throwsAsync(piped);297- t.deepEqual(ipcOutput, [foobarString]);299+ const {ipcOutput} = await assertRejects(piped);300+ assert.deepEqual(ipcOutput, [foobarString]);301 });302 300-test('The .pipe() return value .getEachMessage() waits for the pipe when the consumer throws', async t => {303+test('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);306 304- 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);314 315 const {ipcOutput, stdout} = await piped;313- t.deepEqual(ipcOutput, [foobarString]);314- t.is(stdout, '.');316+ assert.deepEqual(ipcOutput, [foobarString]);317+ assert.equal(stdout, '.');318 });319 320 test('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 });326 327 const piped = source.pipe(destination);325- const {message} = t.throws(() => piped.getEachMessage());328+ const {message} = assertThrows(() => piped.getEachMessage());329 327- 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 });335 333-test('The .pipe() return value can exchange IPC messages', async t => {336+test('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 });342 340-test('A chained .pipe() return value can be iterated', async t => {343+test('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'));345 343- t.deepEqual(lines, noNewlinesChunks);346+ assert.deepEqual(lines, noNewlinesChunks);347 });348 346-test('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/});349+test('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 });352 350-test('The .pipe() return value iteration waits for source failure', async t => {353+test('The .pipe() return value iteration waits for source failure', async () => {354 const piped = execa('fail.js').pipe('stdin.js');355 353- 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 });362 360-test('The .pipe() return value .readable() waits for source failure', async t => {363+test('The .pipe() return value .readable() waits for source failure', async () => {364 const piped = execa('fail.js').pipe('stdin.js');365 363- 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 });368 366-test('The .pipe() return value .readableStream() waits for source failure', async t => {369+test('The .pipe() return value .readableStream() waits for source failure', async () => {370 const piped = execa('fail.js').pipe('stdin.js');371 369- 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 });374 372-test('The .pipe() return value .all waits for source failure', async t => {375+test('The .pipe() return value .all waits for source failure', async () => {376 const piped = execa('fail.js').pipe('stdin.js', {all: true});377 375- 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 });380 381 const assertCanceledPipeReader = async (t, getReader, shouldAbortBeforePipe = false) => {382 const abortController = new AbortController();2 unmodified lines385 }386 387 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 });392 393 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/});395 396 if (!shouldAbortBeforePipe) {397 abortController.abort();398 }399 397- await assertSettles(t, readerPromise, 200);400+ await assertSettles(readerPromise, 200);401 };402 403 test('The .pipe() return value .readable() waits for pipe cancellation', async t => {404 await assertCanceledPipeReader(t, piped => text(piped.readable()));10 unmodified lines415 test('The .pipe() return value .all waits for already canceled pipes', async t => {416 await assertCanceledPipeReader(t, piped => text(piped.all), true);417 });418 416-test('Multiple sources piped to one destination each expose the destination methods', async t => {419+test('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 ];425 426 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 }430 431 await Promise.all(piped);432 });433+434+/* eslint-enable node-test/no-conditional-assertion */modified:test/pipe/pipe-arguments.js+99 added-97 removed
1+import assert from 'node:assert/strict';2 import {spawn} from 'node:child_process';3 import {pathToFileURL} from 'node:url';3-import test from 'ava';4+import test from 'node:test';5+import {assertRejects} from '../helpers/assert.js';6 import {$, execa} from '../../index.js';7 import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';8 import {foobarString} from '../helpers/input.js';9 import {getDenoNodePath} from '../helpers/file-path.js';10 11 setFixtureDirectory();12 11-test('$.pipe(subprocess)', async t => {13+test('$.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 });17 16-test('execa.$.pipe(subprocess)', async t => {18+test('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 });22 21-test('$.pipe.pipe(subprocess)', async t => {23+test('$.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 });29 28-test('$.pipe`command`', async t => {30+test('$.pipe`command`', async () => {31 const {stdout} = await $`noop.js ${foobarString}`.pipe`stdin.js`;30- t.is(stdout, foobarString);32+ assert.equal(stdout, foobarString);33 });34 33-test('execa.$.pipe`command`', async t => {35+test('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 });39 38-test('$.pipe.pipe`command`', async t => {40+test('$.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 });46 45-test('$.pipe("file")', async t => {47+test('$.pipe("file")', async () => {48 const {stdout} = await $`noop.js ${foobarString}`.pipe('stdin.js');47- t.is(stdout, foobarString);49+ assert.equal(stdout, foobarString);50 });51 50-test('execa.$.pipe("file")`', async t => {52+test('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 });56 55-test('$.pipe.pipe("file")', async t => {57+test('$.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 });63 62-test('execa.$.pipe(fileUrl)`', async t => {64+test('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 });68 67-test('$.pipe("file", commandArguments, options)', async t => {69+test('$.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 });73 72-test('execa.$.pipe("file", commandArguments, options)`', async t => {74+test('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 });78 77-test('execa.$.pipe("file", commandArguments, options with denoNodePath)`', async t => {79+test('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 });83 82-test('execa.$.pipe("file", commandArguments, denoNodePath)`', async t => {84+test('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 });88 87-test('$.pipe.pipe("file", commandArguments, options)', async t => {89+test('$.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 });95 94-test('$.pipe(subprocess, pipeOptions)', async t => {96+test('$.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 });100 99-test('execa.$.pipe(subprocess, pipeOptions)', async t => {101+test('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 });105 104-test('$.pipe.pipe(subprocess, pipeOptions)', async t => {106+test('$.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 });112 111-test('$.pipe(pipeOptions)`command`', async t => {113+test('$.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 });117 116-test('execa.$.pipe(pipeOptions)`command`', async t => {118+test('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 });122 121-test('$.pipe.pipe(pipeOptions)`command`', async t => {123+test('$.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 });129 128-test('$.pipe("file", pipeOptions)', async t => {130+test('$.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 });134 133-test('execa.$.pipe("file", pipeOptions)', async t => {135+test('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 });139 138-test('$.pipe.pipe("file", pipeOptions)', async t => {140+test('$.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 });146 145-test('$.pipe(options)`command`', async t => {147+test('$.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 });151 150-test('execa.$.pipe(options)`command`', async t => {152+test('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 });156 155-test('$.pipe.pipe(options)`command`', async t => {157+test('$.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 });163 162-test('$.pipe("file", options)', async t => {164+test('$.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 });168 167-test('execa.$.pipe("file", options)', async t => {169+test('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 });173 172-test('$.pipe.pipe("file", options)', async t => {174+test('$.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 });180 179-test('$.pipe(pipeAndSubprocessOptions)`command`', async t => {181+test('$.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 });185 184-test('execa.$.pipe(pipeAndSubprocessOptions)`command`', async t => {186+test('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 });190 189-test('$.pipe.pipe(pipeAndSubprocessOptions)`command`', async t => {191+test('$.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 });197 196-test('$.pipe("file", pipeAndSubprocessOptions)', async t => {198+test('$.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 });202 201-test('execa.$.pipe("file", pipeAndSubprocessOptions)', async t => {203+test('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 });207 206-test('$.pipe.pipe("file", pipeAndSubprocessOptions)', async t => {208+test('$.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 });214 213-test('$.pipe(options)(secondOptions)`command`', async t => {215+test('$.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 });219 218-test('execa.$.pipe(options)(secondOptions)`command`', async t => {220+test('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 });224 223-test('$.pipe.pipe(options)(secondOptions)`command`', async t => {225+test('$.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 });231 230-test('$.pipe`command` forces "stdin: pipe"', async t => {232+test('$.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 });236 235-test('execa.pipe("file") forces "stdin: "pipe"', async t => {237+test('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 });241 240-test('execa.pipe(subprocess) does not force "stdin: pipe"', async t => {241- await t.throwsAsync(242+test('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 });248 247-test('$.pipe(options)(subprocess) fails', async t => {248- await t.throwsAsync(249+test('$.pipe(options)(subprocess) fails', async () => {250+ await assertRejects(251 $`empty.js`.pipe({stdout: 'pipe'})($`empty.js`),252 {message: /Please use \.pipe/},253 );254 });255 254-test('execa.$.pipe(options)(subprocess) fails', async t => {255- await t.throwsAsync(256+test('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 });262 261-test('$.pipe(options)("file") fails', async t => {262- await t.throwsAsync(263+test('$.pipe(options)("file") fails', async () => {264+ await assertRejects(265 $`empty.js`.pipe({stdout: 'pipe'})('empty.js'),266 {message: /Please use \.pipe/},267 );268 });269 268-test('execa.$.pipe(options)("file") fails', async t => {269- await t.throwsAsync(270+test('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 });276 275-const testInvalidPipe = async (t, ...pipeArguments) => {276- await t.throwsAsync(277+const testInvalidPipe = async (...pipeArguments) => {278+ await assertRejects(279 $`empty.js`.pipe(...pipeArguments),280 {message: /must be a template string/},281 );282 };283 282-test('$.pipe(nonExecaSubprocess) fails', testInvalidPipe, spawn('node', ['--version']));283-test('$.pipe(false) fails', testInvalidPipe, false);284+test('$.pipe(nonExecaSubprocess) fails', () => testInvalidPipe(spawn('node', ['--version'])));285+test('$.pipe(false) fails', () => testInvalidPipe(false));modified:test/pipe/sequence.js+162 added-143 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import process from 'node:process';4 import {PassThrough} from 'node:stream';5 import {setTimeout} from 'node:timers/promises';5-import test from 'ava';6+import test from 'node:test';7+import {assertRejects, assertLike} from '../helpers/assert.js';8 import {execa} from '../../index.js';9 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10 import {foobarString} from '../helpers/input.js';11 import {noopGenerator} from '../helpers/generator.js';3 unmodified lines15 16 const isLinux = process.platform === 'linux';17 const timeoutSymbol = Symbol('timeout');18 17-const 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.22+const observeUnhandledRejection = async () => {23+ const testRunnerListeners = process.listeners('unhandledRejection');24+ for (const listener of testRunnerListeners) {25+ process.removeListener('unhandledRejection', listener);26+ }27+28+ try {29+ return await once(process, 'unhandledRejection');30+ } finally {31+ for (const listener of testRunnerListeners) {32+ process.on('unhandledRejection', listener);33+ }34+ }35+};36+37+const assertUnhandledRejection = async pipePromise => {38 const result = await Promise.race([19- unhandledRejectionPromise,20- setTimeout(500, timeoutSymbol),39+ observeUnhandledRejection(),40+ setTimeout(5000, timeoutSymbol),41 ]);42 23- t.not(result, timeoutSymbol);43+ assert.notEqual(result, timeoutSymbol);44 45 if (result === timeoutSymbol) {46 return;47 }48 49 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 };53 34-const assertUnhandledPipePromise = async (t, {destinationOptions = {}, inspectPipePromise} = {}) => {54+const 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 };66 48-test('Source stream abort -> destination success', async t => {67+test('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();72 54- 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 });77 59-test('Source stream error -> destination success', async t => {78+test('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);84 66- 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 });89 71-test('Destination stream abort -> source failure', async t => {90+test('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();95 77- 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 });100 82-test('Destination stream error -> source failure', async t => {101+test('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);107 89- 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 });112 94-test('Source success -> destination success', async t => {113+test('Source success -> destination success', async () => {114 const source = execa('noop.js', [foobarString]);115 const destination = execa('stdin.js');116 const pipePromise = source.pipe(destination);117 99- 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 });122 104-test('Destination stream end -> source failure', async t => {123+test('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();128 110- 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 });133 115-test('Source normal failure -> destination success', async t => {134+test('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);138 120- 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 });143 125-test('Source normal failure -> deep destination success', async t => {144+test('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);150 132- 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 });157 139-const testSourceTerminated = async (t, signal) => {158+const 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);163 145- 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 };168 150-test('Source SIGTERM -> destination success', testSourceTerminated, 'SIGTERM');151-test('Source SIGKILL -> destination success', testSourceTerminated, 'SIGKILL');169+test('Source SIGTERM -> destination success', () => testSourceTerminated('SIGTERM'));170+test('Source SIGKILL -> destination success', () => testSourceTerminated('SIGKILL'));171 153-test('Destination success before source -> source success', async t => {172+test('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);177 178 await destination;179 passThroughStream.end();180 await source;162- t.is(await pipePromise, await destination);181+ assert.equal(await pipePromise, await destination);182 });183 165-test('Destination normal failure -> source failure', async t => {184+test('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);188 170- 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 });193 175-test('Destination normal failure -> deep source failure', async t => {194+test('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);200 182- 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 });207 189-const testDestinationTerminated = async (t, signal) => {208+const 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);213 195- 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 };218 200-test('Destination SIGTERM -> source abort', testDestinationTerminated, 'SIGTERM');201-test('Destination SIGKILL -> source abort', testDestinationTerminated, 'SIGKILL');219+test('Destination SIGTERM -> source abort', () => testDestinationTerminated('SIGTERM'));220+test('Destination SIGKILL -> source abort', () => testDestinationTerminated('SIGKILL'));221 203-test('Source already ended -> ignore source', async t => {222+test('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);227 209- 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 });232 214-test('Source already aborted -> ignore source', async t => {233+test('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);238 220- 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 });243 225-test('Source already errored -> failure', async t => {244+test('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);250 232- 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 });255 237-test('Destination already ended -> ignore source', async t => {256+test('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);262 244- 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 });267 249-test('Destination already aborted -> failure', async t => {268+test('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);274 256- 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 });278 260-test('Destination already errored -> failure', async t => {279+test('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);286 268- 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 });290 272-test('Source normal failure + destination normal failure', async t => {291+test('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);295 277- 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 });300 282-test('Simultaneous error on source and destination', async t => {301+test('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 line307 source.nodeChildProcess.emit('error', sourceCause);308 const destinationCause = new Error('other');309 destination.nodeChildProcess.emit('error', destinationCause);310 292- 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 });315 297-test('Does not need to await individual promises', async t => {316+test('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 });321 303-test.serial('Need to await .pipe() return value', async t => {304- await assertUnhandledPipePromise(t);322+test('Need to await .pipe() return value', async () => {323+ await assertUnhandledPipePromise();324 });325 307-test.serial('Need to await .pipe() return value, "all" option', async t => {308- await assertUnhandledPipePromise(t, {destinationOptions: {all: true}});326+test('Need to await .pipe() return value, "all" option', async () => {327+ await assertUnhandledPipePromise({destinationOptions: {all: true}});328 });329 311-test.serial('Need to await .pipe() return value after inspecting lazy .all', async t => {312- await assertUnhandledPipePromise(t, {330+test('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 });339 321-test.serial('Need to await .pipe() return value after getOneMessage()', async t => {340+test('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');344 327- 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 });351 334-test.serial('Need to await .pipe() return value after paused getEachMessage()', async t => {352+test('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();357 341- 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 });364 365 if (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)$/);375 359- 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);382 366- 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 }386+387+ assert.equal(source.all.readableEnded, true);388+ assert.equal(source.all.errored, null);389+ assert.equal(source.all.destroyed, true);390 };391 373- 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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {fullStdio, fullReadableStdio} from '../helpers/stdio.js';6 import {foobarString} from '../helpers/input.js';7 8 setFixtureDirectory();9 10 // eslint-disable-next-line max-params10-const pipeToSubprocess = async (t, readableFdNumber, writableFdNumber, from, to, readableOptions = {}, writableOptions = {}) => {11+const 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 };16 16-test('pipe(...) can pipe', pipeToSubprocess, 1, 0);17-test('pipe(..., {from: "stdout"}) can pipe', pipeToSubprocess, 1, 0, 'stdout');18-test('pipe(..., {from: "fd1"}) can pipe', pipeToSubprocess, 1, 0, 'fd1');19-test('pipe(..., {from: "stderr"}) can pipe stderr', pipeToSubprocess, 2, 0, 'stderr');20-test('pipe(..., {from: "fd2"}) can pipe', pipeToSubprocess, 2, 0, 'fd2');21-test('pipe(..., {from: "fd3"}) can pipe', pipeToSubprocess, 3, 0, 'fd3', undefined, fullStdio);22-test('pipe(..., {from: "all"}) can pipe stdout', pipeToSubprocess, 1, 0, 'all', undefined, {all: true});23-test('pipe(..., {from: "all"}) can pipe stderr', pipeToSubprocess, 2, 0, 'all', undefined, {all: true});24-test('pipe(..., {from: "all"}) can pipe stdout even with "stderr: ignore"', pipeToSubprocess, 1, 0, 'all', undefined, {all: true, stderr: 'ignore'});25-test('pipe(..., {from: "all"}) can pipe stderr even with "stdout: ignore"', pipeToSubprocess, 2, 0, 'all', undefined, {all: true, stdout: 'ignore'});26-test('pipe(..., {to: "stdin"}) can pipe', pipeToSubprocess, 1, 0, undefined, 'stdin');27-test('pipe(..., {to: "fd0"}) can pipe', pipeToSubprocess, 1, 0, undefined, 'fd0');28-test('pipe(..., {to: "fd3"}) can pipe', pipeToSubprocess, 1, 3, undefined, 'fd3', {}, fullReadableStdio());17+test('pipe(...) can pipe', () => pipeToSubprocess(1, 0));18+test('pipe(..., {from: "stdout"}) can pipe', () => pipeToSubprocess(1, 0, 'stdout'));19+test('pipe(..., {from: "fd1"}) can pipe', () => pipeToSubprocess(1, 0, 'fd1'));20+test('pipe(..., {from: "stderr"}) can pipe stderr', () => pipeToSubprocess(2, 0, 'stderr'));21+test('pipe(..., {from: "fd2"}) can pipe', () => pipeToSubprocess(2, 0, 'fd2'));22+test('pipe(..., {from: "fd3"}) can pipe', () => pipeToSubprocess(3, 0, 'fd3', undefined, fullStdio));23+test('pipe(..., {from: "all"}) can pipe stdout', () => pipeToSubprocess(1, 0, 'all', undefined, {all: true}));24+test('pipe(..., {from: "all"}) can pipe stderr', () => pipeToSubprocess(2, 0, 'all', undefined, {all: true}));25+test('pipe(..., {from: "all"}) can pipe stdout even with "stderr: ignore"', () => pipeToSubprocess(1, 0, 'all', undefined, {all: true, stderr: 'ignore'}));26+test('pipe(..., {from: "all"}) can pipe stderr even with "stdout: ignore"', () => pipeToSubprocess(2, 0, 'all', undefined, {all: true, stdout: 'ignore'}));27+test('pipe(..., {to: "stdin"}) can pipe', () => pipeToSubprocess(1, 0, undefined, 'stdin'));28+test('pipe(..., {to: "fd0"}) can pipe', () => pipeToSubprocess(1, 0, undefined, 'fd0'));29+test('pipe(..., {to: "fd3"}) can pipe', () => pipeToSubprocess(1, 3, undefined, 'fd3', {}, fullReadableStdio()));modified:test/pipe/streaming.js+170 added-168 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {PassThrough} from 'node:stream';3-import test from 'ava';4+import test from 'node:test';5+import {assertRejects, assertLike} from '../helpers/assert.js';6 import {execa} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {foobarString} from '../helpers/input.js';9 import {assertMaxListeners} from '../helpers/listeners.js';1 unmodified line11 import {PARALLEL_COUNT} from '../helpers/parallel.js';12 13 setFixtureDirectory();14 13-test('Can pipe two sources to same destination', async t => {15+test('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);21 20- 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 });28 27-test('Can pipe three sources to same destination', async t => {29+test('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);37 36- 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 });46 45-test.serial('Can pipe many sources to same destination', async t => {46- const checkMaxListeners = assertMaxListeners(t);47+test('Can pipe many sources to same destination', async () => {48+ const checkMaxListeners = assertMaxListeners();49 50 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));54 55 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));60 61 checkMaxListeners();62 });63 62-test.serial('Can pipe same source to many destinations', async t => {63- const checkMaxListeners = assertMaxListeners(t);64+test('Can pipe same source to many destinations', async () => {65+ const checkMaxListeners = assertMaxListeners();66 67 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));71 70- 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);76 77 checkMaxListeners();78 });79 78-test('Can pipe two streams from same subprocess to same destination', async t => {80+test('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'});85 84- 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 });91 90-test('Can pipe same source to two streams from same subprocess', async t => {92+test('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'});97 96- 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 });103 102-test('Can pipe a new source to same destination after some source has already written', async t => {104+test('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);109 110 passThroughStream.write('foo');111 const firstWrite = await once(destination.stdout, 'data');110- t.is(firstWrite.toString(), 'foo');112+ assert.equal(firstWrite.toString(), 'foo');113 114 const secondSource = execa('noop.js', ['bar']);115 const secondPipePromise = secondSource.pipe(destination);116 passThroughStream.end();117 116- 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 });124 123-test('Can pipe a second source to same destination after destination has already ended', async t => {125+test('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);129 128- 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);133 134 const secondSource = execa('noop.js', [foobarString]);135 const secondPipePromise = secondSource.pipe(destination);136 135- 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 });140 139-test('Can pipe same source to a second destination after source has already ended', async t => {141+test('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);145 144- 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);149 150 const secondDestination = execa('stdin.js');151 const secondPipePromise = source.pipe(secondDestination);152 151- 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 });156 155-test('Can pipe a new source to same destination after some but not all sources have ended', async t => {157+test('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);164 163- t.like(await source, {stdout: foobarString});165+ assertLike(await source, {stdout: foobarString});166 167 const thirdSource = execa('noop.js', [foobarString]);168 const thirdPipePromise = thirdSource.pipe(destination);169 passThroughStream.end(`${foobarString}\n`);170 169- 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 });178 177-test('Can pipe two subprocesses already ended', async t => {179+test('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);185 184- 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 });190 189-test('Can pipe to same destination through multiple paths', async t => {191+test('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);198 197- 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 });206 205-test('Can pipe two sources to same destination in objectMode', async t => {207+test('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);218 219 const stdinTransform = {220 * transform([chunk]) {221 yield chunk;3 unmodified lines225 const destination = execa('stdin.js', {stdin: stdinTransform});226 const pipePromise = source.pipe(destination);227 const secondPipePromise = secondSource.pipe(destination);228 227- 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 });235 234-test('Can pipe one source to two destinations', async t => {236+test('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);242 241- 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 });249 248-test('Can pipe one source to three destinations', async t => {250+test('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);258 257- 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 });267 266-test('Can create a series of pipes', async t => {268+test('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);274 273- 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 });281 280-test('Returns pipedFrom on success', async t => {282+test('Returns pipedFrom on success', async () => {283 const source = execa('noop.js', [foobarString]);284 const destination = execa('stdin.js');285 const pipePromise = source.pipe(destination);286 287 const destinationResult = await destination;286- t.deepEqual(destinationResult.pipedFrom, []);288+ assert.deepEqual(destinationResult.pipedFrom, []);289 const sourceResult = await source;290 289- 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 });295 294-test('Returns pipedFrom on deep success', async t => {296+test('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);302 303 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;308 307- 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 });315 314-test('Returns pipedFrom on source failure', async t => {316+test('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);320 321 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);324 323- 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 });329 328-test('Returns pipedFrom on destination failure', async t => {330+test('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);334 333- const destinationResult = await t.throwsAsync(destination);335+ const destinationResult = await assertRejects(destination);336 const sourceResult = await source;337 336- 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 });342 341-test('Returns pipedFrom on source + destination failure', async t => {343+test('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);347 346- 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);350 349- 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 });355 354-test('Returns pipedFrom on deep failure', async t => {356+test('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);362 361- 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);367 366- 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 });374 373-test('Returns pipedFrom from multiple sources', async t => {375+test('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);381 382 const destinationResult = await destination;381- t.deepEqual(destinationResult.pipedFrom, []);383+ assert.deepEqual(destinationResult.pipedFrom, []);384 const sourceResult = await source;385 const secondSourceResult = await secondSource;386 385- 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 });393 392-test('Returns pipedFrom from already ended subprocesses', async t => {394+test('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);400 401 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, []);405 404- 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 });410 409-test('Does not return nor set pipedFrom on signal abort', async t => {411+test('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});416 417 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 });424 423-test('Can pipe same source to same destination twice', async t => {425+test('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);430 431 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: []});435 434- 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 });443 444 // `to: 'fd3'` and higher requires the `stdio` option, which cannot be combined with the `stdin` option that piping sets by default443-test('Can pipe to an additional file descriptor of a destination with the "stdio" option', async t => {445+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa} from '../../index.js';4 import {foobarString} from '../helpers/input.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {assertPipeError} from '../helpers/pipe.js';7+import {assertLike} from '../helpers/assert.js';8 9 setFixtureDirectory();10 9-test('Destination stream is ended when first argument is invalid', async t => {11+test('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);15 14- 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 });20 19-test('Destination stream is ended when first argument is invalid - $', async t => {21+test('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 });25 24-test('Source stream is aborted when second argument is invalid', async t => {26+test('Source stream is aborted when second argument is invalid', async () => {27 const source = execa('noop.js', [foobarString]);28 const pipePromise = source.pipe(false);29 28- 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 });33 32-test('Both arguments might be invalid', async t => {34+test('Both arguments might be invalid', async () => {35 const source = execa('empty.js', {stdout: 'ignore'});36 const pipePromise = source.pipe(false);37 36- 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 });42 43 // 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.42-test('Destination subprocess error is not unhandled when the "to" option is invalid', async t => {45+test('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 });49 47-test('Destination subprocess is terminated when the "to" option is invalid', async t => {50+test('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 });54 52-test('Destination subprocess passed by the user is not terminated when the "to" option is invalid', async t => {55+test('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'});59 57- 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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {defaultHighWaterMark} from '../helpers/stream.js';6 import {foobarString} from '../helpers/input.js';9 unmodified lines16 const doubleFoobarArrayFull = [foobarStringFull, foobarStringFull];17 const doubleFoobarArray = [foobarString, foobarString];18 19 // eslint-disable-next-line max-params19-const testAllBoth = async (t, expectedOutput, encoding, lines, stripFinalNewline, isFailure, execaMethod) => {20+const 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 };32 33 const fdOne = {stderr: true};34 const fdBoth = {stdout: true, stderr: true};35 35-test('result.all is defined', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execa);36-test('result.all is defined, encoding "buffer"', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execa);37-test('result.all is defined, lines', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execa);38-test('result.all is defined, lines, fd-specific one', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execa);39-test('result.all is defined, lines, fd-specific both', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execa);40-test('result.all is defined, stripFinalNewline', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execa);41-test('result.all is defined, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execa);42-test('result.all is defined, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execa);43-test('result.all is defined, encoding "buffer", stripFinalNewline', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execa);44-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execa);45-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execa);46-test('result.all is defined, lines, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execa);47-test('result.all is defined, lines, fd-specific one, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execa);48-test('result.all is defined, lines, fd-specific both, stripFinalNewline', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execa);49-test('result.all is defined, lines, stripFinalNewline, fd-specific one', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execa);50-test('result.all is defined, lines, stripFinalNewline, fd-specific both', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execa);51-test('result.all is defined, failure', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execa);52-test('result.all is defined, encoding "buffer", failure', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execa);53-test('result.all is defined, lines, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execa);54-test('result.all is defined, lines, fd-specific one, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execa);55-test('result.all is defined, lines, fd-specific both, failure', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execa);56-test('result.all is defined, stripFinalNewline, failure', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execa);57-test('result.all is defined, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execa);58-test('result.all is defined, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execa);59-test('result.all is defined, encoding "buffer", stripFinalNewline, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execa);60-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execa);61-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execa);62-test('result.all is defined, lines, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execa);63-test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execa);64-test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execa);65-test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execa);66-test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execa);67-test('result.all is defined, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, false, execaSync);68-test('result.all is defined, encoding "buffer", sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execaSync);69-test('result.all is defined, lines, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, false, execaSync);70-test('result.all is defined, lines, fd-specific one, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, false, execaSync);71-test('result.all is defined, lines, fd-specific both, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execaSync);72-test('result.all is defined, stripFinalNewline, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, false, execaSync);73-test('result.all is defined, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, false, execaSync);74-test('result.all is defined, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, false, execaSync);75-test('result.all is defined, encoding "buffer", stripFinalNewline, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, false, execaSync);76-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, false, execaSync);77-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execaSync);78-test('result.all is defined, lines, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, false, execaSync);79-test('result.all is defined, lines, fd-specific one, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, false, execaSync);80-test('result.all is defined, lines, fd-specific both, stripFinalNewline, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, false, execaSync);81-test('result.all is defined, lines, stripFinalNewline, fd-specific one, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, false, execaSync);82-test('result.all is defined, lines, stripFinalNewline, fd-specific both, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, false, execaSync);83-test('result.all is defined, failure, sync', testAllBoth, doubleFoobarStringFull, 'utf8', false, false, true, execaSync);84-test('result.all is defined, encoding "buffer", failure, sync', testAllBoth, doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execaSync);85-test('result.all is defined, lines, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', true, false, true, execaSync);86-test('result.all is defined, lines, fd-specific one, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdOne, false, true, execaSync);87-test('result.all is defined, lines, fd-specific both, failure, sync', testAllBoth, doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execaSync);88-test('result.all is defined, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, true, true, execaSync);89-test('result.all is defined, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdOne, true, execaSync);90-test('result.all is defined, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarString, 'utf8', false, fdBoth, true, execaSync);91-test('result.all is defined, encoding "buffer", stripFinalNewline, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, true, true, execaSync);92-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdOne, true, execaSync);93-test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execaSync);94-test('result.all is defined, lines, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, true, true, execaSync);95-test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdOne, true, true, execaSync);96-test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', fdBoth, true, true, execaSync);97-test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdOne, true, execaSync);98-test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure, sync', testAllBoth, doubleFoobarArray, 'utf8', true, fdBoth, true, execaSync);36+test('result.all is defined', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, false, execa));37+test('result.all is defined, encoding "buffer"', () => testAllBoth(doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execa));38+test('result.all is defined, lines', () => testAllBoth(doubleFoobarArrayFull, 'utf8', true, false, false, execa));39+test('result.all is defined, lines, fd-specific one', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdOne, false, false, execa));40+test('result.all is defined, lines, fd-specific both', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execa));41+test('result.all is defined, stripFinalNewline', () => testAllBoth(doubleFoobarString, 'utf8', false, true, false, execa));42+test('result.all is defined, stripFinalNewline, fd-specific one', () => testAllBoth(doubleFoobarString, 'utf8', false, fdOne, false, execa));43+test('result.all is defined, stripFinalNewline, fd-specific both', () => testAllBoth(doubleFoobarString, 'utf8', false, fdBoth, false, execa));44+test('result.all is defined, encoding "buffer", stripFinalNewline', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, true, false, execa));45+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdOne, false, execa));46+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execa));47+test('result.all is defined, lines, stripFinalNewline', () => testAllBoth(doubleFoobarArray, 'utf8', true, true, false, execa));48+test('result.all is defined, lines, fd-specific one, stripFinalNewline', () => testAllBoth(doubleFoobarArray, 'utf8', fdOne, true, false, execa));49+test('result.all is defined, lines, fd-specific both, stripFinalNewline', () => testAllBoth(doubleFoobarArray, 'utf8', fdBoth, true, false, execa));50+test('result.all is defined, lines, stripFinalNewline, fd-specific one', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdOne, false, execa));51+test('result.all is defined, lines, stripFinalNewline, fd-specific both', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdBoth, false, execa));52+test('result.all is defined, failure', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, true, execa));53+test('result.all is defined, encoding "buffer", failure', () => testAllBoth(doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execa));54+test('result.all is defined, lines, failure', () => testAllBoth(doubleFoobarArrayFull, 'utf8', true, false, true, execa));55+test('result.all is defined, lines, fd-specific one, failure', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdOne, false, true, execa));56+test('result.all is defined, lines, fd-specific both, failure', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execa));57+test('result.all is defined, stripFinalNewline, failure', () => testAllBoth(doubleFoobarString, 'utf8', false, true, true, execa));58+test('result.all is defined, stripFinalNewline, fd-specific one, failure', () => testAllBoth(doubleFoobarString, 'utf8', false, fdOne, true, execa));59+test('result.all is defined, stripFinalNewline, fd-specific both, failure', () => testAllBoth(doubleFoobarString, 'utf8', false, fdBoth, true, execa));60+test('result.all is defined, encoding "buffer", stripFinalNewline, failure', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, true, true, execa));61+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdOne, true, execa));62+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execa));63+test('result.all is defined, lines, stripFinalNewline, failure', () => testAllBoth(doubleFoobarArray, 'utf8', true, true, true, execa));64+test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure', () => testAllBoth(doubleFoobarArray, 'utf8', fdOne, true, true, execa));65+test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure', () => testAllBoth(doubleFoobarArray, 'utf8', fdBoth, true, true, execa));66+test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdOne, true, execa));67+test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdBoth, true, execa));68+test('result.all is defined, sync', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, false, execaSync));69+test('result.all is defined, encoding "buffer", sync', () => testAllBoth(doubleFoobarUint8ArrayFull, 'buffer', false, false, false, execaSync));70+test('result.all is defined, lines, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', true, false, false, execaSync));71+test('result.all is defined, lines, fd-specific one, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdOne, false, false, execaSync));72+test('result.all is defined, lines, fd-specific both, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdBoth, false, false, execaSync));73+test('result.all is defined, stripFinalNewline, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, true, false, execaSync));74+test('result.all is defined, stripFinalNewline, fd-specific one, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, fdOne, false, execaSync));75+test('result.all is defined, stripFinalNewline, fd-specific both, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, fdBoth, false, execaSync));76+test('result.all is defined, encoding "buffer", stripFinalNewline, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, true, false, execaSync));77+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdOne, false, execaSync));78+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdBoth, false, execaSync));79+test('result.all is defined, lines, stripFinalNewline, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, true, false, execaSync));80+test('result.all is defined, lines, fd-specific one, stripFinalNewline, sync', () => testAllBoth(doubleFoobarArray, 'utf8', fdOne, true, false, execaSync));81+test('result.all is defined, lines, fd-specific both, stripFinalNewline, sync', () => testAllBoth(doubleFoobarArray, 'utf8', fdBoth, true, false, execaSync));82+test('result.all is defined, lines, stripFinalNewline, fd-specific one, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdOne, false, execaSync));83+test('result.all is defined, lines, stripFinalNewline, fd-specific both, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdBoth, false, execaSync));84+test('result.all is defined, failure, sync', () => testAllBoth(doubleFoobarStringFull, 'utf8', false, false, true, execaSync));85+test('result.all is defined, encoding "buffer", failure, sync', () => testAllBoth(doubleFoobarUint8ArrayFull, 'buffer', false, false, true, execaSync));86+test('result.all is defined, lines, failure, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', true, false, true, execaSync));87+test('result.all is defined, lines, fd-specific one, failure, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdOne, false, true, execaSync));88+test('result.all is defined, lines, fd-specific both, failure, sync', () => testAllBoth(doubleFoobarArrayFull, 'utf8', fdBoth, false, true, execaSync));89+test('result.all is defined, stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, true, true, execaSync));90+test('result.all is defined, stripFinalNewline, fd-specific one, failure, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, fdOne, true, execaSync));91+test('result.all is defined, stripFinalNewline, fd-specific both, failure, sync', () => testAllBoth(doubleFoobarString, 'utf8', false, fdBoth, true, execaSync));92+test('result.all is defined, encoding "buffer", stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, true, true, execaSync));93+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific one, failure, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdOne, true, execaSync));94+test('result.all is defined, encoding "buffer", stripFinalNewline, fd-specific both, failure, sync', () => testAllBoth(doubleFoobarUint8Array, 'buffer', false, fdBoth, true, execaSync));95+test('result.all is defined, lines, stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, true, true, execaSync));96+test('result.all is defined, lines, fd-specific one, stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', fdOne, true, true, execaSync));97+test('result.all is defined, lines, fd-specific both, stripFinalNewline, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', fdBoth, true, true, execaSync));98+test('result.all is defined, lines, stripFinalNewline, fd-specific one, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdOne, true, execaSync));99+test('result.all is defined, lines, stripFinalNewline, fd-specific both, failure, sync', () => testAllBoth(doubleFoobarArray, 'utf8', true, fdBoth, true, execaSync));100 100-test.serial('result.all shows both `stdout` and `stderr` intermixed', async t => {101+test('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 });105 105-test.serial('result.all shows both `stdout` and `stderr` not intermixed, sync', t => {106+test('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 });110 110-const testAllIgnored = async (t, options, execaMethod) => {111+const testAllIgnored = async (options, execaMethod) => {112 const {all} = await execaMethod('noop.js');112- t.is(all, undefined);113+ assert.equal(all, undefined);114 };115 115-test('result.all is undefined unless opts.all is true', testAllIgnored, {}, execa);116-test('result.all is undefined if opts.all is false', testAllIgnored, {all: false}, execa);117-test('result.all is undefined if ignored', testAllIgnored, {stdio: 'ignore', all: true}, execa);118-test('result.all is undefined unless opts.all is true, sync', testAllIgnored, {}, execaSync);119-test('result.all is undefined if opts.all is false, sync', testAllIgnored, {all: false}, execaSync);120-test('result.all is undefined if ignored, sync', testAllIgnored, {stdio: 'ignore', all: true}, execaSync);116+test('result.all is undefined unless opts.all is true', () => testAllIgnored({}, execa));117+test('result.all is undefined if opts.all is false', () => testAllIgnored({all: false}, execa));118+test('result.all is undefined if ignored', () => testAllIgnored({stdio: 'ignore', all: true}, execa));119+test('result.all is undefined unless opts.all is true, sync', () => testAllIgnored({}, execaSync));120+test('result.all is undefined if opts.all is false, sync', () => testAllIgnored({all: false}, execaSync));121+test('result.all is undefined if ignored, sync', () => testAllIgnored({stdio: 'ignore', all: true}, execaSync));122 122-const testAllProperties = async (t, options) => {123+const 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 };129 129-test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', testAllProperties, {});130-test('subprocess.all has the right objectMode and highWaterMark - stdout only', testAllProperties, {stderr: 'ignore'});131-test('subprocess.all has the right objectMode and highWaterMark - stderr only', testAllProperties, {stdout: 'ignore'});130+test('subprocess.all has the right objectMode and highWaterMark - stdout + stderr', () => testAllProperties({}));131+test('subprocess.all has the right objectMode and highWaterMark - stdout only', () => testAllProperties({stderr: 'ignore'}));132+test('subprocess.all has the right objectMode and highWaterMark - stderr only', () => testAllProperties({stdout: 'ignore'}));133 133-const testAllIgnore = async (t, streamName, otherStreamName) => {134+const 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);141 142 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 };147 147-test('can use all: true with stdout: ignore', testAllIgnore, 'stderr', 'stdout');148-test('can use all: true with stderr: ignore', testAllIgnore, 'stdout', 'stderr');148+test('can use all: true with stdout: ignore', () => testAllIgnore('stderr', 'stdout'));149+test('can use all: true with stderr: ignore', () => testAllIgnore('stdout', 'stderr'));150 150-const testAllIgnoreSync = (t, streamName, otherStreamName) => {151+const 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 };157 157-test('can use all: true with stdout: ignore, sync', testAllIgnoreSync, 'stderr', 'stdout');158-test('can use all: true with stderr: ignore, sync', testAllIgnoreSync, 'stdout', 'stderr');158+test('can use all: true with stdout: ignore, sync', () => testAllIgnoreSync('stderr', 'stdout'));159+test('can use all: true with stderr: ignore, sync', () => testAllIgnoreSync('stdout', 'stderr'));160 160-test('can use all: true with stdout: ignore + stderr: ignore', async t => {161+test('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);166 167 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 });172 172-test('can use all: true with stdout: ignore + stderr: ignore, sync', t => {173+test('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 });179 180 // `all` is split into lines when the `lines` option applies to either file descriptor, even when only one of them uses it181 const foobarTwoLines = `${foobarString}\n${foobarString}`;182 // The fixture writes the same two lines to both `stdout` and `stderr`183 const foobarTwoLinesArray = Array.from({length: 4}, () => `${foobarString}\n`);183-const testAllBothLines = async (t, lines, execaMethod) => {184+const 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 };188 188-test('result.all is split into lines when only stdout uses the lines option', testAllBothLines, {stdout: true}, execa);189-test('result.all is split into lines when only stderr uses the lines option', testAllBothLines, {stderr: true}, execa);190-test('result.all is split into lines when only stdout uses the lines option, sync', testAllBothLines, {stdout: true}, execaSync);191-test('result.all is split into lines when only stderr uses the lines option, sync', testAllBothLines, {stderr: true}, execaSync);189+test('result.all is split into lines when only stdout uses the lines option', () => testAllBothLines({stdout: true}, execa));190+test('result.all is split into lines when only stderr uses the lines option', () => testAllBothLines({stderr: true}, execa));191+test('result.all is split into lines when only stdout uses the lines option, sync', () => testAllBothLines({stdout: true}, execaSync));192+test('result.all is split into lines when only stderr uses the lines option, sync', () => testAllBothLines({stderr: true}, execaSync));193 194 // When only one file descriptor is interleaved into `all`, it must follow that one exactly, including its `stripFinalNewline` value194-const testAllOneFd = async (t, lines, execaMethod) => {195+const 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 };205 205-test('result.all follows stderr when stdout is ignored', testAllOneFd, false, execa);206-test('result.all follows stderr when stdout is ignored, lines', testAllOneFd, true, execa);207-test('result.all follows stderr when stdout is ignored, sync', testAllOneFd, false, execaSync);208-test('result.all follows stderr when stdout is ignored, lines, sync', testAllOneFd, true, execaSync);206+test('result.all follows stderr when stdout is ignored', () => testAllOneFd(false, execa));207+test('result.all follows stderr when stdout is ignored, lines', () => testAllOneFd(true, execa));208+test('result.all follows stderr when stdout is ignored, sync', () => testAllOneFd(false, execaSync));209+test('result.all follows stderr when stdout is ignored, lines, sync', () => testAllOneFd(true, execaSync));210 211 // `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`211-const testAllOneFdOtherLines = async (t, linesFdName, ignoredFdName, stripFinalNewline, execaMethod) => {212+const 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 };221 221-test('result.all is split into lines when only stdout uses the lines option and stderr is ignored', testAllOneFdOtherLines, 'stdout', 'stderr', true, execa);222-test('result.all is split into lines when only stdout uses the lines option and stderr is ignored, stripFinalNewline false', testAllOneFdOtherLines, 'stdout', 'stderr', false, execa);223-test('result.all is split into lines when only stderr uses the lines option and stdout is ignored', testAllOneFdOtherLines, 'stderr', 'stdout', true, execa);224-test('result.all is split into lines when only stdout uses the lines option and stderr is ignored, sync', testAllOneFdOtherLines, 'stdout', 'stderr', true, execaSync);225-test('result.all is split into lines when only stderr uses the lines option and stdout is ignored, sync', testAllOneFdOtherLines, 'stderr', 'stdout', true, execaSync);222+test('result.all is split into lines when only stdout uses the lines option and stderr is ignored', () => testAllOneFdOtherLines('stdout', 'stderr', true, execa));223+test('result.all is split into lines when only stdout uses the lines option and stderr is ignored, stripFinalNewline false', () => testAllOneFdOtherLines('stdout', 'stderr', false, execa));224+test('result.all is split into lines when only stderr uses the lines option and stdout is ignored', () => testAllOneFdOtherLines('stderr', 'stdout', true, execa));225+test('result.all is split into lines when only stdout uses the lines option and stderr is ignored, sync', () => testAllOneFdOtherLines('stdout', 'stderr', true, execaSync));226+test('result.all is split into lines when only stderr uses the lines option and stdout is ignored, sync', () => testAllOneFdOtherLines('stderr', 'stdout', true, execaSync));227+228+// `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`.230+const 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+};239+240+test('result.all is undefined when no file descriptor is buffered', () => testAllNoFd(false, execa));241+test('result.all is undefined when no file descriptor is buffered, lines', () => testAllNoFd(true, execa));242+test('result.all is undefined when no file descriptor is buffered, sync', () => testAllNoFd(false, execaSync));243+test('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
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {setTimeout} from 'node:timers/promises';3-import test from 'ava';4+import test from 'node:test';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {fullStdio, getStdio} from '../helpers/stdio.js';8 9 setFixtureDirectory();10 10-const testBufferIgnore = async (t, fdNumber, all) => {11- await t.notThrowsAsync(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));11+const testBufferIgnore = async (fdNumber, all) => {12+ await assert.doesNotReject(execa('max-buffer.js', [`${fdNumber}`], {...getStdio(fdNumber, 'ignore'), buffer: false, all}));13 };14 14-test('Subprocess buffers stdout, which does not prevent exit if ignored', testBufferIgnore, 1, false);15-test('Subprocess buffers stderr, which does not prevent exit if ignored', testBufferIgnore, 2, false);16-test('Subprocess buffers all, which does not prevent exit if ignored', testBufferIgnore, 1, true);15+test('Subprocess buffers stdout, which does not prevent exit if ignored', () => testBufferIgnore(1, false));16+test('Subprocess buffers stderr, which does not prevent exit if ignored', () => testBufferIgnore(2, false));17+test('Subprocess buffers all, which does not prevent exit if ignored', () => testBufferIgnore(1, true));18 18-const testBufferNotRead = async (t, fdNumber, all) => {19+const 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 };23 23-test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, false);24-test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', testBufferNotRead, 2, false);25-test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', testBufferNotRead, 3, false);26-test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', testBufferNotRead, 1, true);24+test('Subprocess buffers stdout, which does not prevent exit if not read and buffer is false', () => testBufferNotRead(1, false));25+test('Subprocess buffers stderr, which does not prevent exit if not read and buffer is false', () => testBufferNotRead(2, false));26+test('Subprocess buffers stdio[*], which does not prevent exit if not read and buffer is false', () => testBufferNotRead(3, false));27+test('Subprocess buffers all, which does not prevent exit if not read and buffer is false', () => testBufferNotRead(1, true));28 28-const testBufferRead = async (t, fdNumber, all) => {29+const 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 };35 35-test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', testBufferRead, 1, false);36-test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', testBufferRead, 2, false);37-test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', testBufferRead, 3, false);38-test('Subprocess buffers all, which does not prevent exit if read and buffer is false', testBufferRead, 1, true);36+test('Subprocess buffers stdout, which does not prevent exit if read and buffer is false', () => testBufferRead(1, false));37+test('Subprocess buffers stderr, which does not prevent exit if read and buffer is false', () => testBufferRead(2, false));38+test('Subprocess buffers stdio[*], which does not prevent exit if read and buffer is false', () => testBufferRead(3, false));39+test('Subprocess buffers all, which does not prevent exit if read and buffer is false', () => testBufferRead(1, true));40 40-const testBufferExit = async (t, fdNumber, fixtureName, reject) => {41+const 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 };47 47-test('Subprocess buffers stdout before it is read', testBufferExit, 1, 'noop-delay.js', true);48-test('Subprocess buffers stderr before it is read', testBufferExit, 2, 'noop-delay.js', true);49-test('Subprocess buffers stdio[*] before it is read', testBufferExit, 3, 'noop-delay.js', true);50-test('Subprocess buffers stdout right away, on successfully exit', testBufferExit, 1, 'noop-fd.js', true);51-test('Subprocess buffers stderr right away, on successfully exit', testBufferExit, 2, 'noop-fd.js', true);52-test('Subprocess buffers stdio[*] right away, on successfully exit', testBufferExit, 3, 'noop-fd.js', true);53-test('Subprocess buffers stdout right away, on failure', testBufferExit, 1, 'noop-fail.js', false);54-test('Subprocess buffers stderr right away, on failure', testBufferExit, 2, 'noop-fail.js', false);55-test('Subprocess buffers stdio[*] right away, on failure', testBufferExit, 3, 'noop-fail.js', false);48+test('Subprocess buffers stdout before it is read', () => testBufferExit(1, 'noop-delay.js', true));49+test('Subprocess buffers stderr before it is read', () => testBufferExit(2, 'noop-delay.js', true));50+test('Subprocess buffers stdio[*] before it is read', () => testBufferExit(3, 'noop-delay.js', true));51+test('Subprocess buffers stdout right away, on successfully exit', () => testBufferExit(1, 'noop-fd.js', true));52+test('Subprocess buffers stderr right away, on successfully exit', () => testBufferExit(2, 'noop-fd.js', true));53+test('Subprocess buffers stdio[*] right away, on successfully exit', () => testBufferExit(3, 'noop-fd.js', true));54+test('Subprocess buffers stdout right away, on failure', () => testBufferExit(1, 'noop-fail.js', false));55+test('Subprocess buffers stderr right away, on failure', () => testBufferExit(2, 'noop-fail.js', false));56+test('Subprocess buffers stdio[*] right away, on failure', () => testBufferExit(3, 'noop-fail.js', false));57 57-const testBufferDirect = async (t, fdNumber) => {58+const 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 };65 65-test('Subprocess buffers stdout right away, even if directly read', testBufferDirect, 1);66-test('Subprocess buffers stderr right away, even if directly read', testBufferDirect, 2);67-test('Subprocess buffers stdio[*] right away, even if directly read', testBufferDirect, 3);66+test('Subprocess buffers stdout right away, even if directly read', () => testBufferDirect(1));67+test('Subprocess buffers stderr right away, even if directly read', () => testBufferDirect(2));68+test('Subprocess buffers stdio[*] right away, even if directly read', () => testBufferDirect(3));69 69-const testBufferDestroyOnEnd = async (t, fdNumber) => {70+const 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 };76 76-test('subprocess.stdout must be read right away', testBufferDestroyOnEnd, 1);77-test('subprocess.stderr must be read right away', testBufferDestroyOnEnd, 2);78-test('subprocess.stdio[*] must be read right away', testBufferDestroyOnEnd, 3);77+test('subprocess.stdout must be read right away', () => testBufferDestroyOnEnd(1));78+test('subprocess.stderr must be read right away', () => testBufferDestroyOnEnd(2));79+test('subprocess.stdio[*] must be read right away', () => testBufferDestroyOnEnd(3));modified:test/resolve/exit.js+36 added-34 removed
1+import assert from 'node:assert/strict';2 import process from 'node:process';2-import test from 'ava';3+import test from 'node:test';4+import {assertRejects} from '../helpers/assert.js';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 8 const isWindows = process.platform === 'win32';9 10 setFixtureDirectory();11 10-test('exitCode is 0 on success', async t => {12+test('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 });16 15-const 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);17+const 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 };24 23-test('exitCode is 2', testExitCode, 2);24-test('exitCode is 3', testExitCode, 3);25-test('exitCode is 4', testExitCode, 4);25+test('exitCode is 2', () => testExitCode(2));26+test('exitCode is 3', () => testExitCode(3));27+test('exitCode is 4', () => testExitCode(4));28 29 if (!isWindows) {28- test('error.signal is SIGINT', async t => {30+ test('error.signal is SIGINT', async () => {31 const subprocess = execa('forever.js');32 33 process.kill(subprocess.pid, 'SIGINT');34 33- 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 });38 37- test('error.signalDescription is defined', async t => {39+ test('error.signalDescription is defined', async () => {40 const subprocess = execa('forever.js');41 42 process.kill(subprocess.pid, 'SIGINT');43 42- 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 });47 46- test('error.signal is SIGTERM', async t => {48+ test('error.signal is SIGTERM', async () => {49 const subprocess = execa('forever.js');50 51 process.kill(subprocess.pid, 'SIGTERM');52 51- 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 });56 55- 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 });61 60- test('exitCode is undefined on signal termination', async t => {62+ test('exitCode is undefined on signal termination', async () => {63 const subprocess = execa('forever.js');64 65 process.kill(subprocess.pid);66 65- const {exitCode} = await t.throwsAsync(subprocess);66- t.is(exitCode, undefined);67+ const {exitCode} = await assertRejects(subprocess);68+ assert.equal(exitCode, undefined);69 });70 }71 70-test('result.signal is undefined for successful execution', async t => {72+test('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 });76 75-test('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);77+test('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 });81 80-test('result.signalDescription is undefined for successful execution', async t => {82+test('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
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';2-import test from 'ava';3+import test from 'node:test';4 import getStream from 'get-stream';5+import {assertRejects, assertLike} from '../helpers/assert.js';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {fullStdio} from '../helpers/stdio.js';9 import {foobarString, foobarUppercase, foobarUppercaseUint8Array} from '../helpers/input.js';10 import {resultGenerator, uppercaseGenerator, uppercaseBufferGenerator} from '../helpers/generator.js';11 12 setFixtureDirectory();13 12-const testLateStream = async (t, fdNumber, all) => {14+const testLateStream = async (fdNumber, all) => {15 const subprocess = execa('noop-fd-ipc.js', [`${fdNumber}`, foobarString], {16 ...fullStdio,17 ipc: true,18 buffer: false,5 unmodified lines24 all ? getStream(subprocess.all) : undefined,25 subprocess,26 ]);27 26- t.is(output, '');28+ assert.equal(output, '');29 30 if (all) {29- t.is(allOutput, '');31+ assert.equal(allOutput, '');32 }33 };34 33-test('Lacks some data when stdout is read too late `buffer` set to `false`', testLateStream, 1, false);34-test('Lacks some data when stderr is read too late `buffer` set to `false`', testLateStream, 2, false);35-test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', testLateStream, 3, false);36-test('Lacks some data when all is read too late `buffer` set to `false`', testLateStream, 1, true);35+test('Lacks some data when stdout is read too late `buffer` set to `false`', () => testLateStream(1, false));36+test('Lacks some data when stderr is read too late `buffer` set to `false`', () => testLateStream(2, false));37+test('Lacks some data when stdio[*] is read too late `buffer` set to `false`', () => testLateStream(3, false));38+test('Lacks some data when all is read too late `buffer` set to `false`', () => testLateStream(1, true));39 40 const getFirstDataEvent = async stream => {41 const [output] = await once(stream, 'data');42 return output.toString();43 };44 43-// eslint-disable-next-line max-params44-const testIterationBuffer = async (t, fdNumber, buffer, useDataEvents, all) => {45+const 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 lines52 ]);53 54 const expectedResult = buffer ? foobarString : undefined;55 55- t.is(result.stdio[fdNumber], expectedResult);56- t.is(output, foobarString);56+ assert.equal(result.stdio[fdNumber], expectedResult);57+ assert.equal(output, foobarString);58 58- if (all) {59- t.is(result.all, expectedResult);60- t.is(allOutput, foobarString);59+ if (!all) {60+ return;61 }62+63+ assert.equal(result.all, expectedResult);64+ assert.equal(allOutput, foobarString);65 };66 64-test('Can iterate stdout when `buffer` set to `false`', testIterationBuffer, 1, false, false, false);65-test('Can iterate stderr when `buffer` set to `false`', testIterationBuffer, 2, false, false, false);66-test('Can iterate stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, false, false);67-test('Can iterate all when `buffer` set to `false`', testIterationBuffer, 1, false, false, true);68-test('Can iterate stdout when `buffer` set to `true`', testIterationBuffer, 1, true, false, false);69-test('Can iterate stderr when `buffer` set to `true`', testIterationBuffer, 2, true, false, false);70-test('Can iterate stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, false, false);71-test('Can iterate all when `buffer` set to `true`', testIterationBuffer, 1, true, false, true);72-test('Can listen to `data` events on stdout when `buffer` set to `false`', testIterationBuffer, 1, false, true, false);73-test('Can listen to `data` events on stderr when `buffer` set to `false`', testIterationBuffer, 2, false, true, false);74-test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', testIterationBuffer, 3, false, true, false);75-test('Can listen to `data` events on all when `buffer` set to `false`', testIterationBuffer, 1, false, true, true);76-test('Can listen to `data` events on stdout when `buffer` set to `true`', testIterationBuffer, 1, true, true, false);77-test('Can listen to `data` events on stderr when `buffer` set to `true`', testIterationBuffer, 2, true, true, false);78-test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', testIterationBuffer, 3, true, true, false);79-test('Can listen to `data` events on all when `buffer` set to `true`', testIterationBuffer, 1, true, true, true);67+test('Can iterate stdout when `buffer` set to `false`', () => testIterationBuffer(1, false, false, false));68+test('Can iterate stderr when `buffer` set to `false`', () => testIterationBuffer(2, false, false, false));69+test('Can iterate stdio[*] when `buffer` set to `false`', () => testIterationBuffer(3, false, false, false));70+test('Can iterate all when `buffer` set to `false`', () => testIterationBuffer(1, false, false, true));71+test('Can iterate stdout when `buffer` set to `true`', () => testIterationBuffer(1, true, false, false));72+test('Can iterate stderr when `buffer` set to `true`', () => testIterationBuffer(2, true, false, false));73+test('Can iterate stdio[*] when `buffer` set to `true`', () => testIterationBuffer(3, true, false, false));74+test('Can iterate all when `buffer` set to `true`', () => testIterationBuffer(1, true, false, true));75+test('Can listen to `data` events on stdout when `buffer` set to `false`', () => testIterationBuffer(1, false, true, false));76+test('Can listen to `data` events on stderr when `buffer` set to `false`', () => testIterationBuffer(2, false, true, false));77+test('Can listen to `data` events on stdio[*] when `buffer` set to `false`', () => testIterationBuffer(3, false, true, false));78+test('Can listen to `data` events on all when `buffer` set to `false`', () => testIterationBuffer(1, false, true, true));79+test('Can listen to `data` events on stdout when `buffer` set to `true`', () => testIterationBuffer(1, true, true, false));80+test('Can listen to `data` events on stderr when `buffer` set to `true`', () => testIterationBuffer(2, true, true, false));81+test('Can listen to `data` events on stdio[*] when `buffer` set to `true`', () => testIterationBuffer(3, true, true, false));82+test('Can listen to `data` events on all when `buffer` set to `true`', () => testIterationBuffer(1, true, true, true));83 81-const testNoBufferStreamError = async (t, fdNumber, all) => {84+const 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 };91 89-test('Listen to stdout errors even when `buffer` is `false`', testNoBufferStreamError, 1, false);90-test('Listen to stderr errors even when `buffer` is `false`', testNoBufferStreamError, 2, false);91-test('Listen to stdio[*] errors even when `buffer` is `false`', testNoBufferStreamError, 3, false);92-test('Listen to all errors even when `buffer` is `false`', testNoBufferStreamError, 1, true);92+test('Listen to stdout errors even when `buffer` is `false`', () => testNoBufferStreamError(1, false));93+test('Listen to stderr errors even when `buffer` is `false`', () => testNoBufferStreamError(2, false));94+test('Listen to stdio[*] errors even when `buffer` is `false`', () => testNoBufferStreamError(3, false));95+test('Listen to all errors even when `buffer` is `false`', () => testNoBufferStreamError(1, true));96 94-const testOutput = async (t, buffer, execaMethod) => {97+const 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 };101 99-test('buffer: true returns output', testOutput, true, execa);100-test('buffer: true returns output, fd-specific', testOutput, {stderr: false}, execa);101-test('buffer: default returns output', testOutput, undefined, execa);102-test('buffer: default returns output, fd-specific', testOutput, {}, execa);102+test('buffer: true returns output', () => testOutput(true, execa));103+test('buffer: true returns output, fd-specific', () => testOutput({stderr: false}, execa));104+test('buffer: default returns output', () => testOutput(undefined, execa));105+test('buffer: default returns output, fd-specific', () => testOutput({}, execa));106 104-const testNoOutput = async (t, stdioOption, buffer, execaMethod) => {107+const 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 };111 109-test('buffer: false does not return output', testNoOutput, 'pipe', false, execa);110-test('buffer: false does not return output, fd-specific', testNoOutput, 'pipe', {stdout: false}, execa);111-test('buffer: false does not return output, stdout undefined', testNoOutput, undefined, false, execa);112-test('buffer: false does not return output, stdout null', testNoOutput, null, false, execa);113-test('buffer: false does not return output, stdout ["pipe"]', testNoOutput, ['pipe'], false, execa);114-test('buffer: false does not return output, stdout [undefined]', testNoOutput, [undefined], false, execa);115-test('buffer: false does not return output, stdout [null]', testNoOutput, [null], false, execa);116-test('buffer: false does not return output, stdout ["pipe", undefined]', testNoOutput, ['pipe', undefined], false, execa);117-test('buffer: false does not return output, sync', testNoOutput, 'pipe', false, execaSync);118-test('buffer: false does not return output, fd-specific, sync', testNoOutput, 'pipe', {stdout: false}, execaSync);119-test('buffer: false does not return output, stdout undefined, sync', testNoOutput, undefined, false, execaSync);120-test('buffer: false does not return output, stdout null, sync', testNoOutput, null, false, execaSync);121-test('buffer: false does not return output, stdout ["pipe"], sync', testNoOutput, ['pipe'], false, execaSync);122-test('buffer: false does not return output, stdout [undefined], sync', testNoOutput, [undefined], false, execaSync);123-test('buffer: false does not return output, stdout [null], sync', testNoOutput, [null], false, execaSync);124-test('buffer: false does not return output, stdout ["pipe", undefined], sync', testNoOutput, ['pipe', undefined], false, execaSync);112+test('buffer: false does not return output', () => testNoOutput('pipe', false, execa));113+test('buffer: false does not return output, fd-specific', () => testNoOutput('pipe', {stdout: false}, execa));114+test('buffer: false does not return output, stdout undefined', () => testNoOutput(undefined, false, execa));115+test('buffer: false does not return output, stdout null', () => testNoOutput(null, false, execa));116+test('buffer: false does not return output, stdout ["pipe"]', () => testNoOutput(['pipe'], false, execa));117+test('buffer: false does not return output, stdout [undefined]', () => testNoOutput([undefined], false, execa));118+test('buffer: false does not return output, stdout [null]', () => testNoOutput([null], false, execa));119+test('buffer: false does not return output, stdout ["pipe", undefined]', () => testNoOutput(['pipe', undefined], false, execa));120+test('buffer: false does not return output, sync', () => testNoOutput('pipe', false, execaSync));121+test('buffer: false does not return output, fd-specific, sync', () => testNoOutput('pipe', {stdout: false}, execaSync));122+test('buffer: false does not return output, stdout undefined, sync', () => testNoOutput(undefined, false, execaSync));123+test('buffer: false does not return output, stdout null, sync', () => testNoOutput(null, false, execaSync));124+test('buffer: false does not return output, stdout ["pipe"], sync', () => testNoOutput(['pipe'], false, execaSync));125+test('buffer: false does not return output, stdout [undefined], sync', () => testNoOutput([undefined], false, execaSync));126+test('buffer: false does not return output, stdout [null], sync', () => testNoOutput([null], false, execaSync));127+test('buffer: false does not return output, stdout ["pipe", undefined], sync', () => testNoOutput(['pipe', undefined], false, execaSync));128 129 /*130 With `buffer: false`, additional file descriptors must still be passed to the subprocess.131 With synchronous methods, `ignore` is used to avoid buffering, but that only redirects `stdout`/`stderr` to `/dev/null`.132 For other file descriptors, it does not pass them at all, which would make the subprocess fail when writing to them.133 */131-const testNoOutputFdStays = async (t, buffer, execaMethod) => {134+const 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 };139 137-test('buffer: false keeps stdio[*] open', testNoOutputFdStays, false, execa);138-test('buffer: false keeps stdio[*] open, fd-specific', testNoOutputFdStays, {fd3: false}, execa);139-test('buffer: false keeps stdio[*] open, sync', testNoOutputFdStays, false, execaSync);140-test('buffer: false keeps stdio[*] open, fd-specific, sync', testNoOutputFdStays, {fd3: false}, execaSync);140+test('buffer: false keeps stdio[*] open', () => testNoOutputFdStays(false, execa));141+test('buffer: false keeps stdio[*] open, fd-specific', () => testNoOutputFdStays({fd3: false}, execa));142+test('buffer: false keeps stdio[*] open, sync', () => testNoOutputFdStays(false, execaSync));143+test('buffer: false keeps stdio[*] open, fd-specific, sync', () => testNoOutputFdStays({fd3: false}, execaSync));144 142-const testNoOutputFail = async (t, execaMethod) => {145+const 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 };150 148-test('buffer: false does not return output, failure', testNoOutputFail, execa);149-test('buffer: false does not return output, failure, sync', testNoOutputFail, execaSync);151+test('buffer: false does not return output, failure', () => testNoOutputFail(execa));152+test('buffer: false does not return output, failure, sync', () => testNoOutputFail(execaSync));153 151-// eslint-disable-next-line max-params152-const testNoOutputAll = async (t, buffer, bufferStdout, bufferStderr, execaMethod) => {154+const 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 };161 160-test('buffer: {}, all: true', testNoOutputAll, {}, true, true, execa);161-test('buffer: {stdout: false}, all: true', testNoOutputAll, {stdout: false}, false, true, execa);162-test('buffer: {stderr: false}, all: true', testNoOutputAll, {stderr: false}, true, false, execa);163-test('buffer: {all: false}, all: true', testNoOutputAll, {all: false}, false, false, execa);164-test('buffer: {}, all: true, sync', testNoOutputAll, {}, true, true, execaSync);165-test('buffer: {stdout: false}, all: true, sync', testNoOutputAll, {stdout: false}, false, true, execaSync);166-test('buffer: {stderr: false}, all: true, sync', testNoOutputAll, {stderr: false}, true, false, execaSync);167-test('buffer: {all: false}, all: true, sync', testNoOutputAll, {all: false}, false, false, execaSync);162+test('buffer: {}, all: true', () => testNoOutputAll({}, true, true, execa));163+test('buffer: {stdout: false}, all: true', () => testNoOutputAll({stdout: false}, false, true, execa));164+test('buffer: {stderr: false}, all: true', () => testNoOutputAll({stderr: false}, true, false, execa));165+test('buffer: {all: false}, all: true', () => testNoOutputAll({all: false}, false, false, execa));166+test('buffer: {}, all: true, sync', () => testNoOutputAll({}, true, true, execaSync));167+test('buffer: {stdout: false}, all: true, sync', () => testNoOutputAll({stdout: false}, false, true, execaSync));168+test('buffer: {stderr: false}, all: true, sync', () => testNoOutputAll({stderr: false}, true, false, execaSync));169+test('buffer: {all: false}, all: true, sync', () => testNoOutputAll({all: false}, false, false, execaSync));170 171 // `result.all` only contains the buffered file descriptors, so its `stripFinalNewline` must only follow those170-const testNoOutputAllStripFinalNewline = async (t, buffer, stripFinalNewline, execaMethod) => {172+const 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 };176 175-test('buffer: {stderr: false} only follows the buffered "stripFinalNewline" in result.all', testNoOutputAllStripFinalNewline, {stderr: false}, {stdout: false, stderr: true}, execa);176-test('buffer: {stdout: false} only follows the buffered "stripFinalNewline" in result.all', testNoOutputAllStripFinalNewline, {stdout: false}, {stdout: true, stderr: false}, execa);177-test('buffer: {stderr: false} only follows the buffered "stripFinalNewline" in result.all, sync', testNoOutputAllStripFinalNewline, {stderr: false}, {stdout: false, stderr: true}, execaSync);178-test('buffer: {stdout: false} only follows the buffered "stripFinalNewline" in result.all, sync', testNoOutputAllStripFinalNewline, {stdout: false}, {stdout: true, stderr: false}, execaSync);177+test('buffer: {stderr: false} only follows the buffered "stripFinalNewline" in result.all', () => testNoOutputAllStripFinalNewline({stderr: false}, {stdout: false, stderr: true}, execa));178+test('buffer: {stdout: false} only follows the buffered "stripFinalNewline" in result.all', () => testNoOutputAllStripFinalNewline({stdout: false}, {stdout: true, stderr: false}, execa));179+test('buffer: {stderr: false} only follows the buffered "stripFinalNewline" in result.all, sync', () => testNoOutputAllStripFinalNewline({stderr: false}, {stdout: false, stderr: true}, execaSync));180+test('buffer: {stdout: false} only follows the buffered "stripFinalNewline" in result.all, sync', () => testNoOutputAllStripFinalNewline({stdout: false}, {stdout: true, stderr: false}, execaSync));181 182 // `result.all` requires the `all` option, even when only one of the two file descriptors is buffered181-const testNoAllWithoutOption = async (t, buffer, execaMethod) => {183+const 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 };187 186-test('buffer: {stdout: false} does not set result.all', testNoAllWithoutOption, {stdout: false}, execa);187-test('buffer: {stderr: false} does not set result.all', testNoAllWithoutOption, {stderr: false}, execa);188-test('buffer: {stdout: false} does not set result.all, sync', testNoAllWithoutOption, {stdout: false}, execaSync);189-test('buffer: {stderr: false} does not set result.all, sync', testNoAllWithoutOption, {stderr: false}, execaSync);188+test('buffer: {stdout: false} does not set result.all', () => testNoAllWithoutOption({stdout: false}, execa));189+test('buffer: {stderr: false} does not set result.all', () => testNoAllWithoutOption({stderr: false}, execa));190+test('buffer: {stdout: false} does not set result.all, sync', () => testNoAllWithoutOption({stdout: false}, execaSync));191+test('buffer: {stderr: false} does not set result.all, sync', () => testNoAllWithoutOption({stderr: false}, execaSync));192 191-const testTransform = async (t, objectMode, execaMethod) => {193+const 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 };202 201-test('buffer: false still runs transforms', testTransform, false, execa);202-test('buffer: false still runs transforms, objectMode', testTransform, true, execa);203-test('buffer: false still runs transforms, sync', testTransform, false, execaSync);204-test('buffer: false still runs transforms, objectMode, sync', testTransform, true, execaSync);203+test('buffer: false still runs transforms', () => testTransform(false, execa));204+test('buffer: false still runs transforms, objectMode', () => testTransform(true, execa));205+test('buffer: false still runs transforms, sync', () => testTransform(false, execaSync));206+test('buffer: false still runs transforms, objectMode, sync', () => testTransform(true, execaSync));207 206-const testTransformBinary = async (t, objectMode, execaMethod) => {208+const 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 };218 217-test('buffer: false still runs transforms, encoding "buffer"', testTransformBinary, false, execa);218-test('buffer: false still runs transforms, encoding "buffer", objectMode', testTransformBinary, true, execa);219-test('buffer: false still runs transforms, encoding "buffer", sync', testTransformBinary, false, execaSync);220-test('buffer: false still runs transforms, encoding "buffer", objectMode, sync', testTransformBinary, true, execaSync);219+test('buffer: false still runs transforms, encoding "buffer"', () => testTransformBinary(false, execa));220+test('buffer: false still runs transforms, encoding "buffer", objectMode', () => testTransformBinary(true, execa));221+test('buffer: false still runs transforms, encoding "buffer", sync', () => testTransformBinary(false, execaSync));222+test('buffer: false still runs transforms, encoding "buffer", objectMode, sync', () => testTransformBinary(true, execaSync));223 222-const testStreamEnd = async (t, fdNumber, buffer) => {224+const 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 };231 230-test('buffer: false > emits end event on stdout when promise is rejected', testStreamEnd, 1, false);231-test('buffer: false > emits end event on stderr when promise is rejected', testStreamEnd, 2, false);232-test('buffer: false > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, false);233-test('buffer: true > emits end event on stdout when promise is rejected', testStreamEnd, 1, true);234-test('buffer: true > emits end event on stderr when promise is rejected', testStreamEnd, 2, true);235-test('buffer: true > emits end event on stdio[*] when promise is rejected', testStreamEnd, 3, true);232+test('buffer: false > emits end event on stdout when promise is rejected', () => testStreamEnd(1, false));233+test('buffer: false > emits end event on stderr when promise is rejected', () => testStreamEnd(2, false));234+test('buffer: false > emits end event on stdio[*] when promise is rejected', () => testStreamEnd(3, false));235+test('buffer: true > emits end event on stdout when promise is rejected', () => testStreamEnd(1, true));236+test('buffer: true > emits end event on stderr when promise is rejected', () => testStreamEnd(2, true));237+test('buffer: true > emits end event on stdio[*] when promise is rejected', () => testStreamEnd(3, true));238 239 // 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.241 const LARGE_OUTPUT = 1e6;242 241-const testNoBufferAllBackpressure = async (t, fdNumber, buffer) => {243+const 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 };248 247-// Without the fix, the subprocess hangs, so it is given a `timeout` to turn the hang into a failed assertion248-test('all: true does not hang on a large stdout with buffer: {stderr: false}', testNoBufferAllBackpressure, 1, {stderr: false});249-test('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 out250+test('all: true does not hang on a large stdout with buffer: {stderr: false}', () => testNoBufferAllBackpressure(1, {stderr: false}));251+test('all: true does not hang on a large stderr with buffer: {stdout: false}', () => testNoBufferAllBackpressure(2, {stdout: false}));252 253 // `subprocess.all` must keep interleaving a file descriptor which is not buffered, even though Execa does not read it itself252-const testAllStreamWithNoBuffer = async (t, fdNumber, optionName) => {254+const 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 };259 258-test('subprocess.all includes an unbuffered stdout', testAllStreamWithNoBuffer, 1, 'stdout');259-test('subprocess.all includes an unbuffered stderr', testAllStreamWithNoBuffer, 2, 'stderr');260+test('subprocess.all includes an unbuffered stdout', () => testAllStreamWithNoBuffer(1, 'stdout'));261+test('subprocess.all includes an unbuffered stderr', () => testAllStreamWithNoBuffer(2, 'stderr'));modified:test/resolve/stdio.js+66 added-54 removed
1+import assert from 'node:assert/strict';2 import {setTimeout} from 'node:timers/promises';2-import test from 'ava';3-import {execa} from '../../index.js';3+import test from 'node:test';4+import {assertRejects} from '../helpers/assert.js';5+import {execa, execaSync} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {8 fullStdio,9 getStdio,8 unmodified lines18 ? getStdio(3, [new Uint8Array(), infiniteGenerator()])19 : {});20 const getStreamOutputSubprocess = fdNumber => execa('noop-repeat.js', [`${fdNumber}`], fdNumber === 3 ? fullStdio : {});21 20-const assertStreamInputError = (t, {exitCode, signal, isTerminated, failed}) => {21- t.is(exitCode, 0);22- t.is(signal, undefined);23- t.false(isTerminated);24- t.true(failed);22+const 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 };28 27-const assertStreamOutputError = (t, fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {29+const assertStreamOutputError = (fdNumber, {exitCode, signal, isTerminated, failed, stderr}) => {30 if (fdNumber !== 3) {29- t.is(exitCode, 1);31+ assert.equal(exitCode, 1);32 }33 32- 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);37 36- assertEpipe(t, stderr, fdNumber);38+ assertEpipe(stderr, fdNumber);39 };40 39-const testStreamInputAbort = async (t, fdNumber) => {41+const 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 };47 46-test('Aborting stdin should not make the subprocess exit', testStreamInputAbort, 0);47-test('Aborting input stdio[*] should not make the subprocess exit', testStreamInputAbort, 3);48+test('Aborting stdin should not make the subprocess exit', () => testStreamInputAbort(0));49+test('Aborting input stdio[*] should not make the subprocess exit', () => testStreamInputAbort(3));50 49-const testStreamOutputAbort = async (t, fdNumber) => {51+const 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 };57 56-test('Aborting stdout should not make the subprocess exit', testStreamOutputAbort, 1);57-test('Aborting stderr should not make the subprocess exit', testStreamOutputAbort, 2);58-test('Aborting output stdio[*] should not make the subprocess exit', testStreamOutputAbort, 3);58+test('Aborting stdout should not make the subprocess exit', () => testStreamOutputAbort(1));59+test('Aborting stderr should not make the subprocess exit', () => testStreamOutputAbort(2));60+test('Aborting output stdio[*] should not make the subprocess exit', () => testStreamOutputAbort(3));61 60-const testStreamInputDestroy = async (t, fdNumber) => {62+const 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 };70 69-test('Destroying stdin should not make the subprocess exit', testStreamInputDestroy, 0);70-test('Destroying input stdio[*] should not make the subprocess exit', testStreamInputDestroy, 3);71+test('Destroying stdin should not make the subprocess exit', () => testStreamInputDestroy(0));72+test('Destroying input stdio[*] should not make the subprocess exit', () => testStreamInputDestroy(3));73 72-const testStreamOutputDestroy = async (t, fdNumber) => {74+const 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 };82 81-test('Destroying stdout should not make the subprocess exit', testStreamOutputDestroy, 1);82-test('Destroying stderr should not make the subprocess exit', testStreamOutputDestroy, 2);83-test('Destroying output stdio[*] should not make the subprocess exit', testStreamOutputDestroy, 3);83+test('Destroying stdout should not make the subprocess exit', () => testStreamOutputDestroy(1));84+test('Destroying stderr should not make the subprocess exit', () => testStreamOutputDestroy(2));85+test('Destroying output stdio[*] should not make the subprocess exit', () => testStreamOutputDestroy(3));86 85-const testStreamInputError = async (t, fdNumber) => {87+const 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 };97 96-test('Errors on stdin should not make the subprocess exit', testStreamInputError, 0);97-test('Errors on input stdio[*] should not make the subprocess exit', testStreamInputError, 3);98+test('Errors on stdin should not make the subprocess exit', () => testStreamInputError(0));99+test('Errors on input stdio[*] should not make the subprocess exit', () => testStreamInputError(3));100 99-const testStreamOutputError = async (t, fdNumber) => {101+const 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 };110 109-test('Errors on stdout should make the subprocess exit', testStreamOutputError, 1);110-test('Errors on stderr should make the subprocess exit', testStreamOutputError, 2);111-test('Errors on output stdio[*] should make the subprocess exit', testStreamOutputError, 3);111+test('Errors on stdout should make the subprocess exit', () => testStreamOutputError(1));112+test('Errors on stderr should make the subprocess exit', () => testStreamOutputError(2));113+test('Errors on output stdio[*] should make the subprocess exit', () => testStreamOutputError(3));114 113-const testWaitOnStreamEnd = async (t, fdNumber) => {115+const 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 };122 121-test('Subprocess waits on stdin before exiting', testWaitOnStreamEnd, 0);122-test('Subprocess waits on stdio[*] before exiting', testWaitOnStreamEnd, 3);123+test('Subprocess waits on stdin before exiting', () => testWaitOnStreamEnd(0));124+test('Subprocess waits on stdio[*] before exiting', () => testWaitOnStreamEnd(3));125+126+// 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.128+const testFailedSpawnStdioLength = async (stdio, expectedLength, execaMethod) => {129+ const {stdio: stdioResult} = await execaMethod('unknown-file.js', {stdio, reject: false});130+ assert.equal(stdioResult.length, expectedLength);131+};132+133+test('result.stdio has one entry per file descriptor when the spawn fails', () => testFailedSpawnStdioLength(fullStdio.stdio, 4, execa));134+test('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
1+import assert from 'node:assert/strict';2 import {setImmediate} from 'node:timers/promises';2-import test from 'ava';3+import test from 'node:test';4+import {assertRejects, assertLike} from '../helpers/assert.js';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {prematureClose} from '../helpers/stdio.js';8 import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';7 unmodified lines16 setFixtureDirectory();17 18 const noop = () => {};19 18-// eslint-disable-next-line max-params19-const testStreamAbortWait = async (t, streamMethod, stream, fdNumber, useTransform) => {20+const 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();26 27 const {stdout} = await subprocess;27- t.is(stdout, '');28- t.true(stream.destroyed);28+ assert.equal(stdout, '');29+ assert.equal(stream.destroyed, true);30 };31 31-test('Keeps running when stdin option is used and subprocess.stdin ends', testStreamAbortWait, noop, noopReadable(), 0, false);32-test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', testStreamAbortWait, noop, noopDuplex(), 0, false);33-test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', testStreamAbortWait, noop, noopReadable(), 3, false);34-test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', testStreamAbortWait, noop, noopReadable(), 0, true);35-test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', testStreamAbortWait, noop, noopDuplex(), 0, true);36-test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', testStreamAbortWait, noop, noopReadable(), 3, true);32+test('Keeps running when stdin option is used and subprocess.stdin ends', () => testStreamAbortWait(noop, noopReadable(), 0, false));33+test('Keeps running when stdin option is used and subprocess.stdin Duplex ends', () => testStreamAbortWait(noop, noopDuplex(), 0, false));34+test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends', () => testStreamAbortWait(noop, noopReadable(), 3, false));35+test('Keeps running when stdin option is used and subprocess.stdin ends, with a transform', () => testStreamAbortWait(noop, noopReadable(), 0, true));36+test('Keeps running when stdin option is used and subprocess.stdin Duplex ends, with a transform', () => testStreamAbortWait(noop, noopDuplex(), 0, true));37+test('Keeps running when input stdio[*] option is used and input subprocess.stdio[*] ends, with a transform', () => testStreamAbortWait(noop, noopReadable(), 3, true));38 38-// eslint-disable-next-line max-params39-const testStreamAbortSuccess = async (t, streamMethod, stream, fdNumber, useTransform) => {39+const 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();43 44 const {stdout} = await subprocess;45- t.is(stdout, '');46- t.true(stream.destroyed);45+ assert.equal(stdout, '');46+ assert.equal(stream.destroyed, true);47 };48 49-test('Passes when stdin option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, false);50-test('Passes when stdin option Duplex aborts', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, false);51-test('Passes when input stdio[*] option aborts', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, false);52-test('Passes when stdout option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, false);53-test('Passes when stderr option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, false);54-test('Passes when output stdio[*] option ends with no more writes', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, false);55-test('Passes when subprocess.stdout aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, false);56-test('Passes when subprocess.stdout Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, false);57-test('Passes when subprocess.stderr aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, false);58-test('Passes when subprocess.stderr Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, false);59-test('Passes when output subprocess.stdio[*] aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, false);60-test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, false);61-test('Passes when stdin option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 0, true);62-test('Passes when stdin option Duplex aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopDuplex(), 0, true);63-test('Passes when input stdio[*] option aborts, with a transform', testStreamAbortSuccess, destroyOptionStream, noopReadable(), 3, true);64-test('Passes when stdout option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 1, true);65-test('Passes when stderr option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 2, true);66-test('Passes when output stdio[*] option ends with no more writes, with a transform', testStreamAbortSuccess, endOptionStream, noopWritable(), 3, true);67-test('Passes when subprocess.stdout aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 1, true);68-test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 1, true);69-test('Passes when subprocess.stderr aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 2, true);70-test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 2, true);71-test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopWritable(), 3, true);72-test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', testStreamAbortSuccess, destroySubprocessStream, noopDuplex(), 3, true);49+test('Passes when stdin option aborts', () => testStreamAbortSuccess(destroyOptionStream, noopReadable(), 0, false));50+test('Passes when stdin option Duplex aborts', () => testStreamAbortSuccess(destroyOptionStream, noopDuplex(), 0, false));51+test('Passes when input stdio[*] option aborts', () => testStreamAbortSuccess(destroyOptionStream, noopReadable(), 3, false));52+test('Passes when stdout option ends with no more writes', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 1, false));53+test('Passes when stderr option ends with no more writes', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 2, false));54+test('Passes when output stdio[*] option ends with no more writes', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 3, false));55+test('Passes when subprocess.stdout aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 1, false));56+test('Passes when subprocess.stdout Duplex aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 1, false));57+test('Passes when subprocess.stderr aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 2, false));58+test('Passes when subprocess.stderr Duplex aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 2, false));59+test('Passes when output subprocess.stdio[*] aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 3, false));60+test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 3, false));61+test('Passes when stdin option aborts, with a transform', () => testStreamAbortSuccess(destroyOptionStream, noopReadable(), 0, true));62+test('Passes when stdin option Duplex aborts, with a transform', () => testStreamAbortSuccess(destroyOptionStream, noopDuplex(), 0, true));63+test('Passes when input stdio[*] option aborts, with a transform', () => testStreamAbortSuccess(destroyOptionStream, noopReadable(), 3, true));64+test('Passes when stdout option ends with no more writes, with a transform', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 1, true));65+test('Passes when stderr option ends with no more writes, with a transform', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 2, true));66+test('Passes when output stdio[*] option ends with no more writes, with a transform', () => testStreamAbortSuccess(endOptionStream, noopWritable(), 3, true));67+test('Passes when subprocess.stdout aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 1, true));68+test('Passes when subprocess.stdout Duplex aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 1, true));69+test('Passes when subprocess.stderr aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 2, true));70+test('Passes when subprocess.stderr Duplex aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 2, true));71+test('Passes when output subprocess.stdio[*] aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopWritable(), 3, true));72+test('Passes when output subprocess.stdio[*] Duplex aborts with no more writes, with a transform', () => testStreamAbortSuccess(destroySubprocessStream, noopDuplex(), 3, true));73 74-// eslint-disable-next-line max-params75-const testStreamAbortFail = async (t, streamMethod, stream, fdNumber, useTransform) => {74+const 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 }80 82- 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 };85 87-test('Throws abort error when subprocess.stdin aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, false);88-test('Throws abort error when subprocess.stdin Duplex aborts', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, false);89-test('Throws abort error when input subprocess.stdio[*] aborts', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, false);90-test('Throws abort error when stdout option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, false);91-test('Throws abort error when stdout option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, false);92-test('Throws abort error when stderr option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, false);93-test('Throws abort error when stderr option Duplex aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, false);94-test('Throws abort error when output stdio[*] option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, false);95-test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, false);96-test('Throws abort error when subprocess.stdin aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 0, true);97-test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopDuplex(), 0, true);98-test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', testStreamAbortFail, destroySubprocessStream, noopReadable(), 3, true);99-test('Throws abort error when stdout option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 1, true);100-test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 1, true);101-test('Throws abort error when stderr option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 2, true);102-test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 2, true);103-test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopWritable(), 3, true);104-test('Throws abort error when output stdio[*] Duplex option aborts with no more writes, with a transform', testStreamAbortFail, destroyOptionStream, noopDuplex(), 3, true);86+test('Throws abort error when subprocess.stdin aborts', () => testStreamAbortFail(destroySubprocessStream, noopReadable(), 0, false));87+test('Throws abort error when subprocess.stdin Duplex aborts', () => testStreamAbortFail(destroySubprocessStream, noopDuplex(), 0, false));88+test('Throws abort error when input subprocess.stdio[*] aborts', () => testStreamAbortFail(destroySubprocessStream, noopReadable(), 3, false));89+test('Throws abort error when stdout option aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 1, false));90+test('Throws abort error when stdout option Duplex aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 1, false));91+test('Throws abort error when stderr option aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 2, false));92+test('Throws abort error when stderr option Duplex aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 2, false));93+test('Throws abort error when output stdio[*] option aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 3, false));94+test('Throws abort error when output stdio[*] Duplex option aborts with no more writes', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 3, false));95+test('Throws abort error when subprocess.stdin aborts, with a transform', () => testStreamAbortFail(destroySubprocessStream, noopReadable(), 0, true));96+test('Throws abort error when subprocess.stdin Duplex aborts, with a transform', () => testStreamAbortFail(destroySubprocessStream, noopDuplex(), 0, true));97+test('Throws abort error when input subprocess.stdio[*] aborts, with a transform', () => testStreamAbortFail(destroySubprocessStream, noopReadable(), 3, true));98+test('Throws abort error when stdout option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 1, true));99+test('Throws abort error when stdout option Duplex aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 1, true));100+test('Throws abort error when stderr option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 2, true));101+test('Throws abort error when stderr option Duplex aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopDuplex(), 2, true));102+test('Throws abort error when output stdio[*] option aborts with no more writes, with a transform', () => testStreamAbortFail(destroyOptionStream, noopWritable(), 3, true));103+test('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
1+import assert from 'node:assert/strict';2 import {setImmediate} from 'node:timers/promises';2-import test from 'ava';3+import test from 'node:test';4+import {assertRejects} from '../helpers/assert.js';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {assertEpipe} from '../helpers/stdio.js';8 import {foobarString} from '../helpers/input.js';6 unmodified lines15 } from '../helpers/wait.js';16 17 setFixtureDirectory();18 17-// eslint-disable-next-line max-params18-const testStreamEpipeFail = async (t, streamMethod, stream, fdNumber, useTransform) => {19+const 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);24 24- 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 };31 31-test('Throws EPIPE when stdout option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 1, false);32-test('Throws EPIPE when stdout option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, false);33-test('Throws EPIPE when stdout option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, false);34-test('Throws EPIPE when stderr option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 2, false);35-test('Throws EPIPE when stderr option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, false);36-test('Throws EPIPE when stderr option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, false);37-test('Throws EPIPE when output stdio[*] option ends with more writes', testStreamEpipeFail, endOptionStream, noopWritable(), 3, false);38-test('Throws EPIPE when output stdio[*] option aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, false);39-test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, false);40-test('Throws EPIPE when subprocess.stdout aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, false);41-test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, false);42-test('Throws EPIPE when subprocess.stderr aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, false);43-test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, false);44-test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, false);45-test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, false);46-test('Throws EPIPE when stdout option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 1, true);47-test('Throws EPIPE when stdout option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 1, true);48-test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 1, true);49-test('Throws EPIPE when stderr option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 2, true);50-test('Throws EPIPE when stderr option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 2, true);51-test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 2, true);52-test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', testStreamEpipeFail, endOptionStream, noopWritable(), 3, true);53-test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopWritable(), 3, true);54-test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroyOptionStream, noopDuplex(), 3, true);55-test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 1, true);56-test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 1, true);57-test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 2, true);58-test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 2, true);59-test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopWritable(), 3, true);60-test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes, with a transform', testStreamEpipeFail, destroySubprocessStream, noopDuplex(), 3, true);32+test('Throws EPIPE when stdout option ends with more writes', () => testStreamEpipeFail(endOptionStream, noopWritable(), 1, false));33+test('Throws EPIPE when stdout option aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 1, false));34+test('Throws EPIPE when stdout option Duplex aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 1, false));35+test('Throws EPIPE when stderr option ends with more writes', () => testStreamEpipeFail(endOptionStream, noopWritable(), 2, false));36+test('Throws EPIPE when stderr option aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 2, false));37+test('Throws EPIPE when stderr option Duplex aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 2, false));38+test('Throws EPIPE when output stdio[*] option ends with more writes', () => testStreamEpipeFail(endOptionStream, noopWritable(), 3, false));39+test('Throws EPIPE when output stdio[*] option aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 3, false));40+test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 3, false));41+test('Throws EPIPE when subprocess.stdout aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 1, false));42+test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 1, false));43+test('Throws EPIPE when subprocess.stderr aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 2, false));44+test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 2, false));45+test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 3, false));46+test('Throws EPIPE when output subprocess.stdio[*] Duplex aborts with more writes', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 3, false));47+test('Throws EPIPE when stdout option ends with more writes, with a transform', () => testStreamEpipeFail(endOptionStream, noopWritable(), 1, true));48+test('Throws EPIPE when stdout option aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 1, true));49+test('Throws EPIPE when stdout option Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 1, true));50+test('Throws EPIPE when stderr option ends with more writes, with a transform', () => testStreamEpipeFail(endOptionStream, noopWritable(), 2, true));51+test('Throws EPIPE when stderr option aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 2, true));52+test('Throws EPIPE when stderr option Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 2, true));53+test('Throws EPIPE when output stdio[*] option ends with more writes, with a transform', () => testStreamEpipeFail(endOptionStream, noopWritable(), 3, true));54+test('Throws EPIPE when output stdio[*] option aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopWritable(), 3, true));55+test('Throws EPIPE when output stdio[*] option Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroyOptionStream, noopDuplex(), 3, true));56+test('Throws EPIPE when subprocess.stdout aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 1, true));57+test('Throws EPIPE when subprocess.stdout Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 1, true));58+test('Throws EPIPE when subprocess.stderr aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 2, true));59+test('Throws EPIPE when subprocess.stderr Duplex aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopDuplex(), 2, true));60+test('Throws EPIPE when output subprocess.stdio[*] aborts with more writes, with a transform', () => testStreamEpipeFail(destroySubprocessStream, noopWritable(), 3, true));61+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {noopReadable, noopWritable, noopDuplex} from '../helpers/stream.js';7 import {destroyOptionStream, destroySubprocessStream, getStreamStdio} from '../helpers/wait.js';8 9 setFixtureDirectory();10 9-// eslint-disable-next-line max-params10-const testStreamError = async (t, streamMethod, stream, fdNumber, useTransform) => {11+const 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 line17 fdNumber,18 error: cause,19 });20 20- 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 };29 29-test('Throws stream error when stdin option errors', testStreamError, destroyOptionStream, noopReadable(), 0, false);30-test('Throws stream error when stdin option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 0, false);31-test('Throws stream error when stdout option errors', testStreamError, destroyOptionStream, noopWritable(), 1, false);32-test('Throws stream error when stdout option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 1, false);33-test('Throws stream error when stderr option errors', testStreamError, destroyOptionStream, noopWritable(), 2, false);34-test('Throws stream error when stderr option Duplex errors', testStreamError, destroyOptionStream, noopDuplex(), 2, false);35-test('Throws stream error when output stdio[*] option errors', testStreamError, destroyOptionStream, noopWritable(), 3, false);36-test('Throws stream error when output stdio[*] Duplex option errors', testStreamError, destroyOptionStream, noopDuplex(), 3, false);37-test('Throws stream error when input stdio[*] option errors', testStreamError, destroyOptionStream, noopReadable(), 3, false);38-test('Throws stream error when subprocess.stdin errors', testStreamError, destroySubprocessStream, noopReadable(), 0, false);39-test('Throws stream error when subprocess.stdin Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 0, false);40-test('Throws stream error when subprocess.stdout errors', testStreamError, destroySubprocessStream, noopWritable(), 1, false);41-test('Throws stream error when subprocess.stdout Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 1, false);42-test('Throws stream error when subprocess.stderr errors', testStreamError, destroySubprocessStream, noopWritable(), 2, false);43-test('Throws stream error when subprocess.stderr Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 2, false);44-test('Throws stream error when output subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopWritable(), 3, false);45-test('Throws stream error when output subprocess.stdio[*] Duplex errors', testStreamError, destroySubprocessStream, noopDuplex(), 3, false);46-test('Throws stream error when input subprocess.stdio[*] errors', testStreamError, destroySubprocessStream, noopReadable(), 3, false);47-test('Throws stream error when stdin option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 0, true);48-test('Throws stream error when stdin option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 0, true);49-test('Throws stream error when stdout option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 1, true);50-test('Throws stream error when stdout option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 1, true);51-test('Throws stream error when stderr option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 2, true);52-test('Throws stream error when stderr option Duplex errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 2, true);53-test('Throws stream error when output stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopWritable(), 3, true);54-test('Throws stream error when output stdio[*] Duplex option errors, with a transform', testStreamError, destroyOptionStream, noopDuplex(), 3, true);55-test('Throws stream error when input stdio[*] option errors, with a transform', testStreamError, destroyOptionStream, noopReadable(), 3, true);56-test('Throws stream error when subprocess.stdin errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 0, true);57-test('Throws stream error when subprocess.stdin Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 0, true);58-test('Throws stream error when subprocess.stdout errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 1, true);59-test('Throws stream error when subprocess.stdout Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 1, true);60-test('Throws stream error when subprocess.stderr errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 2, true);61-test('Throws stream error when subprocess.stderr Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 2, true);62-test('Throws stream error when output subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopWritable(), 3, true);63-test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', testStreamError, destroySubprocessStream, noopDuplex(), 3, true);64-test('Throws stream error when input subprocess.stdio[*] errors, with a transform', testStreamError, destroySubprocessStream, noopReadable(), 3, true);30+test('Throws stream error when stdin option errors', () => testStreamError(destroyOptionStream, noopReadable(), 0, false));31+test('Throws stream error when stdin option Duplex errors', () => testStreamError(destroyOptionStream, noopDuplex(), 0, false));32+test('Throws stream error when stdout option errors', () => testStreamError(destroyOptionStream, noopWritable(), 1, false));33+test('Throws stream error when stdout option Duplex errors', () => testStreamError(destroyOptionStream, noopDuplex(), 1, false));34+test('Throws stream error when stderr option errors', () => testStreamError(destroyOptionStream, noopWritable(), 2, false));35+test('Throws stream error when stderr option Duplex errors', () => testStreamError(destroyOptionStream, noopDuplex(), 2, false));36+test('Throws stream error when output stdio[*] option errors', () => testStreamError(destroyOptionStream, noopWritable(), 3, false));37+test('Throws stream error when output stdio[*] Duplex option errors', () => testStreamError(destroyOptionStream, noopDuplex(), 3, false));38+test('Throws stream error when input stdio[*] option errors', () => testStreamError(destroyOptionStream, noopReadable(), 3, false));39+test('Throws stream error when subprocess.stdin errors', () => testStreamError(destroySubprocessStream, noopReadable(), 0, false));40+test('Throws stream error when subprocess.stdin Duplex errors', () => testStreamError(destroySubprocessStream, noopDuplex(), 0, false));41+test('Throws stream error when subprocess.stdout errors', () => testStreamError(destroySubprocessStream, noopWritable(), 1, false));42+test('Throws stream error when subprocess.stdout Duplex errors', () => testStreamError(destroySubprocessStream, noopDuplex(), 1, false));43+test('Throws stream error when subprocess.stderr errors', () => testStreamError(destroySubprocessStream, noopWritable(), 2, false));44+test('Throws stream error when subprocess.stderr Duplex errors', () => testStreamError(destroySubprocessStream, noopDuplex(), 2, false));45+test('Throws stream error when output subprocess.stdio[*] errors', () => testStreamError(destroySubprocessStream, noopWritable(), 3, false));46+test('Throws stream error when output subprocess.stdio[*] Duplex errors', () => testStreamError(destroySubprocessStream, noopDuplex(), 3, false));47+test('Throws stream error when input subprocess.stdio[*] errors', () => testStreamError(destroySubprocessStream, noopReadable(), 3, false));48+test('Throws stream error when stdin option errors, with a transform', () => testStreamError(destroyOptionStream, noopReadable(), 0, true));49+test('Throws stream error when stdin option Duplex errors, with a transform', () => testStreamError(destroyOptionStream, noopDuplex(), 0, true));50+test('Throws stream error when stdout option errors, with a transform', () => testStreamError(destroyOptionStream, noopWritable(), 1, true));51+test('Throws stream error when stdout option Duplex errors, with a transform', () => testStreamError(destroyOptionStream, noopDuplex(), 1, true));52+test('Throws stream error when stderr option errors, with a transform', () => testStreamError(destroyOptionStream, noopWritable(), 2, true));53+test('Throws stream error when stderr option Duplex errors, with a transform', () => testStreamError(destroyOptionStream, noopDuplex(), 2, true));54+test('Throws stream error when output stdio[*] option errors, with a transform', () => testStreamError(destroyOptionStream, noopWritable(), 3, true));55+test('Throws stream error when output stdio[*] Duplex option errors, with a transform', () => testStreamError(destroyOptionStream, noopDuplex(), 3, true));56+test('Throws stream error when input stdio[*] option errors, with a transform', () => testStreamError(destroyOptionStream, noopReadable(), 3, true));57+test('Throws stream error when subprocess.stdin errors, with a transform', () => testStreamError(destroySubprocessStream, noopReadable(), 0, true));58+test('Throws stream error when subprocess.stdin Duplex errors, with a transform', () => testStreamError(destroySubprocessStream, noopDuplex(), 0, true));59+test('Throws stream error when subprocess.stdout errors, with a transform', () => testStreamError(destroySubprocessStream, noopWritable(), 1, true));60+test('Throws stream error when subprocess.stdout Duplex errors, with a transform', () => testStreamError(destroySubprocessStream, noopDuplex(), 1, true));61+test('Throws stream error when subprocess.stderr errors, with a transform', () => testStreamError(destroySubprocessStream, noopWritable(), 2, true));62+test('Throws stream error when subprocess.stderr Duplex errors, with a transform', () => testStreamError(destroySubprocessStream, noopDuplex(), 2, true));63+test('Throws stream error when output subprocess.stdio[*] errors, with a transform', () => testStreamError(destroySubprocessStream, noopWritable(), 3, true));64+test('Throws stream error when output subprocess.stdio[*] Duplex errors, with a transform', () => testStreamError(destroySubprocessStream, noopDuplex(), 3, true));65+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {getStdio} from '../helpers/stdio.js';6 7 setFixtureDirectory();8 8-const testIgnore = async (t, fdNumber, execaMethod) => {9+const 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 };13 13-test('stdout is undefined if ignored', testIgnore, 1, execa);14-test('stderr is undefined if ignored', testIgnore, 2, execa);15-test('stdio[*] is undefined if ignored', testIgnore, 3, execa);16-test('stdout is undefined if ignored - sync', testIgnore, 1, execaSync);17-test('stderr is undefined if ignored - sync', testIgnore, 2, execaSync);18-test('stdio[*] is undefined if ignored - sync', testIgnore, 3, execaSync);14+test('stdout is undefined if ignored', () => testIgnore(1, execa));15+test('stderr is undefined if ignored', () => testIgnore(2, execa));16+test('stdio[*] is undefined if ignored', () => testIgnore(3, execa));17+test('stdout is undefined if ignored - sync', () => testIgnore(1, execaSync));18+test('stderr is undefined if ignored - sync', () => testIgnore(2, execaSync));19+test('stdio[*] is undefined if ignored - sync', () => testIgnore(3, execaSync));20 20-const testSubprocessEventsCleanup = async (t, fixtureName) => {21+const 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 };27 27-test('subprocess listeners are cleaned up on success', testSubprocessEventsCleanup, 'empty.js');28-test('subprocess listeners are cleaned up on failure', testSubprocessEventsCleanup, 'fail.js');28+test('subprocess listeners are cleaned up on success', () => testSubprocessEventsCleanup('empty.js'));29+test('subprocess listeners are cleaned up on failure', () => testSubprocessEventsCleanup('fail.js'));30 30-test('Aborting stdout should not abort stderr nor all', async t => {31+test('Aborting stdout should not abort stderr nor all', async () => {32 const subprocess = execa('empty.js', {all: true});33 34 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);38 39 await subprocess;40 40- 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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows, assertRejects} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';7 8 setFixtureDirectory();9 8-const 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);10+const 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 };16 15-test('result.durationMs', async t => {17+test('result.durationMs', async () => {18 const {durationMs} = await execa('empty.js');17- assertDurationMs(t, durationMs);19+ assertDurationMs(durationMs);20 });21 20-test('result.durationMs - sync', t => {22+test('result.durationMs - sync', () => {23 const {durationMs} = execaSync('empty.js');22- assertDurationMs(t, durationMs);24+ assertDurationMs(durationMs);25 });26 25-test('error.durationMs', async t => {26- const {durationMs} = await t.throwsAsync(execa('fail.js'));27- assertDurationMs(t, durationMs);27+test('error.durationMs', async () => {28+ const {durationMs} = await assertRejects(execa('fail.js'));29+ assertDurationMs(durationMs);30 });31 30-test('error.durationMs - sync', t => {31- const {durationMs} = t.throws(() => {32+test('error.durationMs - sync', () => {33+ const {durationMs} = assertThrows(() => {34 execaSync('fail.js');35 });34- assertDurationMs(t, durationMs);36+ assertDurationMs(durationMs);37 });38 37-test('error.durationMs - early validation', async t => {38- const {durationMs} = await t.throwsAsync(getEarlyErrorSubprocess());39- assertDurationMs(t, durationMs);39+test('error.durationMs - early validation', async () => {40+ const {durationMs} = await assertRejects(getEarlyErrorSubprocess());41+ assertDurationMs(durationMs);42 });43 42-test('error.durationMs - early validation, sync', t => {43- const {durationMs} = t.throws(getEarlyErrorSubprocessSync);44- assertDurationMs(t, durationMs);44+test('error.durationMs - early validation, sync', () => {45+ const {durationMs} = assertThrows(getEarlyErrorSubprocessSync);46+ assertDurationMs(durationMs);47 });48 47-test('error.durationMs - unpipeSignal', async t => {48- const {durationMs} = await t.throwsAsync(execa('noop.js').pipe('stdin.js', {signal: AbortSignal.abort()}));49- assertDurationMs(t, durationMs);49+test('error.durationMs - unpipeSignal', async () => {50+ const {durationMs} = await assertRejects(execa('noop.js').pipe('stdin.js', {signal: AbortSignal.abort()}));51+ assertDurationMs(durationMs);52 });53 52-test('error.durationMs - pipe validation', async t => {53- const {durationMs} = await t.throwsAsync(execa('noop.js').pipe(false));54- assertDurationMs(t, durationMs);54+test('error.durationMs - pipe validation', async () => {55+ const {durationMs} = await assertRejects(execa('noop.js').pipe(false));56+ assertDurationMs(durationMs);57 });58 57-test.serial('result.durationMs is accurate', async t => {59+test('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
1+import assert from 'node:assert/strict';2 import {arch} from 'node:os';3 import process from 'node:process';4+import {once} from 'node:events';5 import {finished} from 'node:stream/promises';4-import test from 'ava';5-import {execa, execaSync, $, ExecaError, ExecaSyncError} from '../../index.js';6+import test from 'node:test';7+import {assertThrows, assertRejects} from '../helpers/assert.js';8+import {9+ execa,10+ execaSync,11+ $,12+ ExecaError,13+ ExecaSyncError,14+} from '../../index.js';15 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';16 import {foobarString, foobarUint8Array} from '../helpers/input.js';17 import {fullStdio} from '../helpers/stdio.js';18 import {9 unmodified lines28 const isWindows = process.platform === 'win32';29 const ENOENT_REGEXP = isWindows ? /failed with exit code 1/ : /spawn.* ENOENT/;30 31 // A nonexistent command fails asynchronously, so it does not go through the early error path, but the subprocess still has no process to signal23-test('kill() does not signal the current process when the command does not exist', async t => {32+test('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 });39 30-test('execaSync() throws error if ENOENT', t => {31- t.throws(() => {40+test('execaSync() throws error if ENOENT', () => {41+ assertThrows(() => {42 execaSync('foo');43 }, {message: ENOENT_REGEXP});44 });45 36-const testEarlyErrorShape = async (t, reject) => {46+const 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 };54 45-test('child_process.spawn() early errors have correct shape', testEarlyErrorShape, true);46-test('child_process.spawn() early errors have correct shape - reject false', testEarlyErrorShape, false);55+test('child_process.spawn() early errors have correct shape', () => testEarlyErrorShape(true));56+test('child_process.spawn() early errors have correct shape - reject false', () => testEarlyErrorShape(false));57 58 // 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.51-test('kill() does not signal the current process on early errors', async t => {61+test('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 line67 return 0;68 },69 };70 61- 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 });77 68-test('child_process.spawn() early errors are propagated', async t => {69- await t.throwsAsync(getEarlyErrorSubprocess(), expectedEarlyError);78+test('child_process.spawn() early errors are propagated', async () => {79+ await assertRejects(getEarlyErrorSubprocess(), expectedEarlyError);80 });81 72-test('child_process.spawn() early errors are returned', async t => {82+test('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 });86 77-test('child_process.spawnSync() early errors are propagated with a correct shape', t => {78- t.throws(getEarlyErrorSubprocessSync, expectedEarlyErrorSync);87+test('child_process.spawnSync() early errors are propagated with a correct shape', () => {88+ assertThrows(getEarlyErrorSubprocessSync, expectedEarlyErrorSync);89 });90 81-test('child_process.spawnSync() early errors are propagated with a correct shape - reject false', t => {91+test('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 });95 96 if (!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 });100 91- 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 });104 105 if (arch() === 'x64') {96- test('write to fast-exit subprocess', async t => {97- t.plan(1);98-106+ 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 }118 112-const testEarlyErrorPipe = async (t, getSubprocess) => {113- await t.throwsAsync(getSubprocess(), expectedEarlyError);119+const testEarlyErrorPipe = async getSubprocess => {120+ await assertRejects(getSubprocess(), expectedEarlyError);121 };122 116-test('child_process.spawn() early errors on source can use .pipe()', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(execa('empty.js')));117-test('child_process.spawn() early errors on destination can use .pipe()', testEarlyErrorPipe, () => execa('empty.js').pipe(getEarlyErrorSubprocess()));118-test('child_process.spawn() early errors on source and destination can use .pipe()', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess()));119-test('child_process.spawn() early errors can use .pipe() multiple times', testEarlyErrorPipe, () => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess()).pipe(getEarlyErrorSubprocess()));120-test('child_process.spawn() early errors can use .pipe``', testEarlyErrorPipe, () => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`);121-test('child_process.spawn() early errors can use .pipe`` multiple times', testEarlyErrorPipe, () => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`.pipe`empty.js`);123+test('child_process.spawn() early errors on source can use .pipe()', () => testEarlyErrorPipe(() => getEarlyErrorSubprocess().pipe(execa('empty.js'))));124+test('child_process.spawn() early errors on destination can use .pipe()', () => testEarlyErrorPipe(() => execa('empty.js').pipe(getEarlyErrorSubprocess())));125+test('child_process.spawn() early errors on source and destination can use .pipe()', () => testEarlyErrorPipe(() => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess())));126+test('child_process.spawn() early errors can use .pipe() multiple times', () => testEarlyErrorPipe(() => getEarlyErrorSubprocess().pipe(getEarlyErrorSubprocess()).pipe(getEarlyErrorSubprocess())));127+test('child_process.spawn() early errors can use .pipe``', () => testEarlyErrorPipe(() => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`));128+test('child_process.spawn() early errors can use .pipe`` multiple times', () => testEarlyErrorPipe(() => $(earlyErrorOptions)`empty.js`.pipe(earlyErrorOptions)`empty.js`.pipe`empty.js`));129 123-const testEarlyErrorConvertor = async (t, streamMethod) => {130+const 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 };139 132-test('child_process.spawn() early errors can use .readable()', testEarlyErrorConvertor, 'readable');133-test('child_process.spawn() early errors can use .writable()', testEarlyErrorConvertor, 'writable');134-test('child_process.spawn() early errors can use .duplex()', testEarlyErrorConvertor, 'duplex');140+test('child_process.spawn() early errors can use .readable()', () => testEarlyErrorConvertor('readable'));141+test('child_process.spawn() early errors can use .writable()', () => testEarlyErrorConvertor('writable'));142+test('child_process.spawn() early errors can use .duplex()', () => testEarlyErrorConvertor('duplex'));143 136-const testEarlyErrorWebConvertor = async (t, streamMethod) => {144+const testEarlyErrorWebConvertor = async streamMethod => {145 const subprocess = getEarlyErrorSubprocess();146 subprocess[streamMethod]();139- await t.throwsAsync(subprocess);147+ await assertRejects(subprocess);148 };149 142-test('child_process.spawn() early errors can use .readableStream()', testEarlyErrorWebConvertor, 'readableStream');143-test('child_process.spawn() early errors can use .writableStream()', testEarlyErrorWebConvertor, 'writableStream');144-test('child_process.spawn() early errors can use .transformStream()', testEarlyErrorWebConvertor, 'transformStream');150+test('child_process.spawn() early errors can use .readableStream()', () => testEarlyErrorWebConvertor('readableStream'));151+test('child_process.spawn() early errors can use .writableStream()', () => testEarlyErrorWebConvertor('writableStream'));152+test('child_process.spawn() early errors can use .transformStream()', () => testEarlyErrorWebConvertor('transformStream'));153 154 // 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.148-const 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.156+const readEarlyErrorStream = (subprocess, streamMethod) => Array.fromAsync(subprocess[streamMethod]?.() ?? subprocess);157+158+const 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+};163 152- t.deepEqual(chunks, []);153- await t.throwsAsync(subprocess);164+test('child_process.spawn() early errors make .readable() fail', () => testEarlyErrorReadableEnd('readable'));165+test('child_process.spawn() early errors make .duplex() fail', () => testEarlyErrorReadableEnd('duplex'));166+test('child_process.spawn() early errors make .readableStream() fail', () => testEarlyErrorReadableEnd('readableStream'));167+test('child_process.spawn() early errors make .iterable() fail', () => testEarlyErrorReadableEnd('iterable'));168+test('child_process.spawn() early errors make Symbol.asyncIterator fail', () => testEarlyErrorReadableEnd());169+170+const 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 };176 156-test('child_process.spawn() early errors end .readable()', testEarlyErrorReadableEnd, 'readable');157-test('child_process.spawn() early errors end .duplex()', testEarlyErrorReadableEnd, 'duplex');158-test('child_process.spawn() early errors end .readableStream()', testEarlyErrorReadableEnd, 'readableStream');177+test('child_process.spawn() early errors end .readable() with reject: false', () => testEarlyErrorReadableEndNoReject('readable'));178+test('child_process.spawn() early errors end .duplex() with reject: false', () => testEarlyErrorReadableEndNoReject('duplex'));179+test('child_process.spawn() early errors end .readableStream() with reject: false', () => testEarlyErrorReadableEndNoReject('readableStream'));180+test('child_process.spawn() early errors end .iterable() with reject: false', () => testEarlyErrorReadableEndNoReject('iterable'));181+test('child_process.spawn() early errors end Symbol.asyncIterator with reject: false', () => testEarlyErrorReadableEndNoReject());182 160-const testEarlyErrorWritableEnd = async (t, streamMethod) => {161- const subprocess = getEarlyErrorSubprocess();183+const writeEarlyErrorStream = async (subprocess, streamMethod) => {184 const stream = subprocess[streamMethod]();185 stream.end(foobarString);186 await finished(stream, {readable: false});165-166- t.false(stream.writable);167- await t.throwsAsync(subprocess);187 };188 170-test('child_process.spawn() early errors end .writable()', testEarlyErrorWritableEnd, 'writable');171-test('child_process.spawn() early errors end .duplex() writable side', testEarlyErrorWritableEnd, 'duplex');172-173-test('child_process.spawn() early errors end .writableStream()', async t => {174- const subprocess = getEarlyErrorSubprocess();175- const writer = subprocess.writableStream().getWriter();189+const 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+};195 179- await t.throwsAsync(subprocess);180-});181-182-test('child_process.spawn() early errors end .transformStream()', async t => {196+const 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+};201 190- t.deepEqual(chunks, []);191- await t.throwsAsync(subprocess);192-});202+test('child_process.spawn() early errors make .writable() fail', () => testEarlyErrorWritableEnd('writable', writeEarlyErrorStream));203+test('child_process.spawn() early errors make .duplex() writable side fail', () => testEarlyErrorWritableEnd('duplex', writeEarlyErrorStream));204+test('child_process.spawn() early errors make .writableStream() fail', () => testEarlyErrorWritableEnd('writableStream', writeEarlyErrorWebStream));205+test('child_process.spawn() early errors make .transformStream() fail', () => testEarlyErrorWritableEnd('transformStream', writeEarlyErrorWebStream));206 194-const testEarlyErrorIpc = async (t, runIpcMethod) => {207+const 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+};213+214+test('child_process.spawn() early errors end .writable() with reject: false', () => testEarlyErrorWritableEndNoReject('writable', writeEarlyErrorStream));215+test('child_process.spawn() early errors end .duplex() writable side with reject: false', () => testEarlyErrorWritableEndNoReject('duplex', writeEarlyErrorStream));216+test('child_process.spawn() early errors end .writableStream() with reject: false', () => testEarlyErrorWritableEndNoReject('writableStream', writeEarlyErrorWebStream));217+test('child_process.spawn() early errors end .transformStream() with reject: false', () => testEarlyErrorWritableEndNoReject('transformStream', writeEarlyErrorWebStream));218+219+const 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 };226 202-test('child_process.spawn() early errors can use .sendMessage()', testEarlyErrorIpc, subprocess => subprocess.sendMessage('.'));203-test('child_process.spawn() early errors can use .getOneMessage()', testEarlyErrorIpc, subprocess => subprocess.getOneMessage());204-test('child_process.spawn() early errors can use .getEachMessage()', testEarlyErrorIpc, subprocess => subprocess.getEachMessage());227+test('child_process.spawn() early errors can use .sendMessage()', () => testEarlyErrorIpc(subprocess => subprocess.sendMessage('.')));228+test('child_process.spawn() early errors can use .getOneMessage()', () => testEarlyErrorIpc(subprocess => subprocess.getOneMessage()));229+test('child_process.spawn() early errors can use .getEachMessage()', () => testEarlyErrorIpc(subprocess => subprocess.getEachMessage()));230 206-test('child_process.spawn() early errors can use .iterable()', async t => {207- const subprocess = getEarlyErrorSubprocess();208- const lines = await Array.fromAsync(subprocess.iterable());209-210- t.deepEqual(lines, []);211- await t.throwsAsync(subprocess);212-});213-214-test('child_process.spawn() early errors can use Symbol.asyncIterator', async t => {215- const subprocess = getEarlyErrorSubprocess();216- const lines = await Array.fromAsync(subprocess);217-218- t.deepEqual(lines, []);219- await t.throwsAsync(subprocess);220-});221-222-const testEarlyErrorStream = async (t, getStreamProperty, options) => {231+const 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 };239 231-test('child_process.spawn() early errors can use .stdin', testEarlyErrorStream, ({stdin}) => stdin);232-test('child_process.spawn() early errors can use .stdout', testEarlyErrorStream, ({stdout}) => stdout);233-test('child_process.spawn() early errors can use .stderr', testEarlyErrorStream, ({stderr}) => stderr);234-test('child_process.spawn() early errors can use .stdio[1]', testEarlyErrorStream, ({stdio}) => stdio[1]);235-test('child_process.spawn() early errors can use .stdio[3]', testEarlyErrorStream, ({stdio}) => stdio[3], fullStdio);236-test('child_process.spawn() early errors can use .all', testEarlyErrorStream, ({all}) => all, {all: true});240+test('child_process.spawn() early errors can use .stdin', () => testEarlyErrorStream(({stdin}) => stdin));241+test('child_process.spawn() early errors can use .stdout', () => testEarlyErrorStream(({stdout}) => stdout));242+test('child_process.spawn() early errors can use .stderr', () => testEarlyErrorStream(({stderr}) => stderr));243+test('child_process.spawn() early errors can use .stdio[1]', () => testEarlyErrorStream(({stdio}) => stdio[1]));244+test('child_process.spawn() early errors can use .stdio[3]', () => testEarlyErrorStream(({stdio}) => stdio[3], fullStdio));245+test('child_process.spawn() early errors can use .all', () => testEarlyErrorStream(({all}) => all, {all: true}));246 247 // Reading the `inputFile` happens after the file descriptors are set up, so a missing file is reported as an early error, like with asynchronous methods239-test('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');248+test('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 });253 245-test('inputFile which does not exist is an early error, sync', t => {246- const error = t.throws(() => {254+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows, assertRejects} from '../helpers/assert.js';4 import {5 execa,6 execaSync,7 ExecaError,4 unmodified lines12 import {getEarlyErrorSubprocess, getEarlyErrorSubprocessSync} from '../helpers/early-error.js';13 14 setFixtureDirectory();15 14-const testUnusualError = async (t, error, expectedOriginalMessage = String(error)) => {16+const 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 };24 23-test('error instance can be null', testUnusualError, null);24-test('error instance can be false', testUnusualError, false);25-test('error instance can be a string', testUnusualError, 'test');26-test('error instance can be a number', testUnusualError, 0);27-test('error instance can be a BigInt', testUnusualError, 0n);28-test('error instance can be a symbol', testUnusualError, Symbol('test'));29-test('error instance can be a function', testUnusualError, () => {});30-test('error instance can be an array', testUnusualError, ['test', 'test']);25+test('error instance can be null', () => testUnusualError(null));26+test('error instance can be false', () => testUnusualError(false));27+test('error instance can be a string', () => testUnusualError('test'));28+test('error instance can be a number', () => testUnusualError(0));29+test('error instance can be a BigInt', () => testUnusualError(0n));30+test('error instance can be a symbol', () => testUnusualError(Symbol('test')));31+test('error instance can be a function', () => testUnusualError(() => {}));32+test('error instance can be an array', () => testUnusualError(['test', 'test']));33 // eslint-disable-next-line unicorn/error-message32-test('error instance can be an error with an empty message', testUnusualError, new Error(''), '');33-test('error instance can be undefined', testUnusualError, undefined, 'undefined');34+test('error instance can be an error with an empty message', () => testUnusualError(new Error(''), ''));35+test('error instance can be undefined', () => testUnusualError(undefined, 'undefined'));36 35-test('error instance can be a plain object', async t => {37+test('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 });42 41-const runAndFail = (t, fixtureName, argument, error) => {43+const 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 };48 47-const testErrorCopy = async (t, getPreviousArgument, argument = 'two') => {49+const testErrorCopy = async (getPreviousArgument, argument = 'two') => {50 const fixtureName = 'empty.js';51 const firstArgument = 'foo';52 51- 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}`;57 56- 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 };66 65-test('error instance can be shared', testErrorCopy, () => new Error(foobarString));66-test('error TypeError can be shared', testErrorCopy, () => new TypeError(foobarString));67-test('error string can be shared', testErrorCopy, () => foobarString);68-test('error copy can be shared', testErrorCopy, (t, fixtureName) => runAndFail(t, fixtureName, 'bar', new Error(foobarString)));69-test('error with same message can be shared', testErrorCopy, () => new Error(foobarString), 'foo');67+test('error instance can be shared', () => testErrorCopy(() => new Error(foobarString)));68+test('error TypeError can be shared', () => testErrorCopy(() => new TypeError(foobarString)));69+test('error string can be shared', () => testErrorCopy(() => foobarString));70+test('error copy can be shared', () => testErrorCopy(fixtureName => runAndFail(fixtureName, 'bar', new Error(foobarString))));71+test('error with same message can be shared', () => testErrorCopy(() => new Error(foobarString), 'foo'));72 71-test('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);73+test('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 });78 77-test('error.cause is not set if error.isTerminated', async t => {79+test('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 });86 85-test('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);87+test('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 });92 91-test('error.cause is set on error event', async t => {93+test('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 });100 99-test('error.cause is set if error.isCanceled', async t => {101+test('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 });112 111-test('error.cause is not set if error.isTerminated with .kill(error)', async t => {113+test('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 });121 120-test('Error is instanceof ExecaError', async t => {121- await t.throwsAsync(execa('fail.js'), {instanceOf: ExecaError});122+test('Error is instanceof ExecaError', async () => {123+ await assertRejects(execa('fail.js'), {instanceOf: ExecaError});124 });125 124-test('Early error is instanceof ExecaError', async t => {125- await t.throwsAsync(getEarlyErrorSubprocess(), {instanceOf: ExecaError});126+test('Early error is instanceof ExecaError', async () => {127+ await assertRejects(getEarlyErrorSubprocess(), {instanceOf: ExecaError});128 });129 128-test('Error is instanceof ExecaSyncError', t => {129- t.throws(() => {130+test('Error is instanceof ExecaSyncError', () => {131+ assertThrows(() => {132 execaSync('fail.js');133 }, {instanceOf: ExecaSyncError});134 });135 134-test('Early error is instanceof ExecaSyncError', t => {135- t.throws(() => {136+test('Early error is instanceof ExecaSyncError', () => {137+ assertThrows(() => {138 getEarlyErrorSubprocessSync();139 }, {instanceOf: ExecaSyncError});140 });141 140-test('Pipe error is instanceof ExecaError', async t => {141- await t.throwsAsync(execa('empty.js').pipe(false), {instanceOf: ExecaError});142+test('Pipe error is instanceof ExecaError', async () => {143+ await assertRejects(execa('empty.js').pipe(false), {instanceOf: ExecaError});144 });145 144-const 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'));146+const 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 };151 152 const {propertyIsEnumerable} = Object.prototype;153 152-test('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);154+test('error.name is properly set', async () => {155+ const error = await assertRejects(execa('fail.js'));156+ assert.equal(error.name, 'ExecaError');157+ assertNameShape(error);158 });159 158-test('error.name is properly set - sync', async t => {159- const error = await t.throws(() => {160+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {fullStdio, getStdio} from '../helpers/stdio.js';7 import {foobarString, foobarObject, foobarObjectInspect} from '../helpers/input.js';1 unmodified line9 import {noopGenerator, outputObjectGenerator} from '../helpers/generator.js';10 11 setFixtureDirectory();12 11-test('error.message contains the command', async t => {12- await t.throwsAsync(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});13+test('error.message contains the command', async () => {14+ await assertRejects(execa('exit.js', ['2', 'foo', 'bar']), {message: /exit.js 2 foo bar/});15 });16 15-// eslint-disable-next-line max-params16-const testStdioMessage = async (t, encoding, all, objectMode, execaMethod) => {17+const 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 };28 28-test('error.message contains stdout/stderr/stdio if available', testStdioMessage, 'utf8', false, false, execa);29-test('error.message contains stdout/stderr/stdio even with encoding "buffer"', testStdioMessage, 'buffer', false, false, execa);30-test('error.message contains all if available', testStdioMessage, 'utf8', true, false, execa);31-test('error.message contains all even with encoding "buffer"', testStdioMessage, 'buffer', true, false, execa);32-test('error.message contains stdout/stderr/stdio if available, objectMode', testStdioMessage, 'utf8', false, true, execa);33-test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', testStdioMessage, 'buffer', false, true, execa);34-test('error.message contains all if available, objectMode', testStdioMessage, 'utf8', true, true, execa);35-test('error.message contains all even with encoding "buffer", objectMode', testStdioMessage, 'buffer', true, true, execa);36-test('error.message contains stdout/stderr/stdio if available, sync', testStdioMessage, 'utf8', false, false, execaSync);37-test('error.message contains stdout/stderr/stdio even with encoding "buffer", sync', testStdioMessage, 'buffer', false, false, execaSync);38-test('error.message contains all if available, sync', testStdioMessage, 'utf8', true, false, execaSync);39-test('error.message contains all even with encoding "buffer", sync', testStdioMessage, 'buffer', true, false, execaSync);40-test('error.message contains stdout/stderr/stdio if available, objectMode, sync', testStdioMessage, 'utf8', false, true, execaSync);41-test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode, sync', testStdioMessage, 'buffer', false, true, execaSync);42-test('error.message contains all if available, objectMode, sync', testStdioMessage, 'utf8', true, true, execaSync);43-test('error.message contains all even with encoding "buffer", objectMode, sync', testStdioMessage, 'buffer', true, true, execaSync);29+test('error.message contains stdout/stderr/stdio if available', () => testStdioMessage('utf8', false, false, execa));30+test('error.message contains stdout/stderr/stdio even with encoding "buffer"', () => testStdioMessage('buffer', false, false, execa));31+test('error.message contains all if available', () => testStdioMessage('utf8', true, false, execa));32+test('error.message contains all even with encoding "buffer"', () => testStdioMessage('buffer', true, false, execa));33+test('error.message contains stdout/stderr/stdio if available, objectMode', () => testStdioMessage('utf8', false, true, execa));34+test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode', () => testStdioMessage('buffer', false, true, execa));35+test('error.message contains all if available, objectMode', () => testStdioMessage('utf8', true, true, execa));36+test('error.message contains all even with encoding "buffer", objectMode', () => testStdioMessage('buffer', true, true, execa));37+test('error.message contains stdout/stderr/stdio if available, sync', () => testStdioMessage('utf8', false, false, execaSync));38+test('error.message contains stdout/stderr/stdio even with encoding "buffer", sync', () => testStdioMessage('buffer', false, false, execaSync));39+test('error.message contains all if available, sync', () => testStdioMessage('utf8', true, false, execaSync));40+test('error.message contains all even with encoding "buffer", sync', () => testStdioMessage('buffer', true, false, execaSync));41+test('error.message contains stdout/stderr/stdio if available, objectMode, sync', () => testStdioMessage('utf8', false, true, execaSync));42+test('error.message contains stdout/stderr/stdio even with encoding "buffer", objectMode, sync', () => testStdioMessage('buffer', false, true, execaSync));43+test('error.message contains all if available, objectMode, sync', () => testStdioMessage('utf8', true, true, execaSync));44+test('error.message contains all even with encoding "buffer", objectMode, sync', () => testStdioMessage('buffer', true, true, execaSync));45 45-const testLinesMessage = async (t, encoding, stripFinalNewline, execaMethod) => {46+const 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 };56 56-test('error.message handles "lines: true"', testLinesMessage, 'utf8', false, execa);57-test('error.message handles "lines: true", stripFinalNewline', testLinesMessage, 'utf8', true, execa);58-test('error.message handles "lines: true", buffer', testLinesMessage, 'buffer', false, execa);59-test('error.message handles "lines: true", buffer, stripFinalNewline', testLinesMessage, 'buffer', true, execa);60-test('error.message handles "lines: true", sync', testLinesMessage, 'utf8', false, execaSync);61-test('error.message handles "lines: true", stripFinalNewline, sync', testLinesMessage, 'utf8', true, execaSync);62-test('error.message handles "lines: true", buffer, sync', testLinesMessage, 'buffer', false, execaSync);63-test('error.message handles "lines: true", buffer, stripFinalNewline, sync', testLinesMessage, 'buffer', true, execaSync);57+test('error.message handles "lines: true"', () => testLinesMessage('utf8', false, execa));58+test('error.message handles "lines: true", stripFinalNewline', () => testLinesMessage('utf8', true, execa));59+test('error.message handles "lines: true", buffer', () => testLinesMessage('buffer', false, execa));60+test('error.message handles "lines: true", buffer, stripFinalNewline', () => testLinesMessage('buffer', true, execa));61+test('error.message handles "lines: true", sync', () => testLinesMessage('utf8', false, execaSync));62+test('error.message handles "lines: true", stripFinalNewline, sync', () => testLinesMessage('utf8', true, execaSync));63+test('error.message handles "lines: true", buffer, sync', () => testLinesMessage('buffer', false, execaSync));64+test('error.message handles "lines: true", buffer, stripFinalNewline, sync', () => testLinesMessage('buffer', true, execaSync));65 65-const 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`));66+const 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 };70 70-test('error.message does not contain stdout if not available', testPartialIgnoreMessage, 1, 'ignore', 'stderr');71-test('error.message does not contain stderr if not available', testPartialIgnoreMessage, 2, 'ignore', 'stdout');72-test('error.message does not contain stdout if it is an object', testPartialIgnoreMessage, 1, outputObjectGenerator(), 'stderr');73-test('error.message does not contain stderr if it is an object', testPartialIgnoreMessage, 2, outputObjectGenerator(), 'stdout');71+test('error.message does not contain stdout if not available', () => testPartialIgnoreMessage(1, 'ignore', 'stderr'));72+test('error.message does not contain stderr if not available', () => testPartialIgnoreMessage(2, 'ignore', 'stdout'));73+test('error.message does not contain stdout if it is an object', () => testPartialIgnoreMessage(1, outputObjectGenerator(), 'stderr'));74+test('error.message does not contain stderr if it is an object', () => testPartialIgnoreMessage(2, outputObjectGenerator(), 'stdout'));75 75-const testFullIgnoreMessage = async (t, options, resultProperty) => {76- const result = await t.throwsAsync(execa('echo-fail.js', options));76+const 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 };83 83-test('error.message does not contain stdout/stderr/stdio if not available', testFullIgnoreMessage, {stdio: 'ignore'}, 'message');84-test('error.shortMessage does not contain stdout/stderr/stdio', testFullIgnoreMessage, fullStdio, 'shortMessage');84+test('error.message does not contain stdout/stderr/stdio if not available', () => testFullIgnoreMessage({stdio: 'ignore'}, 'message'));85+test('error.shortMessage does not contain stdout/stderr/stdio', () => testFullIgnoreMessage(fullStdio, 'shortMessage'));86 86-const 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'));87+const 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 };91 91-test('error.message newlines are consistent - no newline', testErrorMessageConsistent, 'stdout');92-test('error.message newlines are consistent - newline', testErrorMessageConsistent, 'stdout\n');92+test('error.message newlines are consistent - no newline', () => testErrorMessageConsistent('stdout'));93+test('error.message newlines are consistent - newline', () => testErrorMessageConsistent('stdout\n'));94 94-test('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\')');95+test('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 });99 99-const testIpcOutput = async (t, doubles, ipcInput, returnedMessage) => {100+const 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 };107 107-test('error.message contains IPC messages, single string', testIpcOutput, false, foobarString, foobarString);108-test('error.message contains IPC messages, two strings', testIpcOutput, true, foobarString, foobarString);109-test('error.message contains IPC messages, single object', testIpcOutput, false, foobarObject, foobarObjectInspect);110-test('error.message contains IPC messages, two objects', testIpcOutput, true, foobarObject, foobarObjectInspect);111-test('error.message contains IPC messages, multiline string', testIpcOutput, false, `${foobarString}\n${foobarString}`, `${foobarString}\n${foobarString}`);112-test('error.message contains IPC messages, control characters', testIpcOutput, false, '\0', '\\u0000');108+test('error.message contains IPC messages, single string', () => testIpcOutput(false, foobarString, foobarString));109+test('error.message contains IPC messages, two strings', () => testIpcOutput(true, foobarString, foobarString));110+test('error.message contains IPC messages, single object', () => testIpcOutput(false, foobarObject, foobarObjectInspect));111+test('error.message contains IPC messages, two objects', () => testIpcOutput(true, foobarObject, foobarObjectInspect));112+test('error.message contains IPC messages, multiline string', () => testIpcOutput(false, `${foobarString}\n${foobarString}`, `${foobarString}\n${foobarString}`));113+test('error.message contains IPC messages, control characters', () => testIpcOutput(false, '\0', '\\u0000'));114 114-test('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, []);115+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows, assertRejects, assertLike} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {fullStdio, getStdio} from '../helpers/stdio.js';7 import {foobarString} from '../helpers/input.js';5 unmodified lines13 } from '../helpers/early-error.js';14 15 setFixtureDirectory();16 15-const testOutput = async (t, fdNumber, execaMethod) => {17+const 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);20 21 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 };27 26-test('can return stdout', testOutput, 1, execa);27-test('can return stderr', testOutput, 2, execa);28-test('can return output stdio[*]', testOutput, 3, execa);29-test('can return stdout, sync', testOutput, 1, execaSync);30-test('can return stderr, sync', testOutput, 2, execaSync);31-test('can return output stdio[*], sync', testOutput, 3, execaSync);28+test('can return stdout', () => testOutput(1, execa));29+test('can return stderr', () => testOutput(2, execa));30+test('can return output stdio[*]', () => testOutput(3, execa));31+test('can return stdout, sync', () => testOutput(1, execaSync));32+test('can return stderr, sync', () => testOutput(2, execaSync));33+test('can return output stdio[*], sync', () => testOutput(3, execaSync));34 33-const testNoStdin = async (t, execaMethod) => {35+const testNoStdin = async execaMethod => {36 const {stdio} = await execaMethod('noop.js', [foobarString]);35- t.is(stdio[0], undefined);37+ assert.equal(stdio[0], undefined);38 };39 38-test('cannot return stdin', testNoStdin, execa);39-test('cannot return stdin, sync', testNoStdin, execaSync);40+test('cannot return stdin', () => testNoStdin(execa));41+test('cannot return stdin, sync', () => testNoStdin(execaSync));42 41-test('cannot return input stdio[*]', async t => {43+test('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 });47 46-test('do not try to consume streams twice', async t => {48+test('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 });55 54-const testEmptyErrorStdio = async (t, execaMethod) => {56+const 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 };63 62-test('empty error.stdout/stderr/stdio', testEmptyErrorStdio, execa);63-test('empty error.stdout/stderr/stdio, sync', testEmptyErrorStdio, execaSync);64+test('empty error.stdout/stderr/stdio', () => testEmptyErrorStdio(execa));65+test('empty error.stdout/stderr/stdio, sync', () => testEmptyErrorStdio(execaSync));66 65-const testUndefinedErrorStdio = async (t, execaMethod) => {67+const 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 };73 72-test('undefined error.stdout/stderr/stdio', testUndefinedErrorStdio, execa);73-test('undefined error.stdout/stderr/stdio, sync', testUndefinedErrorStdio, execaSync);74+test('undefined error.stdout/stderr/stdio', () => testUndefinedErrorStdio(execa));75+test('undefined error.stdout/stderr/stdio, sync', () => testUndefinedErrorStdio(execaSync));76 75-const testEmptyAll = async (t, options, expectedValue, execaMethod) => {77+const testEmptyAll = async (options, expectedValue, execaMethod) => {78 const {all} = await execaMethod('empty.js', options);77- t.is(all, expectedValue);79+ assert.equal(all, expectedValue);80 };81 80-test('empty error.all', testEmptyAll, {all: true}, '', execa);81-test('undefined error.all', testEmptyAll, {}, undefined, execa);82-test('ignored error.all', testEmptyAll, {all: true, stdio: 'ignore'}, undefined, execa);83-test('empty error.all, sync', testEmptyAll, {all: true}, '', execaSync);84-test('undefined error.all, sync', testEmptyAll, {}, undefined, execaSync);85-test('ignored error.all, sync', testEmptyAll, {all: true, stdio: 'ignore'}, undefined, execaSync);82+test('empty error.all', () => testEmptyAll({all: true}, '', execa));83+test('undefined error.all', () => testEmptyAll({}, undefined, execa));84+test('ignored error.all', () => testEmptyAll({all: true, stdio: 'ignore'}, undefined, execa));85+test('empty error.all, sync', () => testEmptyAll({all: true}, '', execaSync));86+test('undefined error.all, sync', () => testEmptyAll({}, undefined, execaSync));87+test('ignored error.all, sync', () => testEmptyAll({all: true, stdio: 'ignore'}, undefined, execaSync));88 87-test('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);89+test('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 });93 92-const 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]);94+const 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 };100 99-test('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);101+test('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 });106 105-test('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);107+test('stdout/stderr/all/stdio on subprocess spawning errors, sync', () => {108+ const error = assertThrows(() => getEarlyErrorSubprocessSync({all: true}));109+ assertLike(error, expectedEarlyErrorSync);110+ validateSpawnErrorStdio(error);111 });112 111-const testErrorOutput = async (t, execaMethod) => {113+const 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 };120 119-test('error.stdout/stderr/stdio is defined', testErrorOutput, execa);120-test('error.stdout/stderr/stdio is defined, sync', testErrorOutput, execaSync);121+test('error.stdout/stderr/stdio is defined', () => testErrorOutput(execa));122+test('error.stdout/stderr/stdio is defined, sync', () => testErrorOutput(execaSync));123 122-test('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, []);124+test('ipc on subprocess spawning errors', async () => {125+ const error = await assertRejects(getEarlyErrorSubprocess({ipc: true}));126+ assertLike(error, expectedEarlyError);127+ assert.deepEqual(error.ipcOutput, []);128 });129 128-const testEarlyErrorNoIpc = async (t, options) => {129- const error = await t.throwsAsync(getEarlyErrorSubprocess(options));130- t.like(error, expectedEarlyError);131- t.deepEqual(error.ipcOutput, []);130+const testEarlyErrorNoIpc = async options => {131+ const error = await assertRejects(getEarlyErrorSubprocess(options));132+ assertLike(error, expectedEarlyError);133+ assert.deepEqual(error.ipcOutput, []);134 };135 134-test('ipc on subprocess spawning errors, ipc false', testEarlyErrorNoIpc, {ipc: false});135-test('ipc on subprocess spawning errors, buffer false', testEarlyErrorNoIpc, {buffer: false});136+test('ipc on subprocess spawning errors, ipc false', () => testEarlyErrorNoIpc({ipc: false}));137+test('ipc on subprocess spawning errors, buffer false', () => testEarlyErrorNoIpc({buffer: false}));modified:test/return/reject.js+6 added-5 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 6 setFixtureDirectory();7 7-test('skip throwing when using reject option', async t => {8+test('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 });12 12-test('skip throwing when using reject option in sync mode', t => {13+test('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
1+import assert from 'node:assert/strict';2 import process from 'node:process';2-import test from 'ava';3+import test from 'node:test';4+import {assertThrows, assertRejects} from '../helpers/assert.js';5 import {execa, execaSync} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {fullStdio} from '../helpers/stdio.js';8+/* eslint-disable node-test/no-conditional-assertion -- shared helper functions are called from conditional paths on purpose */9 10 const isWindows = process.platform === 'win32';11 12 setFixtureDirectory();13 11-const testSuccessShape = async (t, execaMethod) => {14+const 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 lines34 'pipedFrom',35 ]);36 };37 35-test('Return value properties are not missing and are ordered', testSuccessShape, execa);36-test('Return value properties are not missing and are ordered, sync', testSuccessShape, execaSync);38+test('Return value properties are not missing and are ordered', () => testSuccessShape(execa));39+test('Return value properties are not missing and are ordered, sync', () => testSuccessShape(execaSync));40 38-const testErrorShape = async (t, execaMethod) => {41+const 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 lines65 'pipedFrom',66 ]);67 };68 66-test('Error properties are not missing and are ordered', testErrorShape, execa);67-test('Error properties are not missing and are ordered, sync', testErrorShape, execaSync);69+test('Error properties are not missing and are ordered', () => testErrorShape(execa));70+test('Error properties are not missing and are ordered, sync', () => testErrorShape(execaSync));71 69-test('failed is false on success', async t => {72+test('failed is false on success', async () => {73 const {failed} = await execa('noop.js', ['foo']);71- t.false(failed);74+ assert.equal(failed, false);75 });76 74-test('failed is true on failure', async t => {75- const {failed} = await t.throwsAsync(execa('fail.js'));76- t.true(failed);77+test('failed is true on failure', async () => {78+ const {failed} = await assertRejects(execa('fail.js'));79+ assert.equal(failed, true);80 });81 79-test('error.isTerminated is true if subprocess was killed directly', async t => {82+test('error.isTerminated is true if subprocess was killed directly', async () => {83 const subprocess = execa('forever.js', {killSignal: 'SIGINT'});84 85 subprocess.kill();86 84- 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 });94 92-test('error.isTerminated is true if subprocess was killed indirectly', async t => {95+test('error.isTerminated is true if subprocess was killed indirectly', async () => {96 const subprocess = execa('forever.js', {killSignal: 'SIGHUP'});97 98 process.kill(subprocess.pid, 'SIGINT');99 100 // `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 });111 109-test('result.isTerminated is false if not killed', async t => {112+test('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 });116 114-test('result.isTerminated is false if not killed and subprocess.kill() was called', async t => {117+test('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 });124 122-test('result.isTerminated is false if not killed, in sync mode', t => {125+test('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 });129 127-test('result.isTerminated is false on subprocess error', async t => {128- const {isTerminated} = await t.throwsAsync(execa('wrong command'));129- t.false(isTerminated);130+test('result.isTerminated is false on subprocess error', async () => {131+ const {isTerminated} = await assertRejects(execa('wrong command'));132+ assert.equal(isTerminated, false);133 });134 132-test('result.isTerminated is false on subprocess error, in sync mode', t => {133- const {isTerminated} = t.throws(() => {135+test('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 });141 139-test('error.code is undefined on success', async t => {142+test('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 });146 144-test('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');147+test('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 });151+152+/* eslint-enable node-test/no-conditional-assertion */modified:test/stdio/direction.js+105 added-91 removed
1+import assert from 'node:assert/strict';2 import {readFile, writeFile, rm} from 'node:fs/promises';3 import process from 'node:process';3-import test from 'ava';4+import test from 'node:test';5 import tempfile from 'tempfile';6+import {assertThrows} from '../helpers/assert.js';7 import {execa, execaSync} from '../../index.js';8 import {getStdio} from '../helpers/stdio.js';9 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10 import {foobarString} from '../helpers/input.js';11 import {noopReadable, noopWritable} from '../helpers/stream.js';12 13 setFixtureDirectory();14 13-const testInputOutput = (t, stdioOption, execaMethod) => {14- t.throws(() => {15+const testInputOutput = (stdioOption, execaMethod) => {16+ assertThrows(() => {17 execaMethod('empty.js', getStdio(3, [new ReadableStream(), stdioOption]));18 }, {message: /readable and writable/});19 };20 19-test('Cannot pass both readable and writable values to stdio[*] - WritableStream', testInputOutput, new WritableStream(), execa);20-test('Cannot pass both readable and writable values to stdio[*] - 1', testInputOutput, 1, execa);21-test('Cannot pass both readable and writable values to stdio[*] - 2', testInputOutput, 2, execa);22-test('Cannot pass both readable and writable values to stdio[*] - process.stdout', testInputOutput, process.stdout, execa);23-test('Cannot pass both readable and writable values to stdio[*] - process.stderr', testInputOutput, process.stderr, execa);24-test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', testInputOutput, new WritableStream(), execaSync);25-test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', testInputOutput, 1, execaSync);26-test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', testInputOutput, 2, execaSync);27-test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', testInputOutput, process.stdout, execaSync);28-test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', testInputOutput, process.stderr, execaSync);21+test('Cannot pass both readable and writable values to stdio[*] - WritableStream', () => testInputOutput(new WritableStream(), execa));22+test('Cannot pass both readable and writable values to stdio[*] - 1', () => testInputOutput(1, execa));23+test('Cannot pass both readable and writable values to stdio[*] - 2', () => testInputOutput(2, execa));24+test('Cannot pass both readable and writable values to stdio[*] - process.stdout', () => testInputOutput(process.stdout, execa));25+test('Cannot pass both readable and writable values to stdio[*] - process.stderr', () => testInputOutput(process.stderr, execa));26+test('Cannot pass both readable and writable values to stdio[*] - WritableStream - sync', () => testInputOutput(new WritableStream(), execaSync));27+test('Cannot pass both readable and writable values to stdio[*] - 1 - sync', () => testInputOutput(1, execaSync));28+test('Cannot pass both readable and writable values to stdio[*] - 2 - sync', () => testInputOutput(2, execaSync));29+test('Cannot pass both readable and writable values to stdio[*] - process.stdout - sync', () => testInputOutput(process.stdout, execaSync));30+test('Cannot pass both readable and writable values to stdio[*] - process.stderr - sync', () => testInputOutput(process.stderr, execaSync));31 30-const testAmbiguousDirection = async (t, execaMethod) => {32+const 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 };41 40-test('stdio[*] default direction is output', testAmbiguousDirection, execa);41-test('stdio[*] default direction is output - sync', testAmbiguousDirection, execaSync);42+test('stdio[*] default direction is output', () => testAmbiguousDirection(execa));43+test('stdio[*] default direction is output - sync', () => testAmbiguousDirection(execaSync));44 43-const testAmbiguousMultiple = async (t, fdNumber) => {45+const 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 };52 51-test('stdin ambiguous direction is influenced by other values', testAmbiguousMultiple, 0);52-test('stdio[*] ambiguous direction is influenced by other values', testAmbiguousMultiple, 3);53+test('stdin ambiguous direction is influenced by other values', () => testAmbiguousMultiple(0));54+test('stdio[*] ambiguous direction is influenced by other values', () => testAmbiguousMultiple(3));55 54-const testDirectionInputPipe = async (t, stdioOption) => {56+const 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 };62 61-test('stdio[*] { value: "pipe", input: true } sets the direction to input', testDirectionInputPipe, {value: 'pipe', input: true});62-test('stdio[*] { value: "overlapped", input: true } sets the direction to input', testDirectionInputPipe, {value: 'overlapped', input: true});63+test('stdio[*] { value: "pipe", input: true } sets the direction to input', () => testDirectionInputPipe({value: 'pipe', input: true}));64+test('stdio[*] { value: "overlapped", input: true } sets the direction to input', () => testDirectionInputPipe({value: 'overlapped', input: true}));65 66 const uppercaseGenerator = function * (line) {67 yield line.toUpperCase();68 };69 68-test('stdio[*] { value: generator, input: true } sets the direction to input', async t => {70+test('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 });76 75-test('stdio[*] { value: {file}, input: true } sets the direction to input', async t => {77+test('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 });84 83-const testInputFixedDirection = (t, stdioOption, execaMethod) => {84- t.throws(() => {85+const 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 };90 89-test('stdio[*] { value: WritableStream, input: true } is invalid', testInputFixedDirection, new WritableStream(), execa);90-test('stdio[*] { value: WritableStream, input: true } is invalid - sync', testInputFixedDirection, new WritableStream(), execaSync);91-test('stdio[*] { value: process.stdout, input: true } is invalid', testInputFixedDirection, process.stdout, execa);92-test('stdio[*] { value: process.stdout, input: true } is invalid - sync', testInputFixedDirection, process.stdout, execaSync);91+test('stdio[*] { value: WritableStream, input: true } is invalid', () => testInputFixedDirection(new WritableStream(), execa));92+test('stdio[*] { value: WritableStream, input: true } is invalid - sync', () => testInputFixedDirection(new WritableStream(), execaSync));93+test('stdio[*] { value: process.stdout, input: true } is invalid', () => testInputFixedDirection(process.stdout, execa));94+test('stdio[*] { value: process.stdout, input: true } is invalid - sync', () => testInputFixedDirection(process.stdout, execaSync));95 94-test('stdio[*] { value: "pipe", input: true } cannot be used in sync mode', t => {95- t.throws(() => {96+test('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 });101 100-test('stdio[*] { value: "pipe", input: true } cannot be used in sync mode with buffer false', t => {101- t.throws(() => {102+test('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 });107 106-const testDirectionOutputPipe = async (t, stdioOption, execaMethod) => {108+const 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 };112 111-test('stdio[*] { value: "pipe" } keeps the default output direction', testDirectionOutputPipe, {value: 'pipe'}, execa);112-test('stdio[*] { value: "pipe" } keeps the default output direction - sync', testDirectionOutputPipe, {value: 'pipe'}, execaSync);113-test('stdio[*] { value: "pipe", input: false } keeps the default output direction', testDirectionOutputPipe, {value: 'pipe', input: false}, execa);114-test('stdio[*] { value: "pipe", input: false } keeps the default output direction - sync', testDirectionOutputPipe, {value: 'pipe', input: false}, execaSync);113+test('stdio[*] { value: "pipe" } keeps the default output direction', () => testDirectionOutputPipe({value: 'pipe'}, execa));114+test('stdio[*] { value: "pipe" } keeps the default output direction - sync', () => testDirectionOutputPipe({value: 'pipe'}, execaSync));115+test('stdio[*] { value: "pipe", input: false } keeps the default output direction', () => testDirectionOutputPipe({value: 'pipe', input: false}, execa));116+test('stdio[*] { value: "pipe", input: false } keeps the default output direction - sync', () => testDirectionOutputPipe({value: 'pipe', input: false}, execaSync));117 116-const testDirectionConflict = (t, execaMethod) => {117- t.throws(() => {118+const testDirectionConflict = execaMethod => {119+ assertThrows(() => {120 execaMethod('empty.js', getStdio(3, [{value: 'pipe', input: true}, 1]));121 }, {message: /readable and writable/});122 };123 122-test('Cannot pass { value: "pipe", input: true } with a writable value to stdio[*]', testDirectionConflict, execa);123-test('Cannot pass { value: "pipe", input: true } with a writable value to stdio[*] - sync', testDirectionConflict, execaSync);124+test('Cannot pass { value: "pipe", input: true } with a writable value to stdio[*]', () => testDirectionConflict(execa));125+test('Cannot pass { value: "pipe", input: true } with a writable value to stdio[*] - sync', () => testDirectionConflict(execaSync));126 125-const testInputBoolean = (t, execaMethod) => {126- t.throws(() => {127+const 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 };132 131-test('stdio[*].input must be a boolean', testInputBoolean, execa);132-test('stdio[*].input must be a boolean - sync', testInputBoolean, execaSync);133+test('stdio[*].input must be a boolean', () => testInputBoolean(execa));134+test('stdio[*].input must be a boolean - sync', () => testInputBoolean(execaSync));135 134-test('stdout.input must be a boolean with buffer false - sync', t => {135- t.throws(() => {136+test('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 line143 `stdin`/`stdout`/`stderr` have a fixed direction, so values that are intrinsically the other direction144 are invalid, like with additional file descriptors.145 Otherwise, asynchronous methods pipe in the wrong direction and crash, e.g. with `dest.end is not a function`.146 */145-const testFixedDirection = (t, options, expectedMessage, execaMethod) => {146- t.throws(() => {147+const testFixedDirection = (options, expectedMessage, execaMethod) => {148+ assertThrows(() => {149 execaMethod('empty.js', options);150 }, {message: expectedMessage});151 };152 153 const readableOutputMessage = /a readable value is always an input, but `std(?:out|err)` is an output/;154 153-test('stdout cannot use a readable Node.js stream', testFixedDirection, {stdout: [noopReadable(), 'pipe']}, readableOutputMessage, execa);154-test('stdout cannot use a readable Node.js stream - sync', testFixedDirection, {stdout: [noopReadable(), 'pipe']}, readableOutputMessage, execaSync);155-test('stderr cannot use a readable Node.js stream', testFixedDirection, {stderr: [noopReadable(), 'pipe']}, readableOutputMessage, execa);156-test('stdout cannot use a readable web stream', testFixedDirection, {stdout: new ReadableStream()}, readableOutputMessage, execa);157-test('stdout cannot use a readable web stream - sync', testFixedDirection, {stdout: new ReadableStream()}, readableOutputMessage, execaSync);158-test('stdout { value: readable, input: true } is invalid', testFixedDirection, {stdout: {value: noopReadable(), input: true}}, readableOutputMessage, execa);155+test('stdout cannot use a readable Node.js stream', () => testFixedDirection({stdout: [noopReadable(), 'pipe']}, readableOutputMessage, execa));156+test('stdout cannot use a readable Node.js stream - sync', () => testFixedDirection({stdout: [noopReadable(), 'pipe']}, readableOutputMessage, execaSync));157+test('stderr cannot use a readable Node.js stream', () => testFixedDirection({stderr: [noopReadable(), 'pipe']}, readableOutputMessage, execa));158+test('stdout cannot use a readable web stream', () => testFixedDirection({stdout: new ReadableStream()}, readableOutputMessage, execa));159+test('stdout cannot use a readable web stream - sync', () => testFixedDirection({stdout: new ReadableStream()}, readableOutputMessage, execaSync));160+test('stdout { value: readable, input: true } is invalid', () => testFixedDirection({stdout: {value: noopReadable(), input: true}}, readableOutputMessage, execa));161 160-test('stdin cannot use a writable Node.js stream', testFixedDirection, {stdin: [noopWritable(), 'pipe']}, /a writable value is always an output/, execa);161-test('stdin cannot use a writable Node.js stream - sync', testFixedDirection, {stdin: [noopWritable(), 'pipe']}, /a writable value is always an output/, execaSync);162-test('stdin cannot use a writable web stream', testFixedDirection, {stdin: new WritableStream()}, /a writable value is always an output/, execa);163-test('stdin cannot use a writable web stream - sync', testFixedDirection, {stdin: new WritableStream()}, /a writable value is always an output/, execaSync);162+test('stdin cannot use a writable Node.js stream', () => testFixedDirection({stdin: [noopWritable(), 'pipe']}, /a writable value is always an output/, execa));163+test('stdin cannot use a writable Node.js stream - sync', () => testFixedDirection({stdin: [noopWritable(), 'pipe']}, /a writable value is always an output/, execaSync));164+test('stdin cannot use a writable web stream', () => testFixedDirection({stdin: new WritableStream()}, /a writable value is always an output/, execa));165+test('stdin cannot use a writable web stream - sync', () => testFixedDirection({stdin: new WritableStream()}, /a writable value is always an output/, execaSync));166 165-test('stdout { value: writable, input: true } is invalid', testFixedDirection, {stdout: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execa);166-test('stdout { value: writable, input: true } is invalid - sync', testFixedDirection, {stdout: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execaSync);167-test('stdout { value: readable, input: true } is invalid - sync', testFixedDirection, {stdout: {value: noopReadable(), input: true}}, readableOutputMessage, execaSync);168-test('stderr cannot use a readable Node.js stream - sync', testFixedDirection, {stderr: [noopReadable(), 'pipe']}, readableOutputMessage, execaSync);169-test('stderr cannot use a readable web stream', testFixedDirection, {stderr: new ReadableStream()}, readableOutputMessage, execa);170-test('stderr cannot use a readable web stream - sync', testFixedDirection, {stderr: new ReadableStream()}, readableOutputMessage, execaSync);171-test('stderr { value: readable, input: true } is invalid', testFixedDirection, {stderr: {value: noopReadable(), input: true}}, readableOutputMessage, execa);172-test('stderr { value: readable, input: true } is invalid - sync', testFixedDirection, {stderr: {value: noopReadable(), input: true}}, readableOutputMessage, execaSync);173-test('stderr { value: web readable, input: true } is invalid', testFixedDirection, {stderr: {value: new ReadableStream(), input: true}}, readableOutputMessage, execa);174-test('stderr { value: web readable, input: true } is invalid - sync', testFixedDirection, {stderr: {value: new ReadableStream(), input: true}}, readableOutputMessage, execaSync);167+test('stdout { value: writable, input: true } is invalid', () => testFixedDirection({stdout: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execa));168+test('stdout { value: writable, input: true } is invalid - sync', () => testFixedDirection({stdout: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execaSync));169+test('stdout { value: readable, input: true } is invalid - sync', () => testFixedDirection({stdout: {value: noopReadable(), input: true}}, readableOutputMessage, execaSync));170+test('stderr cannot use a readable Node.js stream - sync', () => testFixedDirection({stderr: [noopReadable(), 'pipe']}, readableOutputMessage, execaSync));171+test('stderr cannot use a readable web stream', () => testFixedDirection({stderr: new ReadableStream()}, readableOutputMessage, execa));172+test('stderr cannot use a readable web stream - sync', () => testFixedDirection({stderr: new ReadableStream()}, readableOutputMessage, execaSync));173+test('stderr { value: readable, input: true } is invalid', () => testFixedDirection({stderr: {value: noopReadable(), input: true}}, readableOutputMessage, execa));174+test('stderr { value: readable, input: true } is invalid - sync', () => testFixedDirection({stderr: {value: noopReadable(), input: true}}, readableOutputMessage, execaSync));175+test('stderr { value: web readable, input: true } is invalid', () => testFixedDirection({stderr: {value: new ReadableStream(), input: true}}, readableOutputMessage, execa));176+test('stderr { value: web readable, input: true } is invalid - sync', () => testFixedDirection({stderr: {value: new ReadableStream(), input: true}}, readableOutputMessage, execaSync));177 176-test('stdin { value: writable, input: true } is invalid', testFixedDirection, {stdin: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execa);177-test('stdin { value: writable, input: true } is invalid - sync', testFixedDirection, {stdin: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execaSync);178-test('stdin { value: writable web stream, input: true } is invalid', testFixedDirection, {stdin: {value: new WritableStream(), input: true}}, /cannot be used with a writable value/, execa);179-test('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);178+test('stdin { value: writable, input: true } is invalid', () => testFixedDirection({stdin: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execa));179+test('stdin { value: writable, input: true } is invalid - sync', () => testFixedDirection({stdin: {value: noopWritable(), input: true}}, /cannot be used with a writable value/, execaSync));180+test('stdin { value: writable web stream, input: true } is invalid', () => testFixedDirection({stdin: {value: new WritableStream(), input: true}}, /cannot be used with a writable value/, execa));181+test('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));182 183 const writableStdinMessage = /a writable value is always an output/;184 183-test('stdin cannot use a writable Node.js stream after another value', testFixedDirection, {stdin: ['pipe', noopWritable()]}, writableStdinMessage, execa);184-test('stdin cannot use a writable Node.js stream after another value - sync', testFixedDirection, {stdin: ['pipe', noopWritable()]}, writableStdinMessage, execaSync);185-test('stdin cannot use a writable web stream in an array', testFixedDirection, {stdin: [new WritableStream(), 'pipe']}, writableStdinMessage, execa);186-test('stdin cannot use a writable web stream in an array - sync', testFixedDirection, {stdin: [new WritableStream(), 'pipe']}, writableStdinMessage, execaSync);187-test('stdin cannot use both readable and writable values', testFixedDirection, {stdin: [noopReadable(), noopWritable()]}, writableStdinMessage, execa);188-test('stdin cannot use both readable and writable values - sync', testFixedDirection, {stdin: [noopReadable(), noopWritable()]}, writableStdinMessage, execaSync);185+test('stdin cannot use a writable Node.js stream after another value', () => testFixedDirection({stdin: ['pipe', noopWritable()]}, writableStdinMessage, execa));186+test('stdin cannot use a writable Node.js stream after another value - sync', () => testFixedDirection({stdin: ['pipe', noopWritable()]}, writableStdinMessage, execaSync));187+test('stdin cannot use a writable web stream in an array', () => testFixedDirection({stdin: [new WritableStream(), 'pipe']}, writableStdinMessage, execa));188+test('stdin cannot use a writable web stream in an array - sync', () => testFixedDirection({stdin: [new WritableStream(), 'pipe']}, writableStdinMessage, execaSync));189+test('stdin cannot use both readable and writable values', () => testFixedDirection({stdin: [noopReadable(), noopWritable()]}, writableStdinMessage, execa));190+test('stdin cannot use both readable and writable values - sync', () => testFixedDirection({stdin: [noopReadable(), noopWritable()]}, writableStdinMessage, execaSync));191 190-test('stdout cannot use a readable Node.js stream after another value', testFixedDirection, {stdout: ['pipe', noopReadable()]}, readableOutputMessage, execa);191-test('stdout cannot use a readable Node.js stream after another value - sync', testFixedDirection, {stdout: ['pipe', noopReadable()]}, readableOutputMessage, execaSync);192-test('stdout cannot use a readable web stream in an array', testFixedDirection, {stdout: [new ReadableStream(), 'pipe']}, readableOutputMessage, execa);193-test('stdout cannot use a readable web stream in an array - sync', testFixedDirection, {stdout: [new ReadableStream(), 'pipe']}, readableOutputMessage, execaSync);192+test('stdout cannot use a readable Node.js stream after another value', () => testFixedDirection({stdout: ['pipe', noopReadable()]}, readableOutputMessage, execa));193+test('stdout cannot use a readable Node.js stream after another value - sync', () => testFixedDirection({stdout: ['pipe', noopReadable()]}, readableOutputMessage, execaSync));194+test('stdout cannot use a readable web stream in an array', () => testFixedDirection({stdout: [new ReadableStream(), 'pipe']}, readableOutputMessage, execa));195+test('stdout cannot use a readable web stream in an array - sync', () => testFixedDirection({stdout: [new ReadableStream(), 'pipe']}, readableOutputMessage, execaSync));196+197+// A single native value is passed as is to `child_process.spawn()`, which handles it, so its direction is not checked198+const testSingleNativeOtherDirection = async (options, execaMethod) => {199+ const {exitCode} = await execaMethod('empty.js', options);200+ assert.equal(exitCode, 0);201+};202+203+test('stdin can be a single output file descriptor', () => testSingleNativeOtherDirection({stdin: 1}, execa));204+test('stdin can be a single output file descriptor - sync', () => testSingleNativeOtherDirection({stdin: 1}, execaSync));205+test('stdout can be a single input file descriptor', () => testSingleNativeOtherDirection({stdout: 0}, execa));206+test('stdout can be a single input file descriptor - sync', () => testSingleNativeOtherDirection({stdout: 0}, execaSync));207+test('stdout can be process.stdin', () => testSingleNativeOtherDirection({stdout: process.stdin}, execa));modified:test/stdio/duplex.js+22 added-20 removed
1+import assert from 'node:assert/strict';2 import {createHash} from 'node:crypto';3 import {promisify} from 'node:util';4 import {createGzip, gunzip} from 'node:zlib';4-import test from 'ava';5+import test from 'node:test';6+import {assertThrows} from '../helpers/assert.js';7 import {execa} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 import {10 foobarString,4 unmodified lines15 import {uppercaseEncodingDuplex, getOutputDuplex} from '../helpers/duplex.js';16 17 setFixtureDirectory();18 17-test('Can use crypto.createHash()', async t => {19+test('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 });24 23-test('Can use zlib.createGzip()', async t => {25+test('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 });30 29-test('Can use encoding "hex"', async t => {31+test('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 });37 36-test('Cannot use objectMode: true with duplex.readableObjectMode: false', t => {37- t.throws(() => {38+test('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 });43 42-test('Cannot use objectMode: false with duplex.readableObjectMode: true', t => {43- t.throws(() => {44+test('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 });49 48-const testObjectModeFalse = async (t, objectMode) => {50+const 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 };54 53-test('Can use objectMode: false with duplex.readableObjectMode: false', testObjectModeFalse, false);54-test('Can use objectMode: undefined with duplex.readableObjectMode: false', testObjectModeFalse, undefined);55+test('Can use objectMode: false with duplex.readableObjectMode: false', () => testObjectModeFalse(false));56+test('Can use objectMode: undefined with duplex.readableObjectMode: false', () => testObjectModeFalse(undefined));57 56-const testObjectModeTrue = async (t, objectMode) => {58+const 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 };62 61-test('Can use objectMode: true with duplex.readableObjectMode: true', testObjectModeTrue, true);62-test('Can use objectMode: undefined with duplex.readableObjectMode: true', testObjectModeTrue, undefined);63+test('Can use objectMode: true with duplex.readableObjectMode: true', () => testObjectModeTrue(true));64+test('Can use objectMode: undefined with duplex.readableObjectMode: true', () => testObjectModeTrue(undefined));modified:test/stdio/duplicate.js+147 added-139 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {createReadStream, createWriteStream} from 'node:fs';4+import {5+ mkdir,6+ readFile,7+ writeFile,8+ rm,3-import {mkdir, readFile, writeFile, rm} from 'node:fs/promises';4-import {join} from 'node:path';9+} from 'node:fs/promises';10+import path from 'node:path';11 import {Readable, Writable} from 'node:stream';12 import {pathToFileURL} from 'node:url';7-import test from 'ava';13+import test from 'node:test';14 import tempfile from 'tempfile';15+import {assertThrows} from '../helpers/assert.js';16 import {execa, execaSync} from '../../index.js';17 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';18 import {19 uppercaseGenerator,37 unmodified lines57 const differentInputsName = '`stdin` and `stdio[3]`';58 const differentOutputsName = '`stdout` and `stderr`';59 const differentInputsOutputsName = '`stdin` and `stdout`';60 54-test('Can use multiple "pipe" on same input file descriptor', async t => {61+test('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 });67 61-const testTwoPipeOutput = async (t, execaMethod) => {68+const 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 };72 66-test('Can use multiple "pipe" on same output file descriptor', testTwoPipeOutput, execa);67-test('Can use multiple "pipe" on same output file descriptor, sync', testTwoPipeOutput, execaSync);73+test('Can use multiple "pipe" on same output file descriptor', () => testTwoPipeOutput(execa));74+test('Can use multiple "pipe" on same output file descriptor, sync', () => testTwoPipeOutput(execaSync));75 69-test('Can repeat same stream on same input file descriptor', async t => {76+test('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 });81 75-test('Can repeat same stream on same output file descriptor', async t => {82+test('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 });93 87-// eslint-disable-next-line max-params88-const testTwoGenerators = async (t, producesTwo, execaMethod, firstGenerator, secondGenerator = firstGenerator) => {94+const 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 };99 94-test('Can use multiple identical generators', testTwoGenerators, true, execa, appendGenerator().transform);95-test('Can use multiple identical generators, options object', testTwoGenerators, true, execa, appendGenerator());96-test('Can use multiple identical generators, async', testTwoGenerators, true, execa, appendAsyncGenerator().transform);97-test('Can use multiple identical generators, options object, async', testTwoGenerators, true, execa, appendAsyncGenerator());98-test('Can use multiple identical generators, sync', testTwoGenerators, true, execaSync, appendGenerator().transform);99-test('Can use multiple identical generators, options object, sync', testTwoGenerators, true, execaSync, appendGenerator());100-test('Ignore duplicate identical duplexes', testTwoGenerators, false, execa, appendDuplex());101-test('Ignore duplicate identical webTransforms', testTwoGenerators, false, execa, appendWebTransform());102-test('Can use multiple generators with duplexes', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendDuplex());103-test('Can use multiple generators with webTransforms', testTwoGenerators, true, execa, appendGenerator(false, false, true), appendWebTransform());104-test('Can use multiple duplexes with webTransforms', testTwoGenerators, true, execa, appendDuplex(), appendWebTransform());100+test('Can use multiple identical generators', () => testTwoGenerators(true, execa, appendGenerator().transform));101+test('Can use multiple identical generators, options object', () => testTwoGenerators(true, execa, appendGenerator()));102+test('Can use multiple identical generators, async', () => testTwoGenerators(true, execa, appendAsyncGenerator().transform));103+test('Can use multiple identical generators, options object, async', () => testTwoGenerators(true, execa, appendAsyncGenerator()));104+test('Can use multiple identical generators, sync', () => testTwoGenerators(true, execaSync, appendGenerator().transform));105+test('Can use multiple identical generators, options object, sync', () => testTwoGenerators(true, execaSync, appendGenerator()));106+test('Ignore duplicate identical duplexes', () => testTwoGenerators(false, execa, appendDuplex()));107+test('Ignore duplicate identical webTransforms', () => testTwoGenerators(false, execa, appendWebTransform()));108+test('Can use multiple generators with duplexes', () => testTwoGenerators(true, execa, appendGenerator(false, false, true), appendDuplex()));109+test('Can use multiple generators with webTransforms', () => testTwoGenerators(true, execa, appendGenerator(false, false, true), appendWebTransform()));110+test('Can use multiple duplexes with webTransforms', () => testTwoGenerators(true, execa, appendDuplex(), appendWebTransform()));111 106-const testMultiplePipeOutput = async (t, execaMethod) => {112+const 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 };117 112-test('Can use multiple "pipe" on different output file descriptors', testMultiplePipeOutput, execa);113-test('Can use multiple "pipe" on different output file descriptors, sync', testMultiplePipeOutput, execaSync);118+test('Can use multiple "pipe" on different output file descriptors', () => testMultiplePipeOutput(execa));119+test('Can use multiple "pipe" on different output file descriptors, sync', () => testMultiplePipeOutput(execaSync));120 115-test('Can re-use same generator on different input file descriptors', async t => {121+test('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 });125 120-test('Can re-use same generator on different output file descriptors', async t => {126+test('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 });131 126-test('Can re-use same non-native Readable stream on different input file descriptors', async t => {132+test('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 });141 136-const testMultipleStreamOutput = async (t, getStreamOption) => {142+const 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 };150 145-test('Can re-use same native Writable stream on different output file descriptors', testMultipleStreamOutput, getNativeStream);146-test('Can re-use same non-native Writable stream on different output file descriptors', testMultipleStreamOutput, getNonNativeStream);147-test('Can re-use same web Writable stream on different output file descriptors', testMultipleStreamOutput, getWebWritableStream);151+test('Can re-use same native Writable stream on different output file descriptors', () => testMultipleStreamOutput(getNativeStream));152+test('Can re-use same non-native Writable stream on different output file descriptors', () => testMultipleStreamOutput(getNonNativeStream));153+test('Can re-use same web Writable stream on different output file descriptors', () => testMultipleStreamOutput(getWebWritableStream));154 149-const testMultipleInheritOutput = async (t, isSync) => {155+const 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 };159 154-test('Can re-use same parent file descriptor on different output file descriptors', testMultipleInheritOutput, false);155-test('Can re-use same parent file descriptor on different output file descriptors, sync', testMultipleInheritOutput, true);160+test('Can re-use same parent file descriptor on different output file descriptors', () => testMultipleInheritOutput(false));161+test('Can re-use same parent file descriptor on different output file descriptors, sync', () => testMultipleInheritOutput(true));162 157-const testMultipleFileInput = async (t, mapFile) => {163+const 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 };170 165-test('Can re-use same file path on different input file descriptors', testMultipleFileInput, getAbsolutePath);166-test('Can re-use same file URL on different input file descriptors', testMultipleFileInput, pathToFileURL);171+test('Can re-use same file path on different input file descriptors', () => testMultipleFileInput(getAbsolutePath));172+test('Can re-use same file URL on different input file descriptors', () => testMultipleFileInput(pathToFileURL));173 168-const testMultipleFileOutput = async (t, mapFile, execaMethod) => {174+const 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 };180 175-test('Can re-use same file path on different output file descriptors', testMultipleFileOutput, getAbsolutePath, execa);176-test('Can re-use same file path on different output file descriptors, sync', testMultipleFileOutput, getAbsolutePath, execaSync);177-test('Can re-use same file URL on different output file descriptors', testMultipleFileOutput, pathToFileURL, execa);178-test('Can re-use same file URL on different output file descriptors, sync', testMultipleFileOutput, pathToFileURL, execaSync);181+test('Can re-use same file path on different output file descriptors', () => testMultipleFileOutput(getAbsolutePath, execa));182+test('Can re-use same file path on different output file descriptors, sync', () => testMultipleFileOutput(getAbsolutePath, execaSync));183+test('Can re-use same file URL on different output file descriptors', () => testMultipleFileOutput(pathToFileURL, execa));184+test('Can re-use same file URL on different output file descriptors, sync', () => testMultipleFileOutput(pathToFileURL, execaSync));185 180-// One of the two `append` flags would be silently ignored otherwise181-const testAppendConflict = (t, execaMethod, stdoutAppend, stderrAppend) => {186+// When file descriptors target the same file with different `append` values, the first one decides187+const 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 };197 191-test('Cannot use different `append` values on the same output file path', testAppendConflict, execa, undefined, true);192-test('Cannot use different `append` values on the same output file path, reversed', testAppendConflict, execa, true, undefined);193-test('Cannot use different `append` values on the same output file path, sync', testAppendConflict, execaSync, undefined, true);194-test('Cannot use different `append` values on the same output file path, reversed, sync', testAppendConflict, execaSync, true, undefined);198+test('The first file descriptor decides `append` on the same output file path', () => testDifferentAppend(execa, undefined, true, ''));199+test('The first file descriptor decides `append` on the same output file path, reversed', () => testDifferentAppend(execa, true, undefined, 'base\n'));200+test('The first file descriptor decides `append` on the same output file path, sync', () => testDifferentAppend(execaSync, undefined, true, ''));201+test('The first file descriptor decides `append` on the same output file path, reversed, sync', () => testDifferentAppend(execaSync, true, undefined, 'base\n'));202 196-// 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 too204 const sameFdName = '`stdout` and `stdout`';205 199-const testAppendConflictSameFd = (t, execaMethod, appendOne, appendTwo) => {206+const 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 };213 206-test('Cannot use different `append` values on the same output file path in the same file descriptor', testAppendConflictSameFd, execa, undefined, true);207-test('Cannot use different `append` values on the same output file path in the same file descriptor, reversed', testAppendConflictSameFd, execa, true, undefined);208-test('Cannot use different `append` values on the same output file path in the same file descriptor, sync', testAppendConflictSameFd, execaSync, undefined, true);209-test('Cannot use different `append` values on the same output file path in the same file descriptor, reversed, sync', testAppendConflictSameFd, execaSync, true, undefined);214+test('The first item decides `append` on the same output file path in the same file descriptor', () => testDifferentAppendSameFd(execa, undefined, true, ''));215+test('The first item decides `append` on the same output file path in the same file descriptor, reversed', () => testDifferentAppendSameFd(execa, true, undefined, 'base\n'));216+test('The first item decides `append` on the same output file path in the same file descriptor, sync', () => testDifferentAppendSameFd(execaSync, undefined, true, ''));217+test('The first item decides `append` on the same output file path in the same file descriptor, reversed, sync', () => testDifferentAppendSameFd(execaSync, true, undefined, 'base\n'));218 211-const testSameAppend = async (t, execaMethod) => {219+const 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 };226 219-test('Can use the same `append: true` value on the same output file path', testSameAppend, execa);220-test('Can use the same `append: true` value on the same output file path, sync', testSameAppend, execaSync);227+test('Can use the same `append: true` value on the same output file path', () => testSameAppend(execa));228+test('Can use the same `append: true` value on the same output file path, sync', () => testSameAppend(execaSync));229 222-const testFalsyAppend = async (t, execaMethod) => {230+const 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 };236 229-test('Falsy `append` values are the same on the same output file path', testFalsyAppend, execa);230-test('Falsy `append` values are the same on the same output file path, sync', testFalsyAppend, execaSync);237+test('Falsy `append` values are the same on the same output file path', () => testFalsyAppend(execa));238+test('Falsy `append` values are the same on the same output file path, sync', () => testFalsyAppend(execaSync));239 232-const testMultipleFileInputOutput = async (t, mapFile, execaMethod) => {240+const 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 };248 241-test('Can use different file paths on different input/output file descriptors', testMultipleFileInputOutput, getAbsolutePath, execa);242-test('Can use different file paths on different input/output file descriptors, sync', testMultipleFileInputOutput, getAbsolutePath, execaSync);243-test('Can use different file URL on different input/output file descriptors', testMultipleFileInputOutput, pathToFileURL, execa);244-test('Can use different file URL on different input/output file descriptors, sync', testMultipleFileInputOutput, pathToFileURL, execaSync);249+test('Can use different file paths on different input/output file descriptors', () => testMultipleFileInputOutput(getAbsolutePath, execa));250+test('Can use different file paths on different input/output file descriptors, sync', () => testMultipleFileInputOutput(getAbsolutePath, execaSync));251+test('Can use different file URL on different input/output file descriptors', () => testMultipleFileInputOutput(pathToFileURL, execa));252+test('Can use different file URL on different input/output file descriptors, sync', () => testMultipleFileInputOutput(pathToFileURL, execaSync));253 254 // eslint-disable-next-line max-params247-const testMultipleInvalid = async (t, getDummyStream, typeName, getStdio, fdName, execaMethod) => {255+const 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 };264 257-test('Cannot use same Duplex on different input file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentInputs, differentInputsName, execa);258-test('Cannot use same Duplex on different output file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentOutputs, differentOutputsName, execa);259-test('Cannot use same Duplex on both input and output file descriptors', testMultipleInvalid, getDummyDuplex, duplexName, getDifferentInputsOutputs, differentInputsOutputsName, execa);260-test('Cannot use same TransformStream on different input file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentInputs, differentInputsName, execa);261-test('Cannot use same TransformStream on different output file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentOutputs, differentOutputsName, execa);262-test('Cannot use same TransformStream on both input and output file descriptors', testMultipleInvalid, getDummyWebTransformStream, webTransformName, getDifferentInputsOutputs, differentInputsOutputsName, execa);263-test('Cannot use same file path on both input and output file descriptors', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execa);264-test('Cannot use same file URL on both input and output file descriptors', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execa);265-test('Cannot use same file path on both input and output file descriptors, sync', testMultipleInvalid, getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);266-test('Cannot use same file URL on both input and output file descriptors, sync', testMultipleInvalid, getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync);265+test('Cannot use same Duplex on different input file descriptors', () => testMultipleInvalid(getDummyDuplex, duplexName, getDifferentInputs, differentInputsName, execa));266+test('Cannot use same Duplex on different output file descriptors', () => testMultipleInvalid(getDummyDuplex, duplexName, getDifferentOutputs, differentOutputsName, execa));267+test('Cannot use same Duplex on both input and output file descriptors', () => testMultipleInvalid(getDummyDuplex, duplexName, getDifferentInputsOutputs, differentInputsOutputsName, execa));268+test('Cannot use same TransformStream on different input file descriptors', () => testMultipleInvalid(getDummyWebTransformStream, webTransformName, getDifferentInputs, differentInputsName, execa));269+test('Cannot use same TransformStream on different output file descriptors', () => testMultipleInvalid(getDummyWebTransformStream, webTransformName, getDifferentOutputs, differentOutputsName, execa));270+test('Cannot use same TransformStream on both input and output file descriptors', () => testMultipleInvalid(getDummyWebTransformStream, webTransformName, getDifferentInputsOutputs, differentInputsOutputsName, execa));271+test('Cannot use same file path on both input and output file descriptors', () => testMultipleInvalid(getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execa));272+test('Cannot use same file URL on both input and output file descriptors', () => testMultipleInvalid(getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execa));273+test('Cannot use same file path on both input and output file descriptors, sync', () => testMultipleInvalid(getDummyFilePath, filePathName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync));274+test('Cannot use same file URL on both input and output file descriptors, sync', () => testMultipleInvalid(getDummyFileURL, fileURLName, getDifferentInputsOutputs, differentInputsOutputsName, execaSync));275 276 // 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.270-const testSameStreamSameFd = (t, getStream, typeName) => {278+const 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 };284 277-test('Cannot use same Duplex twice on the same output file descriptor', testSameStreamSameFd, noopDuplex, duplexName);278-test('Cannot use same TransformStream twice on the same output file descriptor', testSameStreamSameFd, () => new TransformStream(), webTransformName);285+test('Cannot use same Duplex twice on the same output file descriptor', () => testSameStreamSameFd(noopDuplex, duplexName));286+test('Cannot use same TransformStream twice on the same output file descriptor', () => testSameStreamSameFd(() => new TransformStream(), webTransformName));287 288 // The streams created for the earlier items must be destroyed when a later one is rejected, otherwise they are leaked281-test('Earlier streams are destroyed when a later item of the same file descriptor is rejected', t => {289+test('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 });296 297 // `{file: './output.txt'}` and a `file:` URL are two ways to target the same file290-const testFilePathAndUrl = async (t, execaMethod) => {298+const 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 };304 297-const testFileUrlAndPath = async (t, execaMethod) => {305+const 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 };311 304-test('Can use a file path and a file URL on different output file descriptors', testFilePathAndUrl, execa);305-test('Can use a file URL and a file path on different output file descriptors', testFileUrlAndPath, execa);306-test('Can use a file path and a file URL on different output file descriptors, sync', testFilePathAndUrl, execaSync);307-test('Can use a file URL and a file path on different output file descriptors, sync', testFileUrlAndPath, execaSync);312+test('Can use a file path and a file URL on different output file descriptors', () => testFilePathAndUrl(execa));313+test('Can use a file URL and a file path on different output file descriptors', () => testFileUrlAndPath(execa));314+test('Can use a file path and a file URL on different output file descriptors, sync', () => testFilePathAndUrl(execaSync));315+test('Can use a file URL and a file path on different output file descriptors, sync', () => testFileUrlAndPath(execaSync));316 317 // A single file descriptor can target the same file twice. Its output is a single stream, so it must only be written once.310-const testSameFileSameFd = async (t, execaMethod) => {318+const 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 };324 317-test('Can use the same file path twice on the same output file descriptor', testSameFileSameFd, execa);318-test('Can use the same file path twice on the same output file descriptor, sync', testSameFileSameFd, execaSync);325+test('Can use the same file path twice on the same output file descriptor', () => testSameFileSameFd(execa));326+test('Can use the same file path twice on the same output file descriptor, sync', () => testSameFileSameFd(execaSync));327 328 // A file path is resolved before being compared, so equivalent spellings of the same file are detected321-const testFilePathNormalized = async (t, execaMethod) => {329+const 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`;336 337 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 };341 334-test('Can use equivalent file paths on different output file descriptors', testFilePathNormalized, execa);335-test('Can use equivalent file paths on different output file descriptors, sync', testFilePathNormalized, execaSync);342+test('Can use equivalent file paths on different output file descriptors', () => testFilePathNormalized(execa));343+test('Can use equivalent file paths on different output file descriptors, sync', () => testFilePathNormalized(execaSync));344 337-const testFilePathAndUrlNormalized = async (t, execaMethod) => {345+const 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`;352 353 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 };357 350-test('Can use an equivalent file URL on different output file descriptors', testFilePathAndUrlNormalized, execa);351-test('Can use an equivalent file URL on a different output file descriptor, sync', testFilePathAndUrlNormalized, execaSync);358+test('Can use an equivalent file URL on different output file descriptors', () => testFilePathAndUrlNormalized(execa));359+test('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
1+import assert from 'node:assert/strict';2 import {readFile, open, rm} from 'node:fs/promises';2-import test from 'ava';3+import test from 'node:test';4 import tempfile from 'tempfile';5 import {execa, execaSync} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {getStdio} from '../helpers/stdio.js';8 9 setFixtureDirectory();10 10-const testFileDescriptorOption = async (t, fdNumber, execaMethod) => {11+const 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 };19 19-test('pass `stdout` to a file descriptor', testFileDescriptorOption, 1, execa);20-test('pass `stderr` to a file descriptor', testFileDescriptorOption, 2, execa);21-test('pass `stdio[*]` to a file descriptor', testFileDescriptorOption, 3, execa);22-test('pass `stdout` to a file descriptor - sync', testFileDescriptorOption, 1, execaSync);23-test('pass `stderr` to a file descriptor - sync', testFileDescriptorOption, 2, execaSync);24-test('pass `stdio[*]` to a file descriptor - sync', testFileDescriptorOption, 3, execaSync);20+test('pass `stdout` to a file descriptor', () => testFileDescriptorOption(1, execa));21+test('pass `stderr` to a file descriptor', () => testFileDescriptorOption(2, execa));22+test('pass `stdio[*]` to a file descriptor', () => testFileDescriptorOption(3, execa));23+test('pass `stdout` to a file descriptor - sync', () => testFileDescriptorOption(1, execaSync));24+test('pass `stderr` to a file descriptor - sync', () => testFileDescriptorOption(2, execaSync));25+test('pass `stdio[*]` to a file descriptor - sync', () => testFileDescriptorOption(3, execaSync));26 26-const testStdinWrite = async (t, fdNumber) => {27+const 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 };33 33-test('you can write to subprocess.stdin', testStdinWrite, 0);34-test('you can write to subprocess.stdio[*]', testStdinWrite, 3);34+test('you can write to subprocess.stdin', () => testStdinWrite(0));35+test('you can write to subprocess.stdio[*]', () => testStdinWrite(3));modified:test/stdio/file-path-error.js+88 added-86 removed
1+import assert from 'node:assert/strict';2 import {readFile, writeFile, rm} from 'node:fs/promises';3 import {pathToFileURL} from 'node:url';3-import test from 'ava';4+import test from 'node:test';5 import {pathExists} from 'path-exists';6 import tempfile from 'tempfile';7+import {assertThrows, assertRejects} from '../helpers/assert.js';8 import {execa, execaSync} from '../../index.js';9 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10 import {identity, getStdio} from '../helpers/stdio.js';11 import {foobarString, foobarUppercase} from '../helpers/input.js';8 unmodified lines20 setFixtureDirectory();21 22 const nonFileUrl = new URL('https://example.com');23 22-const testStdioNonFileUrl = (t, fdNumber, execaMethod) => {23- t.throws(() => {24+const testStdioNonFileUrl = (fdNumber, execaMethod) => {25+ assertThrows(() => {26 execaMethod('empty.js', getStdio(fdNumber, nonFileUrl));27 }, {message: /pathToFileURL/});28 };29 28-test('inputFile cannot be a non-file URL', testStdioNonFileUrl, 'inputFile', execa);29-test('stdin cannot be a non-file URL', testStdioNonFileUrl, 0, execa);30-test('stdout cannot be a non-file URL', testStdioNonFileUrl, 1, execa);31-test('stderr cannot be a non-file URL', testStdioNonFileUrl, 2, execa);32-test('stdio[*] cannot be a non-file URL', testStdioNonFileUrl, 3, execa);33-test('inputFile cannot be a non-file URL - sync', testStdioNonFileUrl, 'inputFile', execaSync);34-test('stdin cannot be a non-file URL - sync', testStdioNonFileUrl, 0, execaSync);35-test('stdout cannot be a non-file URL - sync', testStdioNonFileUrl, 1, execaSync);36-test('stderr cannot be a non-file URL - sync', testStdioNonFileUrl, 2, execaSync);37-test('stdio[*] cannot be a non-file URL - sync', testStdioNonFileUrl, 3, execaSync);30+test('inputFile cannot be a non-file URL', () => testStdioNonFileUrl('inputFile', execa));31+test('stdin cannot be a non-file URL', () => testStdioNonFileUrl(0, execa));32+test('stdout cannot be a non-file URL', () => testStdioNonFileUrl(1, execa));33+test('stderr cannot be a non-file URL', () => testStdioNonFileUrl(2, execa));34+test('stdio[*] cannot be a non-file URL', () => testStdioNonFileUrl(3, execa));35+test('inputFile cannot be a non-file URL - sync', () => testStdioNonFileUrl('inputFile', execaSync));36+test('stdin cannot be a non-file URL - sync', () => testStdioNonFileUrl(0, execaSync));37+test('stdout cannot be a non-file URL - sync', () => testStdioNonFileUrl(1, execaSync));38+test('stderr cannot be a non-file URL - sync', () => testStdioNonFileUrl(2, execaSync));39+test('stdio[*] cannot be a non-file URL - sync', () => testStdioNonFileUrl(3, execaSync));40 39-const testInvalidInputFile = (t, execaMethod) => {40- t.throws(() => {41+const testInvalidInputFile = execaMethod => {42+ assertThrows(() => {43 execaMethod('empty.js', getStdio('inputFile', false));44 }, {message: /a file path string or a file URL/});45 };46 45-test('inputFile must be a file URL or string', testInvalidInputFile, execa);46-test('inputFile must be a file URL or string - sync', testInvalidInputFile, execaSync);47+test('inputFile must be a file URL or string', () => testInvalidInputFile(execa));48+test('inputFile must be a file URL or string - sync', () => testInvalidInputFile(execaSync));49 48-const testFilePathObject = (t, fdNumber, execaMethod) => {49- t.throws(() => {50+const testFilePathObject = (fdNumber, execaMethod) => {51+ assertThrows(() => {52 execaMethod('empty.js', getStdio(fdNumber, foobarString));53 }, {message: /must be used/});54 };55 54-test('stdin must be an object when it is a file path string', testFilePathObject, 0, execa);55-test('stdout must be an object when it is a file path string', testFilePathObject, 1, execa);56-test('stderr must be an object when it is a file path string', testFilePathObject, 2, execa);57-test('stdio[*] must be an object when it is a file path string', testFilePathObject, 3, execa);58-test('stdin be an object when it is a file path string - sync', testFilePathObject, 0, execaSync);59-test('stdout be an object when it is a file path string - sync', testFilePathObject, 1, execaSync);60-test('stderr be an object when it is a file path string - sync', testFilePathObject, 2, execaSync);61-test('stdio[*] must be an object when it is a file path string - sync', testFilePathObject, 3, execaSync);56+test('stdin must be an object when it is a file path string', () => testFilePathObject(0, execa));57+test('stdout must be an object when it is a file path string', () => testFilePathObject(1, execa));58+test('stderr must be an object when it is a file path string', () => testFilePathObject(2, execa));59+test('stdio[*] must be an object when it is a file path string', () => testFilePathObject(3, execa));60+test('stdin be an object when it is a file path string - sync', () => testFilePathObject(0, execaSync));61+test('stdout be an object when it is a file path string - sync', () => testFilePathObject(1, execaSync));62+test('stderr be an object when it is a file path string - sync', () => testFilePathObject(2, execaSync));63+test('stdio[*] must be an object when it is a file path string - sync', () => testFilePathObject(3, execaSync));64 63-const testFileError = async (t, fixtureName, mapFile, fdNumber) => {64- await t.throwsAsync(65+const testFileError = async (fixtureName, mapFile, fdNumber) => {66+ await assertRejects(67 execa(fixtureName, [`${fdNumber}`], getStdio(fdNumber, mapFile('./unknown/file'))),68 {code: 'ENOENT'},69 );70 };71 70-test.serial('inputFile file URL errors should be handled', testFileError, 'stdin-fd.js', pathToFileURL, 'inputFile');71-test.serial('stdin file URL errors should be handled', testFileError, 'stdin-fd.js', pathToFileURL, 0);72-test.serial('stdout file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 1);73-test.serial('stderr file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 2);74-test.serial('stdio[*] file URL errors should be handled', testFileError, 'noop-fd.js', pathToFileURL, 3);75-test.serial('inputFile file path errors should be handled', testFileError, 'stdin-fd.js', identity, 'inputFile');76-test.serial('stdin file path errors should be handled', testFileError, 'stdin-fd.js', getAbsolutePath, 0);77-test.serial('stdout file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 1);78-test.serial('stderr file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 2);79-test.serial('stdio[*] file path errors should be handled', testFileError, 'noop-fd.js', getAbsolutePath, 3);72+test('inputFile file URL errors should be handled', () => testFileError('stdin-fd.js', pathToFileURL, 'inputFile'));73+test('stdin file URL errors should be handled', () => testFileError('stdin-fd.js', pathToFileURL, 0));74+test('stdout file URL errors should be handled', () => testFileError('noop-fd.js', pathToFileURL, 1));75+test('stderr file URL errors should be handled', () => testFileError('noop-fd.js', pathToFileURL, 2));76+test('stdio[*] file URL errors should be handled', () => testFileError('noop-fd.js', pathToFileURL, 3));77+test('inputFile file path errors should be handled', () => testFileError('stdin-fd.js', identity, 'inputFile'));78+test('stdin file path errors should be handled', () => testFileError('stdin-fd.js', getAbsolutePath, 0));79+test('stdout file path errors should be handled', () => testFileError('noop-fd.js', getAbsolutePath, 1));80+test('stderr file path errors should be handled', () => testFileError('noop-fd.js', getAbsolutePath, 2));81+test('stdio[*] file path errors should be handled', () => testFileError('noop-fd.js', getAbsolutePath, 3));82 81-const testFileErrorSync = (t, mapFile, fdNumber) => {82- t.throws(() => {83+const testFileErrorSync = (mapFile, fdNumber) => {84+ assertThrows(() => {85 execaSync('empty.js', getStdio(fdNumber, mapFile('./unknown/file')));86 }, {code: 'ENOENT'});87 };88 87-test('inputFile file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 'inputFile');88-test('stdin file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 0);89-test('stdout file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 1);90-test('stderr file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 2);91-test('stdio[*] file URL errors should be handled - sync', testFileErrorSync, pathToFileURL, 3);92-test('inputFile file path errors should be handled - sync', testFileErrorSync, identity, 'inputFile');93-test('stdin file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 0);94-test('stdout file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 1);95-test('stderr file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 2);96-test('stdio[*] file path errors should be handled - sync', testFileErrorSync, getAbsolutePath, 3);89+test('inputFile file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 'inputFile'));90+test('stdin file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 0));91+test('stdout file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 1));92+test('stderr file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 2));93+test('stdio[*] file URL errors should be handled - sync', () => testFileErrorSync(pathToFileURL, 3));94+test('inputFile file path errors should be handled - sync', () => testFileErrorSync(identity, 'inputFile'));95+test('stdin file path errors should be handled - sync', () => testFileErrorSync(getAbsolutePath, 0));96+test('stdout file path errors should be handled - sync', () => testFileErrorSync(getAbsolutePath, 1));97+test('stderr file path errors should be handled - sync', () => testFileErrorSync(getAbsolutePath, 2));98+test('stdio[*] file path errors should be handled - sync', () => testFileErrorSync(getAbsolutePath, 3));99 98-const testInputFileObject = async (t, fdNumber, mapFile, execaMethod) => {100+const 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 line109 }, {message: /cannot use both files and transforms in objectMode/});110 await rm(filePath);111 };112 111-test('stdin cannot use objectMode together with input file paths', testInputFileObject, 0, getAbsolutePath, execa);112-test('stdin cannot use objectMode together with input file URLs', testInputFileObject, 0, pathToFileURL, execa);113-test('stdio[*] cannot use objectMode together with input file paths', testInputFileObject, 3, getAbsolutePath, execa);114-test('stdio[*] cannot use objectMode together with input file URLs', testInputFileObject, 3, pathToFileURL, execa);115-test('stdin cannot use objectMode together with input file paths, sync', testInputFileObject, 0, getAbsolutePath, execaSync);116-test('stdin cannot use objectMode together with input file URLs, sync', testInputFileObject, 0, pathToFileURL, execaSync);113+test('stdin cannot use objectMode together with input file paths', () => testInputFileObject(0, getAbsolutePath, execa));114+test('stdin cannot use objectMode together with input file URLs', () => testInputFileObject(0, pathToFileURL, execa));115+test('stdio[*] cannot use objectMode together with input file paths', () => testInputFileObject(3, getAbsolutePath, execa));116+test('stdio[*] cannot use objectMode together with input file URLs', () => testInputFileObject(3, pathToFileURL, execa));117+test('stdin cannot use objectMode together with input file paths, sync', () => testInputFileObject(0, getAbsolutePath, execaSync));118+test('stdin cannot use objectMode together with input file URLs, sync', () => testInputFileObject(0, pathToFileURL, execaSync));119 118-const testOutputFileObject = async (t, fdNumber, mapFile, execaMethod) => {120+const 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 };130 129-test('stdout cannot use objectMode together with output file paths', testOutputFileObject, 1, getAbsolutePath, execa);130-test('stdout cannot use objectMode together with output file URLs', testOutputFileObject, 1, pathToFileURL, execa);131-test('stderr cannot use objectMode together with output file paths', testOutputFileObject, 2, getAbsolutePath, execa);132-test('stderr cannot use objectMode together with output file URLs', testOutputFileObject, 2, pathToFileURL, execa);133-test('stdio[*] cannot use objectMode together with output file paths', testOutputFileObject, 3, getAbsolutePath, execa);134-test('stdio[*] cannot use objectMode together with output file URLs', testOutputFileObject, 3, pathToFileURL, execa);135-test('stdout cannot use objectMode together with output file paths, sync', testOutputFileObject, 1, getAbsolutePath, execaSync);136-test('stdout cannot use objectMode together with output file URLs, sync', testOutputFileObject, 1, pathToFileURL, execaSync);137-test('stderr cannot use objectMode together with output file paths, sync', testOutputFileObject, 2, getAbsolutePath, execaSync);138-test('stderr cannot use objectMode together with output file URLs, sync', testOutputFileObject, 2, pathToFileURL, execaSync);139-test('stdio[*] cannot use objectMode together with output file paths, sync', testOutputFileObject, 3, getAbsolutePath, execaSync);140-test('stdio[*] cannot use objectMode together with output file URLs, sync', testOutputFileObject, 3, pathToFileURL, execaSync);131+test('stdout cannot use objectMode together with output file paths', () => testOutputFileObject(1, getAbsolutePath, execa));132+test('stdout cannot use objectMode together with output file URLs', () => testOutputFileObject(1, pathToFileURL, execa));133+test('stderr cannot use objectMode together with output file paths', () => testOutputFileObject(2, getAbsolutePath, execa));134+test('stderr cannot use objectMode together with output file URLs', () => testOutputFileObject(2, pathToFileURL, execa));135+test('stdio[*] cannot use objectMode together with output file paths', () => testOutputFileObject(3, getAbsolutePath, execa));136+test('stdio[*] cannot use objectMode together with output file URLs', () => testOutputFileObject(3, pathToFileURL, execa));137+test('stdout cannot use objectMode together with output file paths, sync', () => testOutputFileObject(1, getAbsolutePath, execaSync));138+test('stdout cannot use objectMode together with output file URLs, sync', () => testOutputFileObject(1, pathToFileURL, execaSync));139+test('stderr cannot use objectMode together with output file paths, sync', () => testOutputFileObject(2, getAbsolutePath, execaSync));140+test('stderr cannot use objectMode together with output file URLs, sync', () => testOutputFileObject(2, pathToFileURL, execaSync));141+test('stdio[*] cannot use objectMode together with output file paths, sync', () => testOutputFileObject(3, getAbsolutePath, execaSync));142+test('stdio[*] cannot use objectMode together with output file URLs, sync', () => testOutputFileObject(3, pathToFileURL, execaSync));143 142-test('Generator error stops writing to output file', async t => {144+test('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 });153 152-test('Generator error does not create output file, sync', async t => {154+test('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 });165 164-test('Output file error still returns transformed output, sync', async t => {166+test('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
1+import assert from 'node:assert/strict';2 import {readFile, writeFile, rm} from 'node:fs/promises';3 import path from 'node:path';4 import process from 'node:process';5 import {pathToFileURL} from 'node:url';5-import test from 'ava';6+import test from 'node:test';7 import tempfile from 'tempfile';8+import {assertRejects} from '../helpers/assert.js';9 import {execa, execaSync} from '../../index.js';10 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';11 import {identity, getStdio} from '../helpers/stdio.js';12 import {11 unmodified lines24 if (fdNumberOrName === 'string') {25 return {input: foobarString};26 }27 26- if (fdNumberOrName === 'binary') {27- return {input: foobarUint8Array};28- }29-30- return getStdioInputFile(fdNumberOrName, file);28+ return fdNumberOrName === 'binary' ? {input: foobarUint8Array} : getStdioInputFile(fdNumberOrName, file);29 };30 31 const getStdioInputFile = (fdNumberOrName, file) => getStdio(fdNumberOrName, typeof fdNumberOrName === 'string' ? file : {file});32 35-const testStdinFile = async (t, mapFilePath, fdNumber, execaMethod) => {33+const 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 };40 43-test('inputFile can be a file URL', testStdinFile, pathToFileURL, 'inputFile', execa);44-test('stdin can be a file URL', testStdinFile, pathToFileURL, 0, execa);45-test('inputFile can be an absolute file path', testStdinFile, identity, 'inputFile', execa);46-test('stdin can be an absolute file path', testStdinFile, getAbsolutePath, 0, execa);47-test('inputFile can be a relative file path', testStdinFile, identity, 'inputFile', execa);48-test('stdin can be a relative file path', testStdinFile, getRelativePath, 0, execa);49-test('inputFile can be a file URL - sync', testStdinFile, pathToFileURL, 'inputFile', execaSync);50-test('stdin can be a file URL - sync', testStdinFile, pathToFileURL, 0, execaSync);51-test('inputFile can be an absolute file path - sync', testStdinFile, identity, 'inputFile', execaSync);52-test('stdin can be an absolute file path - sync', testStdinFile, getAbsolutePath, 0, execaSync);53-test('inputFile can be a relative file path - sync', testStdinFile, identity, 'inputFile', execaSync);54-test('stdin can be a relative file path - sync', testStdinFile, getRelativePath, 0, execaSync);41+test('inputFile can be a file URL', () => testStdinFile(pathToFileURL, 'inputFile', execa));42+test('stdin can be a file URL', () => testStdinFile(pathToFileURL, 0, execa));43+test('inputFile can be an absolute file path', () => testStdinFile(identity, 'inputFile', execa));44+test('stdin can be an absolute file path', () => testStdinFile(getAbsolutePath, 0, execa));45+test('inputFile can be a relative file path', () => testStdinFile(identity, 'inputFile', execa));46+test('stdin can be a relative file path', () => testStdinFile(getRelativePath, 0, execa));47+test('inputFile can be a file URL - sync', () => testStdinFile(pathToFileURL, 'inputFile', execaSync));48+test('stdin can be a file URL - sync', () => testStdinFile(pathToFileURL, 0, execaSync));49+test('inputFile can be an absolute file path - sync', () => testStdinFile(identity, 'inputFile', execaSync));50+test('stdin can be an absolute file path - sync', () => testStdinFile(getAbsolutePath, 0, execaSync));51+test('inputFile can be a relative file path - sync', () => testStdinFile(identity, 'inputFile', execaSync));52+test('stdin can be a relative file path - sync', () => testStdinFile(getRelativePath, 0, execaSync));53 56-const testOutputFile = async (t, mapFile, fdNumber, execaMethod) => {54+const 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 };60 63-test('stdout can be a file URL', testOutputFile, pathToFileURL, 1, execa);64-test('stderr can be a file URL', testOutputFile, pathToFileURL, 2, execa);65-test('stdio[*] can be a file URL', testOutputFile, pathToFileURL, 3, execa);66-test('stdout can be an absolute file path', testOutputFile, getAbsolutePath, 1, execa);67-test('stderr can be an absolute file path', testOutputFile, getAbsolutePath, 2, execa);68-test('stdio[*] can be an absolute file path', testOutputFile, getAbsolutePath, 3, execa);69-test('stdout can be a relative file path', testOutputFile, getRelativePath, 1, execa);70-test('stderr can be a relative file path', testOutputFile, getRelativePath, 2, execa);71-test('stdio[*] can be a relative file path', testOutputFile, getRelativePath, 3, execa);72-test('stdout can be a file URL - sync', testOutputFile, pathToFileURL, 1, execaSync);73-test('stderr can be a file URL - sync', testOutputFile, pathToFileURL, 2, execaSync);74-test('stdio[*] can be a file URL - sync', testOutputFile, pathToFileURL, 3, execaSync);75-test('stdout can be an absolute file path - sync', testOutputFile, getAbsolutePath, 1, execaSync);76-test('stderr can be an absolute file path - sync', testOutputFile, getAbsolutePath, 2, execaSync);77-test('stdio[*] can be an absolute file path - sync', testOutputFile, getAbsolutePath, 3, execaSync);78-test('stdout can be a relative file path - sync', testOutputFile, getRelativePath, 1, execaSync);79-test('stderr can be a relative file path - sync', testOutputFile, getRelativePath, 2, execaSync);80-test('stdio[*] can be a relative file path - sync', testOutputFile, getRelativePath, 3, execaSync);61+test('stdout can be a file URL', () => testOutputFile(pathToFileURL, 1, execa));62+test('stderr can be a file URL', () => testOutputFile(pathToFileURL, 2, execa));63+test('stdio[*] can be a file URL', () => testOutputFile(pathToFileURL, 3, execa));64+test('stdout can be an absolute file path', () => testOutputFile(getAbsolutePath, 1, execa));65+test('stderr can be an absolute file path', () => testOutputFile(getAbsolutePath, 2, execa));66+test('stdio[*] can be an absolute file path', () => testOutputFile(getAbsolutePath, 3, execa));67+test('stdout can be a relative file path', () => testOutputFile(getRelativePath, 1, execa));68+test('stderr can be a relative file path', () => testOutputFile(getRelativePath, 2, execa));69+test('stdio[*] can be a relative file path', () => testOutputFile(getRelativePath, 3, execa));70+test('stdout can be a file URL - sync', () => testOutputFile(pathToFileURL, 1, execaSync));71+test('stderr can be a file URL - sync', () => testOutputFile(pathToFileURL, 2, execaSync));72+test('stdio[*] can be a file URL - sync', () => testOutputFile(pathToFileURL, 3, execaSync));73+test('stdout can be an absolute file path - sync', () => testOutputFile(getAbsolutePath, 1, execaSync));74+test('stderr can be an absolute file path - sync', () => testOutputFile(getAbsolutePath, 2, execaSync));75+test('stdio[*] can be an absolute file path - sync', () => testOutputFile(getAbsolutePath, 3, execaSync));76+test('stdout can be a relative file path - sync', () => testOutputFile(getRelativePath, 1, execaSync));77+test('stderr can be a relative file path - sync', () => testOutputFile(getRelativePath, 2, execaSync));78+test('stdio[*] can be a relative file path - sync', () => testOutputFile(getRelativePath, 3, execaSync));79 82-const testInputFileValidUrl = async (t, fdNumber, execaMethod) => {80+const testInputFileValidUrl = async (fdNumber, execaMethod) => {81 const filePath = tempfile();82 await writeFile(filePath, foobarString);83 const currentCwd = process.cwd();84 process.chdir(path.dirname(filePath));85 86 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 };94 97-test.serial('inputFile does not need to start with . when being a relative file path', testInputFileValidUrl, 'inputFile', execa);98-test.serial('stdin does not need to start with . when being a relative file path', testInputFileValidUrl, 0, execa);99-test.serial('inputFile does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 'inputFile', execaSync);100-test.serial('stdin does not need to start with . when being a relative file path - sync', testInputFileValidUrl, 0, execaSync);95+test('inputFile does not need to start with . when being a relative file path', () => testInputFileValidUrl('inputFile', execa));96+test('stdin does not need to start with . when being a relative file path', () => testInputFileValidUrl(0, execa));97+test('inputFile does not need to start with . when being a relative file path - sync', () => testInputFileValidUrl('inputFile', execaSync));98+test('stdin does not need to start with . when being a relative file path - sync', () => testInputFileValidUrl(0, execaSync));99 102-const testMultipleInputs = async (t, indices, execaMethod) => {100+const 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 };108 111-test('inputFile can be set', testMultipleInputs, ['inputFile'], runExeca);112-test('inputFile can be set - sync', testMultipleInputs, ['inputFile'], runExecaSync);113-test('inputFile can be set with $', testMultipleInputs, ['inputFile'], runScript);114-test('inputFile can be set with $.sync', testMultipleInputs, ['inputFile'], runScriptSync);115-test('input String and inputFile can be both set', testMultipleInputs, ['inputFile', 'string'], execa);116-test('input String and stdin can be both set', testMultipleInputs, [0, 'string'], execa);117-test('input Uint8Array and inputFile can be both set', testMultipleInputs, ['inputFile', 'binary'], execa);118-test('input Uint8Array and stdin can be both set', testMultipleInputs, [0, 'binary'], execa);119-test('stdin and inputFile can be both set', testMultipleInputs, [0, 'inputFile'], execa);120-test('input String, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'string'], execa);121-test('input Uint8Array, stdin and inputFile can be all set', testMultipleInputs, ['inputFile', 0, 'binary'], execa);122-test('input String and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'string'], execaSync);123-test('input String and stdin can be both set - sync', testMultipleInputs, [0, 'string'], execaSync);124-test('input Uint8Array and inputFile can be both set - sync', testMultipleInputs, ['inputFile', 'binary'], execaSync);125-test('input Uint8Array and stdin can be both set - sync', testMultipleInputs, [0, 'binary'], execaSync);126-test('stdin and inputFile can be both set - sync', testMultipleInputs, [0, 'inputFile'], execaSync);127-test('input String, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'string'], execaSync);128-test('input Uint8Array, stdin and inputFile can be all set - sync', testMultipleInputs, ['inputFile', 0, 'binary'], execaSync);109+test('inputFile can be set', () => testMultipleInputs(['inputFile'], runExeca));110+test('inputFile can be set - sync', () => testMultipleInputs(['inputFile'], runExecaSync));111+test('inputFile can be set with $', () => testMultipleInputs(['inputFile'], runScript));112+test('inputFile can be set with $.sync', () => testMultipleInputs(['inputFile'], runScriptSync));113+test('input String and inputFile can be both set', () => testMultipleInputs(['inputFile', 'string'], execa));114+test('input String and stdin can be both set', () => testMultipleInputs([0, 'string'], execa));115+test('input Uint8Array and inputFile can be both set', () => testMultipleInputs(['inputFile', 'binary'], execa));116+test('input Uint8Array and stdin can be both set', () => testMultipleInputs([0, 'binary'], execa));117+test('stdin and inputFile can be both set', () => testMultipleInputs([0, 'inputFile'], execa));118+test('input String, stdin and inputFile can be all set', () => testMultipleInputs(['inputFile', 0, 'string'], execa));119+test('input Uint8Array, stdin and inputFile can be all set', () => testMultipleInputs(['inputFile', 0, 'binary'], execa));120+test('input String and inputFile can be both set - sync', () => testMultipleInputs(['inputFile', 'string'], execaSync));121+test('input String and stdin can be both set - sync', () => testMultipleInputs([0, 'string'], execaSync));122+test('input Uint8Array and inputFile can be both set - sync', () => testMultipleInputs(['inputFile', 'binary'], execaSync));123+test('input Uint8Array and stdin can be both set - sync', () => testMultipleInputs([0, 'binary'], execaSync));124+test('stdin and inputFile can be both set - sync', () => testMultipleInputs([0, 'inputFile'], execaSync));125+test('input String, stdin and inputFile can be all set - sync', () => testMultipleInputs(['inputFile', 0, 'string'], execaSync));126+test('input Uint8Array, stdin and inputFile can be all set - sync', () => testMultipleInputs(['inputFile', 0, 'binary'], execaSync));127 130-const testMultipleOutputs = async (t, mapFile, fdNumber, execaMethod) => {128+const 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 };136 139-test('stdout can be two file URLs', testMultipleOutputs, pathToFileURL, 1, execa);140-test('stdout can be two file paths', testMultipleOutputs, getAbsolutePath, 1, execa);141-test('stdout can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 1, execaSync);142-test('stdout can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 1, execaSync);143-test('stderr can be two file URLs', testMultipleOutputs, pathToFileURL, 2, execa);144-test('stderr can be two file paths', testMultipleOutputs, getAbsolutePath, 2, execa);145-test('stderr can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 2, execaSync);146-test('stderr can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 2, execaSync);147-test('stdio[*] can be two file URLs', testMultipleOutputs, pathToFileURL, 3, execa);148-test('stdio[*] can be two file paths', testMultipleOutputs, getAbsolutePath, 3, execa);149-test('stdio[*] can be two file URLs - sync', testMultipleOutputs, pathToFileURL, 3, execaSync);150-test('stdio[*] can be two file paths - sync', testMultipleOutputs, getAbsolutePath, 3, execaSync);137+test('stdout can be two file URLs', () => testMultipleOutputs(pathToFileURL, 1, execa));138+test('stdout can be two file paths', () => testMultipleOutputs(getAbsolutePath, 1, execa));139+test('stdout can be two file URLs - sync', () => testMultipleOutputs(pathToFileURL, 1, execaSync));140+test('stdout can be two file paths - sync', () => testMultipleOutputs(getAbsolutePath, 1, execaSync));141+test('stderr can be two file URLs', () => testMultipleOutputs(pathToFileURL, 2, execa));142+test('stderr can be two file paths', () => testMultipleOutputs(getAbsolutePath, 2, execa));143+test('stderr can be two file URLs - sync', () => testMultipleOutputs(pathToFileURL, 2, execaSync));144+test('stderr can be two file paths - sync', () => testMultipleOutputs(getAbsolutePath, 2, execaSync));145+test('stdio[*] can be two file URLs', () => testMultipleOutputs(pathToFileURL, 3, execa));146+test('stdio[*] can be two file paths', () => testMultipleOutputs(getAbsolutePath, 3, execa));147+test('stdio[*] can be two file URLs - sync', () => testMultipleOutputs(pathToFileURL, 3, execaSync));148+test('stdio[*] can be two file paths - sync', () => testMultipleOutputs(getAbsolutePath, 3, execaSync));149 152-const testInputFileHanging = async (t, mapFilePath) => {150+const 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 };156 159-test('Passing an input file path when subprocess exits does not make promise hang', testInputFileHanging, getAbsolutePath);160-test('Passing an input file URL when subprocess exits does not make promise hang', testInputFileHanging, pathToFileURL);157+test('Passing an input file path when subprocess exits does not make promise hang', () => testInputFileHanging(getAbsolutePath));158+test('Passing an input file URL when subprocess exits does not make promise hang', () => testInputFileHanging(pathToFileURL));159 162-const testOverwriteFile = async (t, fdNumber, execaMethod, append) => {160+const 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 };167 170-test('Overwrite by default to stdout', testOverwriteFile, 1, execa, undefined);171-test('Overwrite by default to stderr', testOverwriteFile, 2, execa, undefined);172-test('Overwrite by default to stdio[*]', testOverwriteFile, 3, execa, undefined);173-test('Overwrite by default to stdout - sync', testOverwriteFile, 1, execaSync, undefined);174-test('Overwrite by default to stderr - sync', testOverwriteFile, 2, execaSync, undefined);175-test('Overwrite by default to stdio[*] - sync', testOverwriteFile, 3, execaSync, undefined);176-test('Overwrite with append false to stdout', testOverwriteFile, 1, execa, false);177-test('Overwrite with append false to stderr', testOverwriteFile, 2, execa, false);178-test('Overwrite with append false to stdio[*]', testOverwriteFile, 3, execa, false);179-test('Overwrite with append false to stdout - sync', testOverwriteFile, 1, execaSync, false);180-test('Overwrite with append false to stderr - sync', testOverwriteFile, 2, execaSync, false);181-test('Overwrite with append false to stdio[*] - sync', testOverwriteFile, 3, execaSync, false);168+test('Overwrite by default to stdout', () => testOverwriteFile(1, execa, undefined));169+test('Overwrite by default to stderr', () => testOverwriteFile(2, execa, undefined));170+test('Overwrite by default to stdio[*]', () => testOverwriteFile(3, execa, undefined));171+test('Overwrite by default to stdout - sync', () => testOverwriteFile(1, execaSync, undefined));172+test('Overwrite by default to stderr - sync', () => testOverwriteFile(2, execaSync, undefined));173+test('Overwrite by default to stdio[*] - sync', () => testOverwriteFile(3, execaSync, undefined));174+test('Overwrite with append false to stdout', () => testOverwriteFile(1, execa, false));175+test('Overwrite with append false to stderr', () => testOverwriteFile(2, execa, false));176+test('Overwrite with append false to stdio[*]', () => testOverwriteFile(3, execa, false));177+test('Overwrite with append false to stdout - sync', () => testOverwriteFile(1, execaSync, false));178+test('Overwrite with append false to stderr - sync', () => testOverwriteFile(2, execaSync, false));179+test('Overwrite with append false to stdio[*] - sync', () => testOverwriteFile(3, execaSync, false));180 183-const testAppendFile = async (t, fdNumber, execaMethod) => {181+const 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 };188 191-test('Can append to stdout', testAppendFile, 1, execa);192-test('Can append to stderr', testAppendFile, 2, execa);193-test('Can append to stdio[*]', testAppendFile, 3, execa);194-test('Can append to stdout - sync', testAppendFile, 1, execaSync);195-test('Can append to stderr - sync', testAppendFile, 2, execaSync);196-test('Can append to stdio[*] - sync', testAppendFile, 3, execaSync);189+test('Can append to stdout', () => testAppendFile(1, execa));190+test('Can append to stderr', () => testAppendFile(2, execa));191+test('Can append to stdio[*]', () => testAppendFile(3, execa));192+test('Can append to stdout - sync', () => testAppendFile(1, execaSync));193+test('Can append to stderr - sync', () => testAppendFile(2, execaSync));194+test('Can append to stdio[*] - sync', () => testAppendFile(3, execaSync));modified:test/stdio/file-path-mixed.js+46 added-45 removed
1+import assert from 'node:assert/strict';2 import {readFile, writeFile, rm} from 'node:fs/promises';3 import {pathToFileURL} from 'node:url';3-import test from 'ava';4+import test from 'node:test';5 import tempfile from 'tempfile';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {getStdio} from '../helpers/stdio.js';2 unmodified lines11 import {getAbsolutePath} from '../helpers/file-path.js';12 13 setFixtureDirectory();14 14-const testInputFileTransform = async (t, fdNumber, mapFile, execaMethod) => {15+const 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 };26 26-test('stdin can use generators together with input file paths', testInputFileTransform, 0, getAbsolutePath, execa);27-test('stdin can use generators together with input file URLs', testInputFileTransform, 0, pathToFileURL, execa);28-test('stdio[*] can use generators together with input file paths', testInputFileTransform, 3, getAbsolutePath, execa);29-test('stdio[*] can use generators together with input file URLs', testInputFileTransform, 3, pathToFileURL, execa);30-test('stdin can use generators together with input file paths, sync', testInputFileTransform, 0, getAbsolutePath, execaSync);31-test('stdin can use generators together with input file URLs, sync', testInputFileTransform, 0, pathToFileURL, execaSync);27+test('stdin can use generators together with input file paths', () => testInputFileTransform(0, getAbsolutePath, execa));28+test('stdin can use generators together with input file URLs', () => testInputFileTransform(0, pathToFileURL, execa));29+test('stdio[*] can use generators together with input file paths', () => testInputFileTransform(3, getAbsolutePath, execa));30+test('stdio[*] can use generators together with input file URLs', () => testInputFileTransform(3, pathToFileURL, execa));31+test('stdin can use generators together with input file paths, sync', () => testInputFileTransform(0, getAbsolutePath, execaSync));32+test('stdin can use generators together with input file URLs, sync', () => testInputFileTransform(0, pathToFileURL, execaSync));33 33-const testOutputFileTransform = async (t, fdNumber, mapFile, execaMethod) => {34+const 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 };43 43-test('stdout can use generators together with output file paths', testOutputFileTransform, 1, getAbsolutePath, execa);44-test('stdout can use generators together with output file URLs', testOutputFileTransform, 1, pathToFileURL, execa);45-test('stderr can use generators together with output file paths', testOutputFileTransform, 2, getAbsolutePath, execa);46-test('stderr can use generators together with output file URLs', testOutputFileTransform, 2, pathToFileURL, execa);47-test('stdio[*] can use generators together with output file paths', testOutputFileTransform, 3, getAbsolutePath, execa);48-test('stdio[*] can use generators together with output file URLs', testOutputFileTransform, 3, pathToFileURL, execa);49-test('stdout can use generators together with output file paths, sync', testOutputFileTransform, 1, getAbsolutePath, execaSync);50-test('stdout can use generators together with output file URLs, sync', testOutputFileTransform, 1, pathToFileURL, execaSync);51-test('stderr can use generators together with output file paths, sync', testOutputFileTransform, 2, getAbsolutePath, execaSync);52-test('stderr can use generators together with output file URLs, sync', testOutputFileTransform, 2, pathToFileURL, execaSync);53-test('stdio[*] can use generators together with output file paths, sync', testOutputFileTransform, 3, getAbsolutePath, execaSync);54-test('stdio[*] can use generators together with output file URLs, sync', testOutputFileTransform, 3, pathToFileURL, execaSync);44+test('stdout can use generators together with output file paths', () => testOutputFileTransform(1, getAbsolutePath, execa));45+test('stdout can use generators together with output file URLs', () => testOutputFileTransform(1, pathToFileURL, execa));46+test('stderr can use generators together with output file paths', () => testOutputFileTransform(2, getAbsolutePath, execa));47+test('stderr can use generators together with output file URLs', () => testOutputFileTransform(2, pathToFileURL, execa));48+test('stdio[*] can use generators together with output file paths', () => testOutputFileTransform(3, getAbsolutePath, execa));49+test('stdio[*] can use generators together with output file URLs', () => testOutputFileTransform(3, pathToFileURL, execa));50+test('stdout can use generators together with output file paths, sync', () => testOutputFileTransform(1, getAbsolutePath, execaSync));51+test('stdout can use generators together with output file URLs, sync', () => testOutputFileTransform(1, pathToFileURL, execaSync));52+test('stderr can use generators together with output file paths, sync', () => testOutputFileTransform(2, getAbsolutePath, execaSync));53+test('stderr can use generators together with output file URLs, sync', () => testOutputFileTransform(2, pathToFileURL, execaSync));54+test('stdio[*] can use generators together with output file paths, sync', () => testOutputFileTransform(3, getAbsolutePath, execaSync));55+test('stdio[*] can use generators together with output file URLs, sync', () => testOutputFileTransform(3, pathToFileURL, execaSync));56 56-const testOutputFileLines = async (t, fdNumber, mapFile, execaMethod) => {57+const 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 };67 67-test('stdout can use "lines: true" together with output file paths', testOutputFileLines, 1, getAbsolutePath, execa);68-test('stdout can use "lines: true" together with output file URLs', testOutputFileLines, 1, pathToFileURL, execa);69-test('stderr can use "lines: true" together with output file paths', testOutputFileLines, 2, getAbsolutePath, execa);70-test('stderr can use "lines: true" together with output file URLs', testOutputFileLines, 2, pathToFileURL, execa);71-test('stdio[*] can use "lines: true" together with output file paths', testOutputFileLines, 3, getAbsolutePath, execa);72-test('stdio[*] can use "lines: true" together with output file URLs', testOutputFileLines, 3, pathToFileURL, execa);73-test('stdout can use "lines: true" together with output file paths, sync', testOutputFileLines, 1, getAbsolutePath, execaSync);74-test('stdout can use "lines: true" together with output file URLs, sync', testOutputFileLines, 1, pathToFileURL, execaSync);75-test('stderr can use "lines: true" together with output file paths, sync', testOutputFileLines, 2, getAbsolutePath, execaSync);76-test('stderr can use "lines: true" together with output file URLs, sync', testOutputFileLines, 2, pathToFileURL, execaSync);77-test('stdio[*] can use "lines: true" together with output file paths, sync', testOutputFileLines, 3, getAbsolutePath, execaSync);78-test('stdio[*] can use "lines: true" together with output file URLs, sync', testOutputFileLines, 3, pathToFileURL, execaSync);68+test('stdout can use "lines: true" together with output file paths', () => testOutputFileLines(1, getAbsolutePath, execa));69+test('stdout can use "lines: true" together with output file URLs', () => testOutputFileLines(1, pathToFileURL, execa));70+test('stderr can use "lines: true" together with output file paths', () => testOutputFileLines(2, getAbsolutePath, execa));71+test('stderr can use "lines: true" together with output file URLs', () => testOutputFileLines(2, pathToFileURL, execa));72+test('stdio[*] can use "lines: true" together with output file paths', () => testOutputFileLines(3, getAbsolutePath, execa));73+test('stdio[*] can use "lines: true" together with output file URLs', () => testOutputFileLines(3, pathToFileURL, execa));74+test('stdout can use "lines: true" together with output file paths, sync', () => testOutputFileLines(1, getAbsolutePath, execaSync));75+test('stdout can use "lines: true" together with output file URLs, sync', () => testOutputFileLines(1, pathToFileURL, execaSync));76+test('stderr can use "lines: true" together with output file paths, sync', () => testOutputFileLines(2, getAbsolutePath, execaSync));77+test('stderr can use "lines: true" together with output file URLs, sync', () => testOutputFileLines(2, pathToFileURL, execaSync));78+test('stdio[*] can use "lines: true" together with output file paths, sync', () => testOutputFileLines(3, getAbsolutePath, execaSync));79+test('stdio[*] can use "lines: true" together with output file URLs, sync', () => testOutputFileLines(3, pathToFileURL, execaSync));80 80-const testOutputFileNoBuffer = async (t, buffer, execaMethod) => {81+const 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 };91 91-test('stdout can use "buffer: false" together with output file paths', testOutputFileNoBuffer, false, execa);92-test('stdout can use "buffer: false" together with output file paths, fd-specific', testOutputFileNoBuffer, {stdout: false}, execa);93-test('stdout can use "buffer: false" together with output file paths, sync', testOutputFileNoBuffer, false, execaSync);94-test('stdout can use "buffer: false" together with output file paths, fd-specific, sync', testOutputFileNoBuffer, {stdout: false}, execaSync);92+test('stdout can use "buffer: false" together with output file paths', () => testOutputFileNoBuffer(false, execa));93+test('stdout can use "buffer: false" together with output file paths, fd-specific', () => testOutputFileNoBuffer({stdout: false}, execa));94+test('stdout can use "buffer: false" together with output file paths, sync', () => testOutputFileNoBuffer(false, execaSync));95+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {getStdio} from '../helpers/stdio.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 8 setFixtureDirectory();9 8-const testEmptyArray = (t, fdNumber, optionName, execaMethod) => {9- t.throws(() => {10+const testEmptyArray = (fdNumber, optionName, execaMethod) => {11+ assertThrows(() => {12 execaMethod('empty.js', getStdio(fdNumber, []));13 }, {message: `The \`${optionName}\` option must not be an empty array.`});14 };15 14-test('Cannot pass an empty array to stdin', testEmptyArray, 0, 'stdin', execa);15-test('Cannot pass an empty array to stdout', testEmptyArray, 1, 'stdout', execa);16-test('Cannot pass an empty array to stderr', testEmptyArray, 2, 'stderr', execa);17-test('Cannot pass an empty array to stdio[*]', testEmptyArray, 3, 'stdio[3]', execa);18-test('Cannot pass an empty array to stdin - sync', testEmptyArray, 0, 'stdin', execaSync);19-test('Cannot pass an empty array to stdout - sync', testEmptyArray, 1, 'stdout', execaSync);20-test('Cannot pass an empty array to stderr - sync', testEmptyArray, 2, 'stderr', execaSync);21-test('Cannot pass an empty array to stdio[*] - sync', testEmptyArray, 3, 'stdio[3]', execaSync);16+test('Cannot pass an empty array to stdin', () => testEmptyArray(0, 'stdin', execa));17+test('Cannot pass an empty array to stdout', () => testEmptyArray(1, 'stdout', execa));18+test('Cannot pass an empty array to stderr', () => testEmptyArray(2, 'stderr', execa));19+test('Cannot pass an empty array to stdio[*]', () => testEmptyArray(3, 'stdio[3]', execa));20+test('Cannot pass an empty array to stdin - sync', () => testEmptyArray(0, 'stdin', execaSync));21+test('Cannot pass an empty array to stdout - sync', () => testEmptyArray(1, 'stdout', execaSync));22+test('Cannot pass an empty array to stderr - sync', () => testEmptyArray(2, 'stderr', execaSync));23+test('Cannot pass an empty array to stdio[*] - sync', () => testEmptyArray(3, 'stdio[3]', execaSync));24 23-const testEmptyArrayBufferFalse = (t, fdNumber, optionName, execaMethod) => {24- t.throws(() => {25+const 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 };30 29-test('Cannot pass an empty array to stdout with buffer: false', testEmptyArrayBufferFalse, 1, 'stdout', execa);30-test('Cannot pass an empty array to stderr with buffer: false', testEmptyArrayBufferFalse, 2, 'stderr', execa);31-test('Cannot pass an empty array to stdout with buffer: false - sync', testEmptyArrayBufferFalse, 1, 'stdout', execaSync);32-test('Cannot pass an empty array to stderr with buffer: false - sync', testEmptyArrayBufferFalse, 2, 'stderr', execaSync);31+test('Cannot pass an empty array to stdout with buffer: false', () => testEmptyArrayBufferFalse(1, 'stdout', execa));32+test('Cannot pass an empty array to stderr with buffer: false', () => testEmptyArrayBufferFalse(2, 'stderr', execa));33+test('Cannot pass an empty array to stdout with buffer: false - sync', () => testEmptyArrayBufferFalse(1, 'stdout', execaSync));34+test('Cannot pass an empty array to stderr with buffer: false - sync', () => testEmptyArrayBufferFalse(2, 'stderr', execaSync));35 34-const testInvalidValueSync = (t, fdNumber, stdioOption) => {35- const {message} = t.throws(() => {36+const 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 };42 41-test('stdin cannot be "overlapped", sync', testInvalidValueSync, 0, 'overlapped');42-test('stdout cannot be "overlapped", sync', testInvalidValueSync, 1, 'overlapped');43-test('stderr cannot be "overlapped", sync', testInvalidValueSync, 2, 'overlapped');44-test('stdio[*] cannot be "overlapped", sync', testInvalidValueSync, 3, 'overlapped');43+test('stdin cannot be "overlapped", sync', () => testInvalidValueSync(0, 'overlapped'));44+test('stdout cannot be "overlapped", sync', () => testInvalidValueSync(1, 'overlapped'));45+test('stderr cannot be "overlapped", sync', () => testInvalidValueSync(2, 'overlapped'));46+test('stdio[*] cannot be "overlapped", sync', () => testInvalidValueSync(3, 'overlapped'));47 46-const testInvalidArrayValue = (t, invalidStdio, fdNumber, execaMethod) => {47- t.throws(() => {48+const testInvalidArrayValue = (invalidStdio, fdNumber, execaMethod) => {49+ assertThrows(() => {50 execaMethod('empty.js', getStdio(fdNumber, ['pipe', invalidStdio]));51 }, {message: /must not include/});52 };53 52-test('Cannot pass "ignore" and another value to stdin', testInvalidArrayValue, 'ignore', 0, execa);53-test('Cannot pass "ignore" and another value to stdout', testInvalidArrayValue, 'ignore', 1, execa);54-test('Cannot pass "ignore" and another value to stderr', testInvalidArrayValue, 'ignore', 2, execa);55-test('Cannot pass "ignore" and another value to stdio[*]', testInvalidArrayValue, 'ignore', 3, execa);56-test('Cannot pass "ignore" and another value to stdin - sync', testInvalidArrayValue, 'ignore', 0, execaSync);57-test('Cannot pass "ignore" and another value to stdout - sync', testInvalidArrayValue, 'ignore', 1, execaSync);58-test('Cannot pass "ignore" and another value to stderr - sync', testInvalidArrayValue, 'ignore', 2, execaSync);59-test('Cannot pass "ignore" and another value to stdio[*] - sync', testInvalidArrayValue, 'ignore', 3, execaSync);54+test('Cannot pass "ignore" and another value to stdin', () => testInvalidArrayValue('ignore', 0, execa));55+test('Cannot pass "ignore" and another value to stdout', () => testInvalidArrayValue('ignore', 1, execa));56+test('Cannot pass "ignore" and another value to stderr', () => testInvalidArrayValue('ignore', 2, execa));57+test('Cannot pass "ignore" and another value to stdio[*]', () => testInvalidArrayValue('ignore', 3, execa));58+test('Cannot pass "ignore" and another value to stdin - sync', () => testInvalidArrayValue('ignore', 0, execaSync));59+test('Cannot pass "ignore" and another value to stdout - sync', () => testInvalidArrayValue('ignore', 1, execaSync));60+test('Cannot pass "ignore" and another value to stderr - sync', () => testInvalidArrayValue('ignore', 2, execaSync));61+test('Cannot pass "ignore" and another value to stdio[*] - sync', () => testInvalidArrayValue('ignore', 3, execaSync));62 63 // The `stdio: 'ipc'` value (raw `child_process` syntax) was replaced by the `ipc: true` option62-const testIpcStdioOption = (t, fdNumber, stdioOption, execaMethod) => {63- t.throws(() => {64+const testIpcStdioOption = (fdNumber, stdioOption, execaMethod) => {65+ assertThrows(() => {66 execaMethod('empty.js', getStdio(fdNumber, stdioOption));67 }, {message: /The `ipc: true` option must be used instead/});68 };69 68-test('stdin cannot be "ipc"', testIpcStdioOption, 0, 'ipc', execa);69-test('stdout cannot be "ipc"', testIpcStdioOption, 1, 'ipc', execa);70-test('stderr cannot be "ipc"', testIpcStdioOption, 2, 'ipc', execa);71-test('stdio[*] cannot be "ipc"', testIpcStdioOption, 3, 'ipc', execa);72-test('stdin cannot be "ipc" - sync', testIpcStdioOption, 0, 'ipc', execaSync);73-test('stdout cannot be "ipc" - sync', testIpcStdioOption, 1, 'ipc', execaSync);74-test('stderr cannot be "ipc" - sync', testIpcStdioOption, 2, 'ipc', execaSync);75-test('stdio[*] cannot be "ipc" - sync', testIpcStdioOption, 3, 'ipc', execaSync);76-test('stdio cannot be "ipc"', testIpcStdioOption, 'stdio', 'ipc', execa);77-test('stdio cannot be "ipc" - sync', testIpcStdioOption, 'stdio', 'ipc', execaSync);78-test('stdio[*] cannot be ["ipc"]', testIpcStdioOption, 3, ['ipc'], execa);79-test('stdio[*] cannot be ["ipc"] - sync', testIpcStdioOption, 3, ['ipc'], execaSync);80-test('stdio[*] cannot be {value: "ipc"}', testIpcStdioOption, 3, {value: 'ipc'}, execa);81-test('stdio[*] cannot be {value: "ipc"} - sync', testIpcStdioOption, 3, {value: 'ipc'}, execaSync);82-test('Cannot pass "ipc" and another value to stdio[*]', testIpcStdioOption, 3, ['pipe', 'ipc'], execa);83-test('Cannot pass "ipc" and another value to stdio[*] - sync', testIpcStdioOption, 3, ['pipe', 'ipc'], execaSync);84-test('Cannot pass {value: "ipc"} and another value to stdio[*]', testIpcStdioOption, 3, ['pipe', {value: 'ipc'}], execa);85-test('Cannot pass {value: "ipc"} and another value to stdio[*] - sync', testIpcStdioOption, 3, ['pipe', {value: 'ipc'}], execaSync);70+test('stdin cannot be "ipc"', () => testIpcStdioOption(0, 'ipc', execa));71+test('stdout cannot be "ipc"', () => testIpcStdioOption(1, 'ipc', execa));72+test('stderr cannot be "ipc"', () => testIpcStdioOption(2, 'ipc', execa));73+test('stdio[*] cannot be "ipc"', () => testIpcStdioOption(3, 'ipc', execa));74+test('stdin cannot be "ipc" - sync', () => testIpcStdioOption(0, 'ipc', execaSync));75+test('stdout cannot be "ipc" - sync', () => testIpcStdioOption(1, 'ipc', execaSync));76+test('stderr cannot be "ipc" - sync', () => testIpcStdioOption(2, 'ipc', execaSync));77+test('stdio[*] cannot be "ipc" - sync', () => testIpcStdioOption(3, 'ipc', execaSync));78+test('stdio cannot be "ipc"', () => testIpcStdioOption('stdio', 'ipc', execa));79+test('stdio cannot be "ipc" - sync', () => testIpcStdioOption('stdio', 'ipc', execaSync));80+test('stdio[*] cannot be ["ipc"]', () => testIpcStdioOption(3, ['ipc'], execa));81+test('stdio[*] cannot be ["ipc"] - sync', () => testIpcStdioOption(3, ['ipc'], execaSync));82+test('stdio[*] cannot be {value: "ipc"}', () => testIpcStdioOption(3, {value: 'ipc'}, execa));83+test('stdio[*] cannot be {value: "ipc"} - sync', () => testIpcStdioOption(3, {value: 'ipc'}, execaSync));84+test('Cannot pass "ipc" and another value to stdio[*]', () => testIpcStdioOption(3, ['pipe', 'ipc'], execa));85+test('Cannot pass "ipc" and another value to stdio[*] - sync', () => testIpcStdioOption(3, ['pipe', 'ipc'], execaSync));86+test('Cannot pass {value: "ipc"} and another value to stdio[*]', () => testIpcStdioOption(3, ['pipe', {value: 'ipc'}], execa));87+test('Cannot pass {value: "ipc"} and another value to stdio[*] - sync', () => testIpcStdioOption(3, ['pipe', {value: 'ipc'}], execaSync));88 89 // A file descriptor must be a non-negative integer. Without this, `node:child_process` aborts the current process with a fatal assertion when spawning.88-const testInvalidFileDescriptor = (t, fdNumber, optionName, stdioOption, execaMethod) => {89- t.throws(() => {90+const 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 };95 94-test('Cannot pass a fractional file descriptor to stdin', testInvalidFileDescriptor, 0, 'stdin', 1.5, execa);95-test('Cannot pass NaN as a file descriptor to stdin', testInvalidFileDescriptor, 0, 'stdin', Number.NaN, execa);96-test('Cannot pass Infinity as a file descriptor to stdout', testInvalidFileDescriptor, 1, 'stdout', Number.POSITIVE_INFINITY, execa);97-test('Cannot pass a too large file descriptor to stderr', testInvalidFileDescriptor, 2, 'stderr', 2 ** 32, execa);98-test('Cannot pass a negative file descriptor to stdio[*]', testInvalidFileDescriptor, 3, 'stdio[3]', -1, execa);99-test('Cannot pass a fractional file descriptor to stdout', testInvalidFileDescriptor, 1, 'stdout', 1.5, execaSync);100-test('Cannot pass a negative file descriptor to stdin', testInvalidFileDescriptor, 0, 'stdin', -1, execaSync);96+test('Cannot pass a fractional file descriptor to stdin', () => testInvalidFileDescriptor(0, 'stdin', 1.5, execa));97+test('Cannot pass NaN as a file descriptor to stdin', () => testInvalidFileDescriptor(0, 'stdin', NaN, execa));98+test('Cannot pass Infinity as a file descriptor to stdout', () => testInvalidFileDescriptor(1, 'stdout', Infinity, execa));99+test('Cannot pass a too large file descriptor to stderr', () => testInvalidFileDescriptor(2, 'stderr', 2 ** 32, execa));100+test('Cannot pass a negative file descriptor to stdio[*]', () => testInvalidFileDescriptor(3, 'stdio[3]', -1, execa));101+test('Cannot pass a fractional file descriptor to stdout', () => testInvalidFileDescriptor(1, 'stdout', 1.5, execaSync));102+test('Cannot pass a negative file descriptor to stdin', () => testInvalidFileDescriptor(0, 'stdin', -1, execaSync));modified:test/stdio/handle-normal.js+28 added-27 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa} from '../../index.js';4 import {getStdio} from '../helpers/stdio.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {foobarString, foobarUint8Array} from '../helpers/input.js';7 8 setFixtureDirectory();9 9-const testInputOverlapped = async (t, fdNumber) => {10+const 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 };14 14-test('stdin can be ["overlapped", "pipe"]', testInputOverlapped, 0);15-test('stdio[*] input can be ["overlapped", "pipe"]', testInputOverlapped, 3);15+test('stdin can be ["overlapped", "pipe"]', () => testInputOverlapped(0));16+test('stdio[*] input can be ["overlapped", "pipe"]', () => testInputOverlapped(3));17 17-const testOutputOverlapped = async (t, fdNumber) => {18+const 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 };22 22-test('stdout can be ["overlapped", "pipe"]', testOutputOverlapped, 1);23-test('stderr can be ["overlapped", "pipe"]', testOutputOverlapped, 2);24-test('stdio[*] output can be ["overlapped", "pipe"]', testOutputOverlapped, 3);23+test('stdout can be ["overlapped", "pipe"]', () => testOutputOverlapped(1));24+test('stderr can be ["overlapped", "pipe"]', () => testOutputOverlapped(2));25+test('stdio[*] output can be ["overlapped", "pipe"]', () => testOutputOverlapped(3));26 26-const testFd3Undefined = async (t, stdioOption, options) => {27+const 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);31 32 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 };36 36-test('stdio[*] undefined means "ignore"', testFd3Undefined, undefined, {});37-test('stdio[*] null means "ignore"', testFd3Undefined, null, {});38-test('stdio[*] [undefined] means "ignore"', testFd3Undefined, [undefined], {});39-test('stdio[*] [null] means "ignore"', testFd3Undefined, [null], {});40-test('stdio[*] undefined means "ignore", "lines: true"', testFd3Undefined, undefined, {lines: true});41-test('stdio[*] null means "ignore", "lines: true"', testFd3Undefined, null, {lines: true});42-test('stdio[*] [undefined] means "ignore", "lines: true"', testFd3Undefined, [undefined], {lines: true});43-test('stdio[*] [null] means "ignore", "lines: true"', testFd3Undefined, [null], {lines: true});44-test('stdio[*] undefined means "ignore", "encoding: hex"', testFd3Undefined, undefined, {encoding: 'hex'});45-test('stdio[*] null means "ignore", "encoding: hex"', testFd3Undefined, null, {encoding: 'hex'});46-test('stdio[*] [undefined] means "ignore", "encoding: hex"', testFd3Undefined, [undefined], {encoding: 'hex'});47-test('stdio[*] [null] means "ignore", "encoding: hex"', testFd3Undefined, [null], {encoding: 'hex'});37+test('stdio[*] undefined means "ignore"', () => testFd3Undefined(undefined, {}));38+test('stdio[*] null means "ignore"', () => testFd3Undefined(null, {}));39+test('stdio[*] [undefined] means "ignore"', () => testFd3Undefined([undefined], {}));40+test('stdio[*] [null] means "ignore"', () => testFd3Undefined([null], {}));41+test('stdio[*] undefined means "ignore", "lines: true"', () => testFd3Undefined(undefined, {lines: true}));42+test('stdio[*] null means "ignore", "lines: true"', () => testFd3Undefined(null, {lines: true}));43+test('stdio[*] [undefined] means "ignore", "lines: true"', () => testFd3Undefined([undefined], {lines: true}));44+test('stdio[*] [null] means "ignore", "lines: true"', () => testFd3Undefined([null], {lines: true}));45+test('stdio[*] undefined means "ignore", "encoding: hex"', () => testFd3Undefined(undefined, {encoding: 'hex'}));46+test('stdio[*] null means "ignore", "encoding: hex"', () => testFd3Undefined(null, {encoding: 'hex'}));47+test('stdio[*] [undefined] means "ignore", "encoding: hex"', () => testFd3Undefined([undefined], {encoding: 'hex'}));48+test('stdio[*] [null] means "ignore", "encoding: hex"', () => testFd3Undefined([null], {encoding: 'hex'}));modified:test/stdio/handle-options.js+42 added-32 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa} from '../../index.js';3-import {getStdio} from '../helpers/stdio.js';4+import {getStdio, fullStdio} from '../helpers/stdio.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6+import {nestedSubprocess} from '../helpers/nested.js';7 8 setFixtureDirectory();9 8-const testNoPipeOption = async (t, stdioOption, fdNumber) => {10+const 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 };15 14-test('stdin can be "ignore"', testNoPipeOption, 'ignore', 0);15-test('stdin can be ["ignore"]', testNoPipeOption, ['ignore'], 0);16-test('stdin can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 0);17-test('stdin can be "inherit"', testNoPipeOption, 'inherit', 0);18-test('stdin can be ["inherit"]', testNoPipeOption, ['inherit'], 0);19-test('stdin can be 0', testNoPipeOption, 0, 0);20-test('stdin can be [0]', testNoPipeOption, [0], 0);21-test('stdout can be "ignore"', testNoPipeOption, 'ignore', 1);22-test('stdout can be ["ignore"]', testNoPipeOption, ['ignore'], 1);23-test('stdout can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 1);24-test('stdout can be "inherit"', testNoPipeOption, 'inherit', 1);25-test('stdout can be ["inherit"]', testNoPipeOption, ['inherit'], 1);26-test('stdout can be 1', testNoPipeOption, 1, 1);27-test('stdout can be [1]', testNoPipeOption, [1], 1);28-test('stderr can be "ignore"', testNoPipeOption, 'ignore', 2);29-test('stderr can be ["ignore"]', testNoPipeOption, ['ignore'], 2);30-test('stderr can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 2);31-test('stderr can be "inherit"', testNoPipeOption, 'inherit', 2);32-test('stderr can be ["inherit"]', testNoPipeOption, ['inherit'], 2);33-test('stderr can be 2', testNoPipeOption, 2, 2);34-test('stderr can be [2]', testNoPipeOption, [2], 2);35-test('stdio[*] can be "ignore"', testNoPipeOption, 'ignore', 3);36-test('stdio[*] can be ["ignore"]', testNoPipeOption, ['ignore'], 3);37-test('stdio[*] can be ["ignore", "ignore"]', testNoPipeOption, ['ignore', 'ignore'], 3);38-test('stdio[*] can be "inherit"', testNoPipeOption, 'inherit', 3);39-test('stdio[*] can be ["inherit"]', testNoPipeOption, ['inherit'], 3);40-test('stdio[*] can be 3', testNoPipeOption, 3, 3);41-test('stdio[*] can be [3]', testNoPipeOption, [3], 3);16+test('stdin can be "ignore"', () => testNoPipeOption('ignore', 0));17+test('stdin can be ["ignore"]', () => testNoPipeOption(['ignore'], 0));18+test('stdin can be ["ignore", "ignore"]', () => testNoPipeOption(['ignore', 'ignore'], 0));19+test('stdin can be "inherit"', () => testNoPipeOption('inherit', 0));20+test('stdin can be ["inherit"]', () => testNoPipeOption(['inherit'], 0));21+test('stdin can be 0', () => testNoPipeOption(0, 0));22+test('stdin can be [0]', () => testNoPipeOption([0], 0));23+test('stdout can be "ignore"', () => testNoPipeOption('ignore', 1));24+test('stdout can be ["ignore"]', () => testNoPipeOption(['ignore'], 1));25+test('stdout can be ["ignore", "ignore"]', () => testNoPipeOption(['ignore', 'ignore'], 1));26+test('stdout can be "inherit"', () => testNoPipeOption('inherit', 1));27+test('stdout can be ["inherit"]', () => testNoPipeOption(['inherit'], 1));28+test('stdout can be 1', () => testNoPipeOption(1, 1));29+test('stdout can be [1]', () => testNoPipeOption([1], 1));30+test('stderr can be "ignore"', () => testNoPipeOption('ignore', 2));31+test('stderr can be ["ignore"]', () => testNoPipeOption(['ignore'], 2));32+test('stderr can be ["ignore", "ignore"]', () => testNoPipeOption(['ignore', 'ignore'], 2));33+test('stderr can be "inherit"', () => testNoPipeOption('inherit', 2));34+test('stderr can be ["inherit"]', () => testNoPipeOption(['inherit'], 2));35+test('stderr can be 2', () => testNoPipeOption(2, 2));36+test('stderr can be [2]', () => testNoPipeOption([2], 2));37+test('stdio[*] can be "ignore"', () => testNoPipeOption('ignore', 3));38+test('stdio[*] can be ["ignore"]', () => testNoPipeOption(['ignore'], 3));39+test('stdio[*] can be ["ignore", "ignore"]', () => testNoPipeOption(['ignore', 'ignore'], 3));40+41+// 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.42+const 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+};47+48+test('stdio[*] can be "inherit"', () => testNoPipeOptionFd3('inherit'));49+test('stdio[*] can be ["inherit"]', () => testNoPipeOptionFd3(['inherit']));50+test('stdio[*] can be 3', () => testNoPipeOptionFd3(3));51+test('stdio[*] can be [3]', () => testNoPipeOptionFd3([3]));modified:test/stdio/iterable.js+96 added-94 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {setImmediate} from 'node:timers/promises';3-import test from 'ava';4+import test from 'node:test';5+import {assertThrows, assertRejects} from '../helpers/assert.js';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {getStdio} from '../helpers/stdio.js';9 import {34 unmodified lines44 };45 46 setFixtureDirectory();47 46-const testIterable = async (t, stdioOption, fdNumber, execaMethod) => {48+const 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 };52 51-const testIpcDataIterable = async (t, fdNumber, execaMethod) => {53+const 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 };57 56-test.serial('stdin option can be an array of strings', testIterable, [foobarArray], 0, execa);57-test.serial('stdin option can be an array of strings - sync', testIterable, [foobarArray], 0, execaSync);58-test.serial('stdio[*] option can be an array of strings', testIterable, [foobarArray], 3, execa);59-test.serial('stdin option can be an array with "ipc" as input data', testIpcDataIterable, 0, execa);60-test.serial('stdin option can be an array with "ipc" as input data - sync', testIpcDataIterable, 0, execaSync);61-test.serial('stdio[*] option can be an array with "ipc" as input data', testIpcDataIterable, 3, execa);62-test.serial('stdin option can be an array of Uint8Arrays', testIterable, [binaryArray], 0, execa);63-test.serial('stdin option can be an array of Uint8Arrays - sync', testIterable, [binaryArray], 0, execaSync);64-test.serial('stdio[*] option can be an array of Uint8Arrays', testIterable, [binaryArray], 3, execa);65-test.serial('stdin option can be an iterable of strings', testIterable, stringGenerator(), 0, execa);66-test.serial('stdin option can be an iterable of strings - sync', testIterable, stringGenerator(), 0, execaSync);67-test.serial('stdio[*] option can be an iterable of strings', testIterable, stringGenerator(), 3, execa);68-test.serial('stdin option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 0, execa);69-test.serial('stdin option can be an iterable of Uint8Arrays - sync', testIterable, binaryGenerator(), 0, execaSync);70-test.serial('stdio[*] option can be an iterable of Uint8Arrays', testIterable, binaryGenerator(), 3, execa);71-test.serial('stdin option can be an iterable of strings + Uint8Arrays', testIterable, mixedGenerator(), 0, execa);72-test.serial('stdin option can be an iterable of strings + Uint8Arrays - sync', testIterable, mixedGenerator(), 0, execaSync);73-test.serial('stdio[*] option can be an iterable of strings + Uint8Arrays', testIterable, mixedGenerator(), 3, execa);74-test.serial('stdin option can be an async iterable', testIterable, asyncGenerator(), 0, execa);75-test.serial('stdio[*] option can be an async iterable', testIterable, asyncGenerator(), 3, execa);58+test('stdin option can be an array of strings', () => testIterable([foobarArray], 0, execa));59+test('stdin option can be an array of strings - sync', () => testIterable([foobarArray], 0, execaSync));60+test('stdio[*] option can be an array of strings', () => testIterable([foobarArray], 3, execa));61+test('stdin option can be an array with "ipc" as input data', () => testIpcDataIterable(0, execa));62+test('stdin option can be an array with "ipc" as input data - sync', () => testIpcDataIterable(0, execaSync));63+test('stdio[*] option can be an array with "ipc" as input data', () => testIpcDataIterable(3, execa));64+test('stdin option can be an array of Uint8Arrays', () => testIterable([binaryArray], 0, execa));65+test('stdin option can be an array of Uint8Arrays - sync', () => testIterable([binaryArray], 0, execaSync));66+test('stdio[*] option can be an array of Uint8Arrays', () => testIterable([binaryArray], 3, execa));67+test('stdin option can be an iterable of strings', () => testIterable(stringGenerator(), 0, execa));68+test('stdin option can be an iterable of strings - sync', () => testIterable(stringGenerator(), 0, execaSync));69+test('stdio[*] option can be an iterable of strings', () => testIterable(stringGenerator(), 3, execa));70+test('stdin option can be an iterable of Uint8Arrays', () => testIterable(binaryGenerator(), 0, execa));71+test('stdin option can be an iterable of Uint8Arrays - sync', () => testIterable(binaryGenerator(), 0, execaSync));72+test('stdio[*] option can be an iterable of Uint8Arrays', () => testIterable(binaryGenerator(), 3, execa));73+test('stdin option can be an iterable of strings + Uint8Arrays', () => testIterable(mixedGenerator(), 0, execa));74+test('stdin option can be an iterable of strings + Uint8Arrays - sync', () => testIterable(mixedGenerator(), 0, execaSync));75+test('stdio[*] option can be an iterable of strings + Uint8Arrays', () => testIterable(mixedGenerator(), 3, execa));76+test('stdin option can be an async iterable', () => testIterable(asyncGenerator(), 0, execa));77+test('stdio[*] option can be an async iterable', () => testIterable(asyncGenerator(), 3, execa));78 79 const foobarObjectGenerator = function * () {80 yield foobarObject;81 };1 unmodified line83 const foobarAsyncObjectGenerator = async function * () {84 yield foobarObject;85 };86 85-const testObjectIterable = async (t, stdioOption, fdNumber, execaMethod) => {87+const 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 };91 90-test('stdin option can be an array of objects', testObjectIterable, [foobarObject], 0, execa);91-test('stdio[*] option can be an array of objects', testObjectIterable, [foobarObject], 3, execa);92-test('stdin option can be an iterable of objects', testObjectIterable, foobarObjectGenerator(), 0, execa);93-test('stdio[*] option can be an iterable of objects', testObjectIterable, foobarObjectGenerator(), 3, execa);94-test('stdin option can be an async iterable of objects', testObjectIterable, foobarAsyncObjectGenerator(), 0, execa);95-test('stdio[*] option can be an async iterable of objects', testObjectIterable, foobarAsyncObjectGenerator(), 3, execa);96-test('stdin option can be an array of objects - sync', testObjectIterable, [foobarObject], 0, execaSync);97-test('stdin option can be an iterable of objects - sync', testObjectIterable, foobarObjectGenerator(), 0, execaSync);92+test('stdin option can be an array of objects', () => testObjectIterable([foobarObject], 0, execa));93+test('stdio[*] option can be an array of objects', () => testObjectIterable([foobarObject], 3, execa));94+test('stdin option can be an iterable of objects', () => testObjectIterable(foobarObjectGenerator(), 0, execa));95+test('stdio[*] option can be an iterable of objects', () => testObjectIterable(foobarObjectGenerator(), 3, execa));96+test('stdin option can be an async iterable of objects', () => testObjectIterable(foobarAsyncObjectGenerator(), 0, execa));97+test('stdio[*] option can be an async iterable of objects', () => testObjectIterable(foobarAsyncObjectGenerator(), 3, execa));98+test('stdin option can be an array of objects - sync', () => testObjectIterable([foobarObject], 0, execaSync));99+test('stdin option can be an iterable of objects - sync', () => testObjectIterable(foobarObjectGenerator(), 0, execaSync));100 99-const testIterableNoGeneratorsSync = (t, stdioOption, fdNumber) => {100- t.throws(() => {101+const testIterableNoGeneratorsSync = (stdioOption, fdNumber) => {102+ assertThrows(() => {103 execaSync('empty.js', getStdio(fdNumber, stdioOption));104 }, {message: /must be used to serialize/});105 };106 105-test('stdin option cannot be an array of objects without generators - sync', testIterableNoGeneratorsSync, [[foobarObject]], 0);106-test('stdin option cannot be an iterable of objects without generators - sync', testIterableNoGeneratorsSync, foobarObjectGenerator(), 0);107+test('stdin option cannot be an array of objects without generators - sync', () => testIterableNoGeneratorsSync([[foobarObject]], 0));108+test('stdin option cannot be an iterable of objects without generators - sync', () => testIterableNoGeneratorsSync(foobarObjectGenerator(), 0));109 108-const testIterableNoSerializeSync = (t, stdioOption, fdNumber) => {109- t.throws(() => {110+const 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 };115 114-test('stdin option cannot be an array of objects without serializing - sync', testIterableNoSerializeSync, [foobarObject], 0);115-test('stdin option cannot be an iterable of objects without serializing - sync', testIterableNoSerializeSync, foobarObjectGenerator(), 0);116+test('stdin option cannot be an array of objects without serializing - sync', () => testIterableNoSerializeSync([foobarObject], 0));117+test('stdin option cannot be an iterable of objects without serializing - sync', () => testIterableNoSerializeSync(foobarObjectGenerator(), 0));118 117-const testIterableSync = (t, stdioOption, fdNumber) => {118- t.throws(() => {119+const testIterableSync = (stdioOption, fdNumber) => {120+ assertThrows(() => {121 execaSync('empty.js', getStdio(fdNumber, stdioOption));122 }, {message: /an iterable with synchronous methods/});123 };124 123-test('stdio[*] option cannot be an array of strings - sync', testIterableSync, [foobarArray], 3);124-test('stdio[*] option cannot be an array of Uint8Arrays - sync', testIterableSync, [binaryArray], 3);125-test('stdio[*] option cannot be an array of objects - sync', testIterableSync, [[foobarObject]], 3);126-test('stdio[*] option cannot be an iterable of strings - sync', testIterableSync, stringGenerator(), 3);127-test('stdio[*] option cannot be an iterable of Uint8Arrays - sync', testIterableSync, binaryGenerator(), 3);128-test('stdio[*] option cannot be an iterable of objects - sync', testIterableSync, foobarObjectGenerator(), 3);129-test('stdio[*] option cannot be multiple iterables - sync', testIterableSync, [stringGenerator(), stringGenerator()], 3);125+test('stdio[*] option cannot be an array of strings - sync', () => testIterableSync([foobarArray], 3));126+test('stdio[*] option cannot be an array of Uint8Arrays - sync', () => testIterableSync([binaryArray], 3));127+test('stdio[*] option cannot be an array of objects - sync', () => testIterableSync([[foobarObject]], 3));128+test('stdio[*] option cannot be an iterable of strings - sync', () => testIterableSync(stringGenerator(), 3));129+test('stdio[*] option cannot be an iterable of Uint8Arrays - sync', () => testIterableSync(binaryGenerator(), 3));130+test('stdio[*] option cannot be an iterable of objects - sync', () => testIterableSync(foobarObjectGenerator(), 3));131+test('stdio[*] option cannot be multiple iterables - sync', () => testIterableSync([stringGenerator(), stringGenerator()], 3));132 131-const testAsyncIterableSync = (t, stdioOption, fdNumber) => {132- t.throws(() => {133+const testAsyncIterableSync = (stdioOption, fdNumber) => {134+ assertThrows(() => {135 execaSync('empty.js', getStdio(fdNumber, stdioOption));136 }, {message: /an async iterable with synchronous method/});137 };138 137-test('stdin option cannot be an async iterable - sync', testAsyncIterableSync, asyncGenerator(), 0);138-test('stdio[*] option cannot be an async iterable - sync', testAsyncIterableSync, asyncGenerator(), 3);139-test('stdin option cannot be an async iterable of objects - sync', testAsyncIterableSync, foobarAsyncObjectGenerator(), 0);140-test('stdio[*] option cannot be an async iterable of objects - sync', testAsyncIterableSync, foobarAsyncObjectGenerator(), 3);139+test('stdin option cannot be an async iterable - sync', () => testAsyncIterableSync(asyncGenerator(), 0));140+test('stdio[*] option cannot be an async iterable - sync', () => testAsyncIterableSync(asyncGenerator(), 3));141+test('stdin option cannot be an async iterable of objects - sync', () => testAsyncIterableSync(foobarAsyncObjectGenerator(), 0));142+test('stdio[*] option cannot be an async iterable of objects - sync', () => testAsyncIterableSync(foobarAsyncObjectGenerator(), 3));143 142-const testIterableError = async (t, fdNumber) => {144+const 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 };149 148-test('stdin option handles errors in iterables', testIterableError, 0);149-test('stdio[*] option handles errors in iterables', testIterableError, 3);150+test('stdin option handles errors in iterables', () => testIterableError(0));151+test('stdio[*] option handles errors in iterables', () => testIterableError(3));152 151-const testIterableErrorSync = (t, fdNumber) => {153+const 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 };160 159-test('stdin option handles errors in iterables - sync', testIterableErrorSync, 0);160-test('stdio[*] option handles errors in iterables - sync', testIterableErrorSync, 3);161+test('stdin option handles errors in iterables - sync', () => testIterableErrorSync(0));162+test('stdio[*] option handles errors in iterables - sync', () => testIterableErrorSync(3));163 162-const testNoIterableOutput = (t, stdioOption, fdNumber, execaMethod) => {163- t.throws(() => {164+const testNoIterableOutput = (stdioOption, fdNumber, execaMethod) => {165+ assertThrows(() => {166 execaMethod('empty.js', getStdio(fdNumber, stdioOption));167 }, {message: /cannot be an iterable/});168 };169 168-test('stdout option cannot be an array of strings', testNoIterableOutput, [foobarArray], 1, execa);169-test('stderr option cannot be an array of strings', testNoIterableOutput, [foobarArray], 2, execa);170-test('stdout option cannot be an array of strings - sync', testNoIterableOutput, [foobarArray], 1, execaSync);171-test('stderr option cannot be an array of strings - sync', testNoIterableOutput, [foobarArray], 2, execaSync);172-test('stdout option cannot be an iterable', testNoIterableOutput, stringGenerator(), 1, execa);173-test('stderr option cannot be an iterable', testNoIterableOutput, stringGenerator(), 2, execa);174-test('stdout option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 1, execaSync);175-test('stderr option cannot be an iterable - sync', testNoIterableOutput, stringGenerator(), 2, execaSync);170+test('stdout option cannot be an array of strings', () => testNoIterableOutput([foobarArray], 1, execa));171+test('stderr option cannot be an array of strings', () => testNoIterableOutput([foobarArray], 2, execa));172+test('stdout option cannot be an array of strings - sync', () => testNoIterableOutput([foobarArray], 1, execaSync));173+test('stderr option cannot be an array of strings - sync', () => testNoIterableOutput([foobarArray], 2, execaSync));174+test('stdout option cannot be an iterable', () => testNoIterableOutput(stringGenerator(), 1, execa));175+test('stderr option cannot be an iterable', () => testNoIterableOutput(stringGenerator(), 2, execa));176+test('stdout option cannot be an iterable - sync', () => testNoIterableOutput(stringGenerator(), 1, execaSync));177+test('stderr option cannot be an iterable - sync', () => testNoIterableOutput(stringGenerator(), 2, execaSync));178 177-test('stdin option can be an infinite iterable', async t => {179+test('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 });188 187-const testMultipleIterable = async (t, stdioOption, fdNumber, execaMethod) => {189+const 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 };197 196-test('stdin option can be multiple iterables', testMultipleIterable, [stringGenerator(), stringGenerator()], 0, execa);197-test('stdio[*] option can be multiple iterables', testMultipleIterable, [stringGenerator(), stringGenerator()], 3, execa);198-test('stdin option can be multiple iterables - sync', testMultipleIterable, [stringGenerator(), stringGenerator()], 0, execaSync);199-test('stdin option can be multiple mixed iterables', testMultipleIterable, [stringGenerator(), binaryGenerator()], 0, execa);200-test('stdio[*] option can be multiple mixed iterables', testMultipleIterable, [stringGenerator(), binaryGenerator()], 3, execa);201-test('stdin option can be multiple mixed iterables - sync', testMultipleIterable, [stringGenerator(), binaryGenerator()], 0, execaSync);202-test('stdin option can be sync/async mixed iterables', testMultipleIterable, [stringGenerator(), asyncGenerator()], 0, execa);203-test('stdio[*] option can be sync/async mixed iterables', testMultipleIterable, [stringGenerator(), asyncGenerator()], 3, execa);198+test('stdin option can be multiple iterables', () => testMultipleIterable([stringGenerator(), stringGenerator()], 0, execa));199+test('stdio[*] option can be multiple iterables', () => testMultipleIterable([stringGenerator(), stringGenerator()], 3, execa));200+test('stdin option can be multiple iterables - sync', () => testMultipleIterable([stringGenerator(), stringGenerator()], 0, execaSync));201+test('stdin option can be multiple mixed iterables', () => testMultipleIterable([stringGenerator(), binaryGenerator()], 0, execa));202+test('stdio[*] option can be multiple mixed iterables', () => testMultipleIterable([stringGenerator(), binaryGenerator()], 3, execa));203+test('stdin option can be multiple mixed iterables - sync', () => testMultipleIterable([stringGenerator(), binaryGenerator()], 0, execaSync));204+test('stdin option can be sync/async mixed iterables', () => testMultipleIterable([stringGenerator(), asyncGenerator()], 0, execa));205+test('stdio[*] option can be sync/async mixed iterables', () => testMultipleIterable([stringGenerator(), asyncGenerator()], 3, execa));206 205-test('stdin option iterable is canceled on subprocess error', async t => {207+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertRejects} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {fullStdio} from '../helpers/stdio.js';7 import {getOutputsGenerator} from '../helpers/generator.js';10 unmodified lines18 19 setFixtureDirectory();20 21 // eslint-disable-next-line max-params20-const testStreamLines = async (t, fdNumber, input, expectedOutput, lines, stripFinalNewline, execaMethod) => {22+const 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 };26 25-test('"lines: true" splits lines, stdout', testStreamLines, 1, simpleFull, simpleLines, true, false, execa);26-test('"lines: true" splits lines, stdout, fd-specific', testStreamLines, 1, simpleFull, simpleLines, {stdout: true}, false, execa);27-test('"lines: true" splits lines, stderr', testStreamLines, 2, simpleFull, simpleLines, true, false, execa);28-test('"lines: true" splits lines, stderr, fd-specific', testStreamLines, 2, simpleFull, simpleLines, {stderr: true}, false, execa);29-test('"lines: true" splits lines, stdio[*]', testStreamLines, 3, simpleFull, simpleLines, true, false, execa);30-test('"lines: true" splits lines, stdio[*], fd-specific', testStreamLines, 3, simpleFull, simpleLines, {fd3: true}, false, execa);31-test('"lines: true" splits lines, stdout, stripFinalNewline', testStreamLines, 1, simpleFull, noNewlinesChunks, true, true, execa);32-test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific', testStreamLines, 1, simpleFull, noNewlinesChunks, true, {stdout: true}, execa);33-test('"lines: true" splits lines, stderr, stripFinalNewline', testStreamLines, 2, simpleFull, noNewlinesChunks, true, true, execa);34-test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific', testStreamLines, 2, simpleFull, noNewlinesChunks, true, {stderr: true}, execa);35-test('"lines: true" splits lines, stdio[*], stripFinalNewline', testStreamLines, 3, simpleFull, noNewlinesChunks, true, true, execa);36-test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific', testStreamLines, 3, simpleFull, noNewlinesChunks, true, {fd3: true}, execa);37-test('"lines: true" splits lines, stdout, sync', testStreamLines, 1, simpleFull, simpleLines, true, false, execaSync);38-test('"lines: true" splits lines, stdout, fd-specific, sync', testStreamLines, 1, simpleFull, simpleLines, {stdout: true}, false, execaSync);39-test('"lines: true" splits lines, stderr, sync', testStreamLines, 2, simpleFull, simpleLines, true, false, execaSync);40-test('"lines: true" splits lines, stderr, fd-specific, sync', testStreamLines, 2, simpleFull, simpleLines, {stderr: true}, false, execaSync);41-test('"lines: true" splits lines, stdio[*], sync', testStreamLines, 3, simpleFull, simpleLines, true, false, execaSync);42-test('"lines: true" splits lines, stdio[*], fd-specific, sync', testStreamLines, 3, simpleFull, simpleLines, {fd3: true}, false, execaSync);43-test('"lines: true" splits lines, stdout, stripFinalNewline, sync', testStreamLines, 1, simpleFull, noNewlinesChunks, true, true, execaSync);44-test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific, sync', testStreamLines, 1, simpleFull, noNewlinesChunks, true, {stdout: true}, execaSync);45-test('"lines: true" splits lines, stderr, stripFinalNewline, sync', testStreamLines, 2, simpleFull, noNewlinesChunks, true, true, execaSync);46-test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific, sync', testStreamLines, 2, simpleFull, noNewlinesChunks, true, {stderr: true}, execaSync);47-test('"lines: true" splits lines, stdio[*], stripFinalNewline, sync', testStreamLines, 3, simpleFull, noNewlinesChunks, true, true, execaSync);48-test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific, sync', testStreamLines, 3, simpleFull, noNewlinesChunks, true, {fd3: true}, execaSync);27+test('"lines: true" splits lines, stdout', () => testStreamLines(1, simpleFull, simpleLines, true, false, execa));28+test('"lines: true" splits lines, stdout, fd-specific', () => testStreamLines(1, simpleFull, simpleLines, {stdout: true}, false, execa));29+test('"lines: true" splits lines, stderr', () => testStreamLines(2, simpleFull, simpleLines, true, false, execa));30+test('"lines: true" splits lines, stderr, fd-specific', () => testStreamLines(2, simpleFull, simpleLines, {stderr: true}, false, execa));31+test('"lines: true" splits lines, stdio[*]', () => testStreamLines(3, simpleFull, simpleLines, true, false, execa));32+test('"lines: true" splits lines, stdio[*], fd-specific', () => testStreamLines(3, simpleFull, simpleLines, {fd3: true}, false, execa));33+test('"lines: true" splits lines, stdout, stripFinalNewline', () => testStreamLines(1, simpleFull, noNewlinesChunks, true, true, execa));34+test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific', () => testStreamLines(1, simpleFull, noNewlinesChunks, true, {stdout: true}, execa));35+test('"lines: true" splits lines, stderr, stripFinalNewline', () => testStreamLines(2, simpleFull, noNewlinesChunks, true, true, execa));36+test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific', () => testStreamLines(2, simpleFull, noNewlinesChunks, true, {stderr: true}, execa));37+test('"lines: true" splits lines, stdio[*], stripFinalNewline', () => testStreamLines(3, simpleFull, noNewlinesChunks, true, true, execa));38+test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific', () => testStreamLines(3, simpleFull, noNewlinesChunks, true, {fd3: true}, execa));39+test('"lines: true" splits lines, stdout, sync', () => testStreamLines(1, simpleFull, simpleLines, true, false, execaSync));40+test('"lines: true" splits lines, stdout, fd-specific, sync', () => testStreamLines(1, simpleFull, simpleLines, {stdout: true}, false, execaSync));41+test('"lines: true" splits lines, stderr, sync', () => testStreamLines(2, simpleFull, simpleLines, true, false, execaSync));42+test('"lines: true" splits lines, stderr, fd-specific, sync', () => testStreamLines(2, simpleFull, simpleLines, {stderr: true}, false, execaSync));43+test('"lines: true" splits lines, stdio[*], sync', () => testStreamLines(3, simpleFull, simpleLines, true, false, execaSync));44+test('"lines: true" splits lines, stdio[*], fd-specific, sync', () => testStreamLines(3, simpleFull, simpleLines, {fd3: true}, false, execaSync));45+test('"lines: true" splits lines, stdout, stripFinalNewline, sync', () => testStreamLines(1, simpleFull, noNewlinesChunks, true, true, execaSync));46+test('"lines: true" splits lines, stdout, stripFinalNewline, fd-specific, sync', () => testStreamLines(1, simpleFull, noNewlinesChunks, true, {stdout: true}, execaSync));47+test('"lines: true" splits lines, stderr, stripFinalNewline, sync', () => testStreamLines(2, simpleFull, noNewlinesChunks, true, true, execaSync));48+test('"lines: true" splits lines, stderr, stripFinalNewline, fd-specific, sync', () => testStreamLines(2, simpleFull, noNewlinesChunks, true, {stderr: true}, execaSync));49+test('"lines: true" splits lines, stdio[*], stripFinalNewline, sync', () => testStreamLines(3, simpleFull, noNewlinesChunks, true, true, execaSync));50+test('"lines: true" splits lines, stdio[*], stripFinalNewline, fd-specific, sync', () => testStreamLines(3, simpleFull, noNewlinesChunks, true, {fd3: true}, execaSync));51 52 const bigArray = Array.from({length: 1e5}).fill('.\n');53 const bigString = bigArray.join('');54 const bigStringNoNewlines = '.'.repeat(1e6);55 const bigStringNoNewlinesEnd = `${bigStringNoNewlines}\n`;56 57 // eslint-disable-next-line max-params56-const testStreamLinesGenerator = async (t, input, expectedLines, objectMode, binary, stripFinalNewline, execaMethod) => {58+const 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 };66 65-test('"lines: true" works with strings generators', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false, false, execa);66-test('"lines: true" works with strings generators, binary', testStreamLinesGenerator, simpleChunks, simpleLines, false, true, false, execa);67-test('"lines: true" works with big strings generators', testStreamLinesGenerator, [bigString], bigArray, false, false, false, execa);68-test('"lines: true" works with big strings generators without newlines', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execa);69-test('"lines: true" is a noop with strings generators, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, false, execa);70-test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, true, execa);71-test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execa);72-test('"lines: true" is a noop with strings generators, binary, objectMode', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true, false, execa);73-test('"lines: true" is a noop big strings generators, objectMode', testStreamLinesGenerator, [bigString], [bigString], true, false, false, execa);74-test('"lines: true" is a noop big strings generators without newlines, objectMode', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execa);75-test('"lines: true" works with strings generators, sync', testStreamLinesGenerator, simpleChunks, simpleFullEndLines, false, false, false, execaSync);76-test('"lines: true" works with strings generators, binary, sync', testStreamLinesGenerator, simpleChunks, simpleLines, false, true, false, execaSync);77-test('"lines: true" works with big strings generators, sync', testStreamLinesGenerator, [bigString], bigArray, false, false, false, execaSync);78-test('"lines: true" works with big strings generators without newlines, sync', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execaSync);79-test('"lines: true" is a noop with strings generators, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, false, execaSync);80-test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, true, execaSync);81-test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode, sync', testStreamLinesGenerator, simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execaSync);82-test('"lines: true" is a noop with strings generators, binary, objectMode, sync', testStreamLinesGenerator, simpleChunks, simpleChunks, true, true, false, execaSync);83-test('"lines: true" is a noop big strings generators, objectMode, sync', testStreamLinesGenerator, [bigString], [bigString], true, false, false, execaSync);84-test('"lines: true" is a noop big strings generators without newlines, objectMode, sync', testStreamLinesGenerator, [bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execaSync);67+test('"lines: true" works with strings generators', () => testStreamLinesGenerator(simpleChunks, simpleFullEndLines, false, false, false, execa));68+test('"lines: true" works with strings generators, binary', () => testStreamLinesGenerator(simpleChunks, simpleLines, false, true, false, execa));69+test('"lines: true" works with big strings generators', () => testStreamLinesGenerator([bigString], bigArray, false, false, false, execa));70+test('"lines: true" works with big strings generators without newlines', () => testStreamLinesGenerator([bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execa));71+test('"lines: true" is a noop with strings generators, objectMode', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, false, execa));72+test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, true, execa));73+test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execa));74+test('"lines: true" is a noop with strings generators, binary, objectMode', () => testStreamLinesGenerator(simpleChunks, simpleChunks, true, true, false, execa));75+test('"lines: true" is a noop big strings generators, objectMode', () => testStreamLinesGenerator([bigString], [bigString], true, false, false, execa));76+test('"lines: true" is a noop big strings generators without newlines, objectMode', () => testStreamLinesGenerator([bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execa));77+test('"lines: true" works with strings generators, sync', () => testStreamLinesGenerator(simpleChunks, simpleFullEndLines, false, false, false, execaSync));78+test('"lines: true" works with strings generators, binary, sync', () => testStreamLinesGenerator(simpleChunks, simpleLines, false, true, false, execaSync));79+test('"lines: true" works with big strings generators, sync', () => testStreamLinesGenerator([bigString], bigArray, false, false, false, execaSync));80+test('"lines: true" works with big strings generators without newlines, sync', () => testStreamLinesGenerator([bigStringNoNewlines], [bigStringNoNewlinesEnd], false, false, false, execaSync));81+test('"lines: true" is a noop with strings generators, objectMode, sync', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, false, execaSync));82+test('"lines: true" is a noop with strings generators, stripFinalNewline, objectMode, sync', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, true, execaSync));83+test('"lines: true" is a noop with strings generators, stripFinalNewline, fd-specific, objectMode, sync', () => testStreamLinesGenerator(simpleFullEndChunks, simpleFullEndChunks, true, false, {stdout: true}, execaSync));84+test('"lines: true" is a noop with strings generators, binary, objectMode, sync', () => testStreamLinesGenerator(simpleChunks, simpleChunks, true, true, false, execaSync));85+test('"lines: true" is a noop big strings generators, objectMode, sync', () => testStreamLinesGenerator([bigString], [bigString], true, false, false, execaSync));86+test('"lines: true" is a noop big strings generators without newlines, objectMode, sync', () => testStreamLinesGenerator([bigStringNoNewlines], [bigStringNoNewlines], true, false, false, execaSync));87 86-test('"lines: true" stops on stream error', async t => {88+test('"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 }95 96 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 });102 101-test('"lines: true" stops on stream error event', async t => {103+test('"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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows, assertRejects} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {simpleLines, noNewlinesChunks, getSimpleChunkSubprocessAsync} from '../helpers/lines.js';7 import {assertErrorMessage} from '../helpers/max-buffer.js';1 unmodified line9 setFixtureDirectory();10 11 const maxBuffer = simpleLines.length - 1;12 11-const testBelowMaxBuffer = async (t, lines) => {13+const 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 };18 17-test('"lines: true" can be below "maxBuffer"', testBelowMaxBuffer, true);18-test('"lines: true" can be below "maxBuffer", fd-specific', testBelowMaxBuffer, {stdout: true});19+test('"lines: true" can be below "maxBuffer"', () => testBelowMaxBuffer(true));20+test('"lines: true" can be below "maxBuffer", fd-specific', () => testBelowMaxBuffer({stdout: true}));21 20-const 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));22+const 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 };28 27-test('"lines: true" can be above "maxBuffer"', testAboveMaxBuffer, true);28-test('"lines: true" can be above "maxBuffer", fd-specific', testAboveMaxBuffer, {stdout: true});29+test('"lines: true" can be above "maxBuffer"', () => testAboveMaxBuffer(true));30+test('"lines: true" can be above "maxBuffer", fd-specific', () => testAboveMaxBuffer({stdout: true}));31 30-const 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, ['...', '...']);32+const 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 };38 37-test('"maxBuffer" is measured in lines with "lines: true"', testMaxBufferUnit, true);38-test('"maxBuffer" is measured in lines with "lines: true", fd-specific', testMaxBufferUnit, {stdout: true});39+test('"maxBuffer" is measured in lines with "lines: true"', () => testMaxBufferUnit(true));40+test('"maxBuffer" is measured in lines with "lines: true", fd-specific', () => testMaxBufferUnit({stdout: true}));41 40-const testMaxBufferUnitSync = (t, lines) => {41- const {isMaxBuffer, shortMessage, stdout} = t.throws(() => {42+const 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 };50 49-test('"maxBuffer" is measured in bytes with "lines: true", sync', testMaxBufferUnitSync, true);50-test('"maxBuffer" is measured in bytes with "lines: true", fd-specific, sync', testMaxBufferUnitSync, {stdout: true});51+test('"maxBuffer" is measured in bytes with "lines: true", sync', () => testMaxBufferUnitSync(true));52+test('"maxBuffer" is measured in bytes with "lines: true", fd-specific, sync', () => testMaxBufferUnitSync({stdout: true}));modified:test/stdio/lines-mixed.js+23 added-22 removed
1+import assert from 'node:assert/strict';2 import {Writable} from 'node:stream';2-import test from 'ava';3+import test from 'node:test';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {assertStreamOutput, assertStreamDataEvents, assertIterableChunks} from '../helpers/convert.js';6 import {7 simpleFull,3 unmodified lines11 } from '../helpers/lines.js';12 13 setFixtureDirectory();14 14-const testAsyncIteration = async (t, expectedLines, stripFinalNewline) => {15+const 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 };22 22-test('"lines: true" works with stream async iteration', testAsyncIteration, simpleLines, false);23-test('"lines: true" works with stream async iteration, stripFinalNewline', testAsyncIteration, noNewlinesChunks, true);23+test('"lines: true" works with stream async iteration', () => testAsyncIteration(simpleLines, false));24+test('"lines: true" works with stream async iteration, stripFinalNewline', () => testAsyncIteration(noNewlinesChunks, true));25 25-const testDataEvents = async (t, expectedLines, stripFinalNewline) => {26+const 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 };32 32-test('"lines: true" works with stream "data" events', testDataEvents, simpleLines, false);33-test('"lines: true" works with stream "data" events, stripFinalNewline', testDataEvents, noNewlinesChunks, true);33+test('"lines: true" works with stream "data" events', () => testDataEvents(simpleLines, false));34+test('"lines: true" works with stream "data" events, stripFinalNewline', () => testDataEvents(noNewlinesChunks, true));35 35-const testWritableStream = async (t, expectedLines, stripFinalNewline) => {36+const testWritableStream = async (expectedLines, stripFinalNewline) => {37 let output = '';38 const writable = new Writable({39 write(line, encoding, done) {40 output += line.toString();1 unmodified line42 },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 };49 49-test('"lines: true" works with writable streams targets', testWritableStream, simpleLines, false);50-test('"lines: true" works with writable streams targets, stripFinalNewline', testWritableStream, noNewlinesChunks, true);50+test('"lines: true" works with writable streams targets', () => testWritableStream(simpleLines, false));51+test('"lines: true" works with writable streams targets, stripFinalNewline', () => testWritableStream(noNewlinesChunks, true));52 52-const testIterable = async (t, expectedLines, stripFinalNewline) => {53+const 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 };59 59-test('"lines: true" works with subprocess.iterable()', testIterable, simpleLines, false);60-test('"lines: true" works with subprocess.iterable(), stripFinalNewline', testIterable, noNewlinesChunks, true);60+test('"lines: true" works with subprocess.iterable()', () => testIterable(simpleLines, false));61+test('"lines: true" works with subprocess.iterable(), stripFinalNewline', () => testIterable(noNewlinesChunks, true));modified:test/stdio/lines-noop.js+50 added-49 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {getOutputsGenerator} from '../helpers/generator.js';6 import {foobarObject} from '../helpers/input.js';8 unmodified lines15 } from '../helpers/lines.js';16 17 setFixtureDirectory();18 18-const testStreamLinesNoop = async (t, lines, execaMethod) => {19+const 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 };23 23-test('"lines: false" is a noop', testStreamLinesNoop, false, execa);24-test('"lines: false" is a noop, fd-specific', testStreamLinesNoop, {stderr: true}, execa);25-test('"lines: false" is a noop, fd-specific none', testStreamLinesNoop, {}, execa);26-test('"lines: false" is a noop, sync', testStreamLinesNoop, false, execaSync);27-test('"lines: false" is a noop, fd-specific, sync', testStreamLinesNoop, {stderr: true}, execaSync);28-test('"lines: false" is a noop, fd-specific none, sync', testStreamLinesNoop, {}, execaSync);24+test('"lines: false" is a noop', () => testStreamLinesNoop(false, execa));25+test('"lines: false" is a noop, fd-specific', () => testStreamLinesNoop({stderr: true}, execa));26+test('"lines: false" is a noop, fd-specific none', () => testStreamLinesNoop({}, execa));27+test('"lines: false" is a noop, sync', () => testStreamLinesNoop(false, execaSync));28+test('"lines: false" is a noop, fd-specific, sync', () => testStreamLinesNoop({stderr: true}, execaSync));29+test('"lines: false" is a noop, fd-specific none, sync', () => testStreamLinesNoop({}, execaSync));30 30-const testLinesObjectMode = async (t, lines, execaMethod) => {31+const 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 };38 38-test('"lines: true" is a noop with objects generators, objectMode', testLinesObjectMode, true, execa);39-test('"lines: true" is a noop with objects generators, fd-specific, objectMode', testLinesObjectMode, {stdout: true}, execa);40-test('"lines: true" is a noop with objects generators, objectMode, sync', testLinesObjectMode, true, execaSync);41-test('"lines: true" is a noop with objects generators, fd-specific, objectMode, sync', testLinesObjectMode, {stdout: true}, execaSync);39+test('"lines: true" is a noop with objects generators, objectMode', () => testLinesObjectMode(true, execa));40+test('"lines: true" is a noop with objects generators, fd-specific, objectMode', () => testLinesObjectMode({stdout: true}, execa));41+test('"lines: true" is a noop with objects generators, objectMode, sync', () => testLinesObjectMode(true, execaSync));42+test('"lines: true" is a noop with objects generators, fd-specific, objectMode, sync', () => testLinesObjectMode({stdout: true}, execaSync));43 44 // eslint-disable-next-line max-params44-const testEncoding = async (t, input, expectedOutput, encoding, lines, stripFinalNewline, execaMethod) => {45+const 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 };54 54-test('"lines: true" is a noop with "encoding: utf16"', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execa);55-test('"lines: true" is a noop with "encoding: utf16", fd-specific', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execa);56-test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execa);57-test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execa);58-test('"lines: true" is a noop with "encoding: buffer"', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execa);59-test('"lines: true" is a noop with "encoding: buffer", fd-specific', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execa);60-test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execa);61-test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execa);62-test('"lines: true" is a noop with "encoding: hex"', testEncoding, simpleFull, simpleFullHex, 'hex', true, false, execa);63-test('"lines: true" is a noop with "encoding: hex", fd-specific', testEncoding, simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execa);64-test('"lines: true" is a noop with "encoding: hex", stripFinalNewline', testEncoding, simpleFull, simpleFullHex, 'hex', true, true, execa);65-test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific', testEncoding, simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execa);66-test('"lines: true" is a noop with "encoding: utf16", sync', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execaSync);67-test('"lines: true" is a noop with "encoding: utf16", fd-specific, sync', testEncoding, simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execaSync);68-test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, sync', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execaSync);69-test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific, sync', testEncoding, simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execaSync);70-test('"lines: true" is a noop with "encoding: buffer", sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync);71-test('"lines: true" is a noop with "encoding: buffer", fd-specific, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execaSync);72-test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync);73-test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific, sync', testEncoding, simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execaSync);74-test('"lines: true" is a noop with "encoding: hex", sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, false, execaSync);75-test('"lines: true" is a noop with "encoding: hex", fd-specific, sync', testEncoding, simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execaSync);76-test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, true, execaSync);77-test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific, sync', testEncoding, simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execaSync);55+test('"lines: true" is a noop with "encoding: utf16"', () => testEncoding(simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execa));56+test('"lines: true" is a noop with "encoding: utf16", fd-specific', () => testEncoding(simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execa));57+test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline', () => testEncoding(simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execa));58+test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific', () => testEncoding(simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execa));59+test('"lines: true" is a noop with "encoding: buffer"', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, false, execa));60+test('"lines: true" is a noop with "encoding: buffer", fd-specific', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execa));61+test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, false, execa));62+test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execa));63+test('"lines: true" is a noop with "encoding: hex"', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, false, execa));64+test('"lines: true" is a noop with "encoding: hex", fd-specific', () => testEncoding(simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execa));65+test('"lines: true" is a noop with "encoding: hex", stripFinalNewline', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, true, execa));66+test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execa));67+test('"lines: true" is a noop with "encoding: utf16", sync', () => testEncoding(simpleFullUtf16Uint8Array, simpleLines, 'utf16le', true, false, execaSync));68+test('"lines: true" is a noop with "encoding: utf16", fd-specific, sync', () => testEncoding(simpleFullUtf16Uint8Array, simpleLines, 'utf16le', {stdout: true}, false, execaSync));69+test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, sync', () => testEncoding(simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, true, execaSync));70+test('"lines: true" is a noop with "encoding: utf16", stripFinalNewline, fd-specific, sync', () => testEncoding(simpleFullUtf16Uint8Array, noNewlinesChunks, 'utf16le', true, {stdout: true}, execaSync));71+test('"lines: true" is a noop with "encoding: buffer", sync', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync));72+test('"lines: true" is a noop with "encoding: buffer", fd-specific, sync', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', {stdout: true}, false, execaSync));73+test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, sync', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, false, execaSync));74+test('"lines: true" is a noop with "encoding: buffer", stripFinalNewline, fd-specific, sync', () => testEncoding(simpleFull, simpleFullUint8Array, 'buffer', true, {stdout: false}, execaSync));75+test('"lines: true" is a noop with "encoding: hex", sync', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, false, execaSync));76+test('"lines: true" is a noop with "encoding: hex", fd-specific, sync', () => testEncoding(simpleFull, simpleFullHex, 'hex', {stdout: true}, false, execaSync));77+test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, sync', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, true, execaSync));78+test('"lines: true" is a noop with "encoding: hex", stripFinalNewline, fd-specific, sync', () => testEncoding(simpleFull, simpleFullHex, 'hex', true, {stdout: true}, execaSync));79 79-const testLinesNoBuffer = async (t, lines, buffer, execaMethod) => {80+const testLinesNoBuffer = async (lines, buffer, execaMethod) => {81 const {stdout} = await getSimpleChunkSubprocess(execaMethod, {lines, buffer});81- t.is(stdout, undefined);82+ assert.equal(stdout, undefined);83 };84 84-test('"lines: true" is a noop with "buffer: false"', testLinesNoBuffer, true, false, execa);85-test('"lines: true" is a noop with "buffer: false", fd-specific buffer', testLinesNoBuffer, true, {stdout: false}, execa);86-test('"lines: true" is a noop with "buffer: false", fd-specific lines', testLinesNoBuffer, {stdout: true}, false, execa);87-test('"lines: true" is a noop with "buffer: false", sync', testLinesNoBuffer, true, false, execaSync);88-test('"lines: true" is a noop with "buffer: false", fd-specific buffer, sync', testLinesNoBuffer, true, {stdout: false}, execaSync);89-test('"lines: true" is a noop with "buffer: false", fd-specific lines, sync', testLinesNoBuffer, {stdout: true}, false, execaSync);85+test('"lines: true" is a noop with "buffer: false"', () => testLinesNoBuffer(true, false, execa));86+test('"lines: true" is a noop with "buffer: false", fd-specific buffer', () => testLinesNoBuffer(true, {stdout: false}, execa));87+test('"lines: true" is a noop with "buffer: false", fd-specific lines', () => testLinesNoBuffer({stdout: true}, false, execa));88+test('"lines: true" is a noop with "buffer: false", sync', () => testLinesNoBuffer(true, false, execaSync));89+test('"lines: true" is a noop with "buffer: false", fd-specific buffer, sync', () => testLinesNoBuffer(true, {stdout: false}, execaSync));90+test('"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
1+import assert from 'node:assert/strict';2 import {platform} from 'node:process';2-import test from 'ava';3+import test from 'node:test';4+import {assertThrows} from '../helpers/assert.js';5 import {execa, execaSync} from '../../index.js';6 import {getStdio, fullStdio} from '../helpers/stdio.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {foobarString} from '../helpers/input.js';1 unmodified line10 11 setFixtureDirectory();12 13 const isLinux = platform === 'linux';12-const isWindows = platform === 'win32';14 14-const testFd3InheritOutput = async (t, stdioOption, isSync) => {15+const 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 };19 19-test('stdio[*] output can use "inherit"', testFd3InheritOutput, 'inherit', false);20-test('stdio[*] output can use ["inherit"]', testFd3InheritOutput, ['inherit'], false);21-test('stdio[*] output can use "inherit", sync', testFd3InheritOutput, 'inherit', true);22-test('stdio[*] output can use ["inherit"], sync', testFd3InheritOutput, ['inherit'], true);20+test('stdio[*] output can use "inherit"', () => testFd3InheritOutput('inherit', false));21+test('stdio[*] output can use ["inherit"]', () => testFd3InheritOutput(['inherit'], false));22+test('stdio[*] output can use "inherit", sync', () => testFd3InheritOutput('inherit', true));23+test('stdio[*] output can use ["inherit"], sync', () => testFd3InheritOutput(['inherit'], true));24 25 if (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 };30 30- 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 }48 48-const testOverflowStreamArray = (t, fdNumber, stdioOption) => {49- t.throws(() => {49+const testOverflowStreamArray = (fdNumber, stdioOption) => {50+ assertThrows(() => {51 execa('empty.js', getStdio(fdNumber, stdioOption));52 }, {message: /no such standard stream/});53 };54 54-test('stdin cannot use 4+ and another value', testOverflowStreamArray, 0, [4, 'pipe']);55-test('stdout cannot use 4+ and another value', testOverflowStreamArray, 1, [4, 'pipe']);56-test('stderr cannot use 4+ and another value', testOverflowStreamArray, 2, [4, 'pipe']);57-test('stdio[*] cannot use 4+ and another value', testOverflowStreamArray, 3, [4, 'pipe']);58-test('stdio[*] cannot use "inherit" and another value', testOverflowStreamArray, 3, ['inherit', 'pipe']);55+test('stdin cannot use 4+ and another value', () => testOverflowStreamArray(0, [4, 'pipe']));56+test('stdout cannot use 4+ and another value', () => testOverflowStreamArray(1, [4, 'pipe']));57+test('stderr cannot use 4+ and another value', () => testOverflowStreamArray(2, [4, 'pipe']));58+test('stdio[*] cannot use 4+ and another value', () => testOverflowStreamArray(3, [4, 'pipe']));59+test('stdio[*] cannot use "inherit" and another value', () => testOverflowStreamArray(3, ['inherit', 'pipe']));60 60-const 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.63+const closedFdNumber = 1000;64 65- return isWindows ? 'EBADF' : 'ENXIO';65+const testOverflowStreamArraySync = fdNumber => {66+ assertThrows(() => {67+ execaSync('noop-fd.js', [fdNumber, foobarString], getStdio(fdNumber, [closedFdNumber, 'pipe']));68+ }, {code: 'EBADF'});69 };70 68-const testOverflowStreamArraySync = (t, fdNumber) => {69- t.throws(() => {70- execaSync('noop-fd.js', [fdNumber, foobarString], getStdio(fdNumber, [4, 'pipe']));71- }, {code: getInvalidFdCode()});72-};71+test('stdout cannot use 4+ and another value, sync', () => testOverflowStreamArraySync(1));72+test('stderr cannot use 4+ and another value, sync', () => testOverflowStreamArraySync(2));73+test('stdio[*] cannot use 4+ and another value, sync', () => testOverflowStreamArraySync(3));74 74-test('stdout cannot use 4+ and another value, sync', testOverflowStreamArraySync, 1);75-test('stderr cannot use 4+ and another value, sync', testOverflowStreamArraySync, 2);76-test('stdio[*] cannot use 4+ and another value, sync', testOverflowStreamArraySync, 3);77-75 // `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.81-const testSameTargetOutput = async (t, stdioOption, isSync) => {78+const 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 };82 86-test('stdout output is not duplicated with [1, "inherit"]', testSameTargetOutput, [1, 'inherit'], false);87-test('stdout output is not duplicated with ["inherit", 1]', testSameTargetOutput, ['inherit', 1], false);88-test('stdout output is not duplicated with [1, "inherit"], sync', testSameTargetOutput, [1, 'inherit'], true);89-test('stdout output is not duplicated with ["inherit", 1], sync', testSameTargetOutput, ['inherit', 1], true);83+test('stdout output is not duplicated with [1, "inherit"]', () => testSameTargetOutput([1, 'inherit'], false));84+test('stdout output is not duplicated with ["inherit", 1]', () => testSameTargetOutput(['inherit', 1], false));85+test('stdout output is not duplicated with [1, "inherit"], sync', () => testSameTargetOutput([1, 'inherit'], true));86+test('stdout output is not duplicated with ["inherit", 1], sync', () => testSameTargetOutput(['inherit', 1], true));modified:test/stdio/native-inherit-pipe.js+62 added-60 removed
1+import assert from 'node:assert/strict';2 import {readFile, rm} from 'node:fs/promises';2-import test from 'ava';3+import test from 'node:test';4 import tempfile from 'tempfile';5+import {assertRejects} from '../helpers/assert.js';6 import {execa} from '../../index.js';7 import {getStdio, fullStdio} from '../helpers/stdio.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 import {foobarString} from '../helpers/input.js';10 import {nestedSubprocess} from '../helpers/nested.js';11 12 setFixtureDirectory();13 12-const testInheritStdin = async (t, stdioOption, isSync) => {14+const 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 };18 17-test('stdin can be ["inherit", "pipe"]', testInheritStdin, ['inherit', 'pipe'], false);18-test('stdin can be [0, "pipe"]', testInheritStdin, [0, 'pipe'], false);19-test('stdin can be [process.stdin, "pipe"]', testInheritStdin, ['stdin', 'pipe'], false);20-test.serial('stdin can be ["inherit", "pipe"], sync', testInheritStdin, ['inherit', 'pipe'], true);21-test.serial('stdin can be [0, "pipe"], sync', testInheritStdin, [0, 'pipe'], true);22-test.serial('stdin can be [process.stdin, "pipe"], sync', testInheritStdin, ['stdin', 'pipe'], true);19+test('stdin can be ["inherit", "pipe"]', () => testInheritStdin(['inherit', 'pipe'], false));20+test('stdin can be [0, "pipe"]', () => testInheritStdin([0, 'pipe'], false));21+test('stdin can be [process.stdin, "pipe"]', () => testInheritStdin(['stdin', 'pipe'], false));22+test('stdin can be ["inherit", "pipe"], sync', () => testInheritStdin(['inherit', 'pipe'], true));23+test('stdin can be [0, "pipe"], sync', () => testInheritStdin([0, 'pipe'], true));24+test('stdin can be [process.stdin, "pipe"], sync', () => testInheritStdin(['stdin', 'pipe'], true));25 26 // eslint-disable-next-line max-params25-const testInheritStdioOutput = async (t, fdNumber, outerFdNumber, stdioOption, isSync, encoding) => {27+const 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 };32 31-test('stdout can be ["inherit", "pipe"]', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], false, 'utf8');32-test('stdout can be [1, "pipe"]', testInheritStdioOutput, 1, 2, [1, 'pipe'], false, 'utf8');33-test('stdout can be [process.stdout, "pipe"]', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], false, 'utf8');34-test('stderr can be ["inherit", "pipe"]', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], false, 'utf8');35-test('stderr can be [2, "pipe"]', testInheritStdioOutput, 2, 1, [2, 'pipe'], false, 'utf8');36-test('stderr can be [process.stderr, "pipe"]', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], false, 'utf8');37-test('stdout can be ["inherit", "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], false, 'buffer');38-test('stdout can be [1, "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, [1, 'pipe'], false, 'buffer');39-test('stdout can be [process.stdout, "pipe"], encoding "buffer"', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], false, 'buffer');40-test('stderr can be ["inherit", "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], false, 'buffer');41-test('stderr can be [2, "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, [2, 'pipe'], false, 'buffer');42-test('stderr can be [process.stderr, "pipe"], encoding "buffer"', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], false, 'buffer');43-test('stdout can be ["inherit", "pipe"], sync', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], true, 'utf8');44-test('stdout can be [1, "pipe"], sync', testInheritStdioOutput, 1, 2, [1, 'pipe'], true, 'utf8');45-test('stdout can be [process.stdout, "pipe"], sync', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], true, 'utf8');46-test('stderr can be ["inherit", "pipe"], sync', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], true, 'utf8');47-test('stderr can be [2, "pipe"], sync', testInheritStdioOutput, 2, 1, [2, 'pipe'], true, 'utf8');48-test('stderr can be [process.stderr, "pipe"], sync', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], true, 'utf8');49-test('stdio[*] output can be ["inherit", "pipe"], sync', testInheritStdioOutput, 3, 1, ['inherit', 'pipe'], true, 'utf8');50-test('stdio[*] output can be [3, "pipe"], sync', testInheritStdioOutput, 3, 1, [3, 'pipe'], true, 'utf8');51-test('stdout can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, ['inherit', 'pipe'], true, 'buffer');52-test('stdout can be [1, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, [1, 'pipe'], true, 'buffer');53-test('stdout can be [process.stdout, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 1, 2, ['stdout', 'pipe'], true, 'buffer');54-test('stderr can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, ['inherit', 'pipe'], true, 'buffer');55-test('stderr can be [2, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, [2, 'pipe'], true, 'buffer');56-test('stderr can be [process.stderr, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 2, 1, ['stderr', 'pipe'], true, 'buffer');57-test('stdio[*] output can be ["inherit", "pipe"], encoding "buffer", sync', testInheritStdioOutput, 3, 1, ['inherit', 'pipe'], true, 'buffer');58-test('stdio[*] output can be [3, "pipe"], encoding "buffer", sync', testInheritStdioOutput, 3, 1, [3, 'pipe'], true, 'buffer');33+test('stdout can be ["inherit", "pipe"]', () => testInheritStdioOutput(1, 2, ['inherit', 'pipe'], false, 'utf8'));34+test('stdout can be [1, "pipe"]', () => testInheritStdioOutput(1, 2, [1, 'pipe'], false, 'utf8'));35+test('stdout can be [process.stdout, "pipe"]', () => testInheritStdioOutput(1, 2, ['stdout', 'pipe'], false, 'utf8'));36+test('stderr can be ["inherit", "pipe"]', () => testInheritStdioOutput(2, 1, ['inherit', 'pipe'], false, 'utf8'));37+test('stderr can be [2, "pipe"]', () => testInheritStdioOutput(2, 1, [2, 'pipe'], false, 'utf8'));38+test('stderr can be [process.stderr, "pipe"]', () => testInheritStdioOutput(2, 1, ['stderr', 'pipe'], false, 'utf8'));39+test('stdout can be ["inherit", "pipe"], encoding "buffer"', () => testInheritStdioOutput(1, 2, ['inherit', 'pipe'], false, 'buffer'));40+test('stdout can be [1, "pipe"], encoding "buffer"', () => testInheritStdioOutput(1, 2, [1, 'pipe'], false, 'buffer'));41+test('stdout can be [process.stdout, "pipe"], encoding "buffer"', () => testInheritStdioOutput(1, 2, ['stdout', 'pipe'], false, 'buffer'));42+test('stderr can be ["inherit", "pipe"], encoding "buffer"', () => testInheritStdioOutput(2, 1, ['inherit', 'pipe'], false, 'buffer'));43+test('stderr can be [2, "pipe"], encoding "buffer"', () => testInheritStdioOutput(2, 1, [2, 'pipe'], false, 'buffer'));44+test('stderr can be [process.stderr, "pipe"], encoding "buffer"', () => testInheritStdioOutput(2, 1, ['stderr', 'pipe'], false, 'buffer'));45+test('stdout can be ["inherit", "pipe"], sync', () => testInheritStdioOutput(1, 2, ['inherit', 'pipe'], true, 'utf8'));46+test('stdout can be [1, "pipe"], sync', () => testInheritStdioOutput(1, 2, [1, 'pipe'], true, 'utf8'));47+test('stdout can be [process.stdout, "pipe"], sync', () => testInheritStdioOutput(1, 2, ['stdout', 'pipe'], true, 'utf8'));48+test('stderr can be ["inherit", "pipe"], sync', () => testInheritStdioOutput(2, 1, ['inherit', 'pipe'], true, 'utf8'));49+test('stderr can be [2, "pipe"], sync', () => testInheritStdioOutput(2, 1, [2, 'pipe'], true, 'utf8'));50+test('stderr can be [process.stderr, "pipe"], sync', () => testInheritStdioOutput(2, 1, ['stderr', 'pipe'], true, 'utf8'));51+test('stdio[*] output can be ["inherit", "pipe"], sync', () => testInheritStdioOutput(3, 1, ['inherit', 'pipe'], true, 'utf8'));52+test('stdio[*] output can be [3, "pipe"], sync', () => testInheritStdioOutput(3, 1, [3, 'pipe'], true, 'utf8'));53+test('stdout can be ["inherit", "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(1, 2, ['inherit', 'pipe'], true, 'buffer'));54+test('stdout can be [1, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(1, 2, [1, 'pipe'], true, 'buffer'));55+test('stdout can be [process.stdout, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(1, 2, ['stdout', 'pipe'], true, 'buffer'));56+test('stderr can be ["inherit", "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(2, 1, ['inherit', 'pipe'], true, 'buffer'));57+test('stderr can be [2, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(2, 1, [2, 'pipe'], true, 'buffer'));58+test('stderr can be [process.stderr, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(2, 1, ['stderr', 'pipe'], true, 'buffer'));59+test('stdio[*] output can be ["inherit", "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(3, 1, ['inherit', 'pipe'], true, 'buffer'));60+test('stdio[*] output can be [3, "pipe"], encoding "buffer", sync', () => testInheritStdioOutput(3, 1, [3, 'pipe'], true, 'buffer'));61 60-const testInheritNoBuffer = async (t, stdioOption, isSync) => {62+const 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 };68 67-test('stdin can be ["inherit", "pipe"], buffer: false', testInheritNoBuffer, ['inherit', 'pipe'], false);68-test('stdin can be [0, "pipe"], buffer: false', testInheritNoBuffer, [0, 'pipe'], false);69-test.serial('stdin can be ["inherit", "pipe"], buffer: false, sync', testInheritNoBuffer, ['inherit', 'pipe'], true);70-test.serial('stdin can be [0, "pipe"], buffer: false, sync', testInheritNoBuffer, [0, 'pipe'], true);69+test('stdin can be ["inherit", "pipe"], buffer: false', () => testInheritNoBuffer(['inherit', 'pipe'], false));70+test('stdin can be [0, "pipe"], buffer: false', () => testInheritNoBuffer([0, 'pipe'], false));71+test('stdin can be ["inherit", "pipe"], buffer: false, sync', () => testInheritNoBuffer(['inherit', 'pipe'], true));72+test('stdin can be [0, "pipe"], buffer: false, sync', () => testInheritNoBuffer([0, 'pipe'], true));73 72-test('stdin can use ["inherit", "pipe"] in a TTY', async t => {74+test('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 });79 78-const testNoTtyInput = async (t, fdNumber, optionName) => {80+const 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 };86 85-test('stdin cannot use ["inherit", "pipe"] in a TTY, sync', testNoTtyInput, 0, 'stdin');86-test('stdio[*] input cannot use ["inherit", "pipe"] in a TTY, sync', testNoTtyInput, 3, 'stdio[3]');87+test('stdin cannot use ["inherit", "pipe"] in a TTY, sync', () => testNoTtyInput(0, 'stdin'));88+test('stdio[*] input cannot use ["inherit", "pipe"] in a TTY, sync', () => testNoTtyInput(3, 'stdio[3]'));89 88-const testTtyOutput = async (t, fdNumber, isSync) => {90+const 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 };94 93-test('stdout can use ["inherit", "pipe"] in a TTY', testTtyOutput, 1, false);94-test('stderr can use ["inherit", "pipe"] in a TTY', testTtyOutput, 2, false);95-test('stdout can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 1, true);96-test('stderr can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 2, true);97-test('stdio[*] output can use ["inherit", "pipe"] in a TTY, sync', testTtyOutput, 3, true);95+test('stdout can use ["inherit", "pipe"] in a TTY', () => testTtyOutput(1, false));96+test('stderr can use ["inherit", "pipe"] in a TTY', () => testTtyOutput(2, false));97+test('stdout can use ["inherit", "pipe"] in a TTY, sync', () => testTtyOutput(1, true));98+test('stderr can use ["inherit", "pipe"] in a TTY, sync', () => testTtyOutput(2, true));99+test('stdio[*] output can use ["inherit", "pipe"] in a TTY, sync', () => testTtyOutput(3, true));modified:test/stdio/native-redirect.js+58 added-58 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {foobarString} from '../helpers/input.js';6 7 setFixtureDirectory();8 8-// eslint-disable-next-line max-params9-const testRedirect = async (t, stdioOption, fdNumber, isInput, isSync) => {9+const 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 };17 18 const isStderrDescriptor = stdioOption => stdioOption === 219 || stdioOption === 'stderr'20 || (Array.isArray(stdioOption) && isStderrDescriptor(stdioOption[0]));21 22-test.serial('stdio[*] can be 0', testRedirect, 0, 3, true, false);23-test.serial('stdio[*] can be [0]', testRedirect, [0], 3, true, false);24-test.serial('stdio[*] can be [0, "pipe"]', testRedirect, [0, 'pipe'], 3, true, false);25-test.serial('stdio[*] can be process.stdin', testRedirect, 'stdin', 3, true, false);26-test.serial('stdio[*] can be [process.stdin]', testRedirect, ['stdin'], 3, true, false);27-test.serial('stdio[*] can be [process.stdin, "pipe"]', testRedirect, ['stdin', 'pipe'], 3, true, false);28-test('stdout can be 2', testRedirect, 2, 1, false, false);29-test('stdout can be [2]', testRedirect, [2], 1, false, false);30-test('stdout can be [2, "pipe"]', testRedirect, [2, 'pipe'], 1, false, false);31-test('stdout can be process.stderr', testRedirect, 'stderr', 1, false, false);32-test('stdout can be [process.stderr]', testRedirect, ['stderr'], 1, false, false);33-test('stdout can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 1, false, false);34-test('stderr can be 1', testRedirect, 1, 2, false, false);35-test('stderr can be [1]', testRedirect, [1], 2, false, false);36-test('stderr can be [1, "pipe"]', testRedirect, [1, 'pipe'], 2, false, false);37-test('stderr can be process.stdout', testRedirect, 'stdout', 2, false, false);38-test('stderr can be [process.stdout]', testRedirect, ['stdout'], 2, false, false);39-test('stderr can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 2, false, false);40-test('stdio[*] can be 1', testRedirect, 1, 3, false, false);41-test('stdio[*] can be [1]', testRedirect, [1], 3, false, false);42-test('stdio[*] can be [1, "pipe"]', testRedirect, [1, 'pipe'], 3, false, false);43-test('stdio[*] can be 2', testRedirect, 2, 3, false, false);44-test('stdio[*] can be [2]', testRedirect, [2], 3, false, false);45-test('stdio[*] can be [2, "pipe"]', testRedirect, [2, 'pipe'], 3, false, false);46-test('stdio[*] can be process.stdout', testRedirect, 'stdout', 3, false, false);47-test('stdio[*] can be [process.stdout]', testRedirect, ['stdout'], 3, false, false);48-test('stdio[*] can be [process.stdout, "pipe"]', testRedirect, ['stdout', 'pipe'], 3, false, false);49-test('stdio[*] can be process.stderr', testRedirect, 'stderr', 3, false, false);50-test('stdio[*] can be [process.stderr]', testRedirect, ['stderr'], 3, false, false);51-test('stdio[*] can be [process.stderr, "pipe"]', testRedirect, ['stderr', 'pipe'], 3, false, false);52-test('stdout can be 2, sync', testRedirect, 2, 1, false, true);53-test('stdout can be [2], sync', testRedirect, [2], 1, false, true);54-test('stdout can be [2, "pipe"], sync', testRedirect, [2, 'pipe'], 1, false, true);55-test('stdout can be process.stderr, sync', testRedirect, 'stderr', 1, false, true);56-test('stdout can be [process.stderr], sync', testRedirect, ['stderr'], 1, false, true);57-test('stdout can be [process.stderr, "pipe"], sync', testRedirect, ['stderr', 'pipe'], 1, false, true);58-test('stderr can be 1, sync', testRedirect, 1, 2, false, true);59-test('stderr can be [1], sync', testRedirect, [1], 2, false, true);60-test('stderr can be [1, "pipe"], sync', testRedirect, [1, 'pipe'], 2, false, true);61-test('stderr can be process.stdout, sync', testRedirect, 'stdout', 2, false, true);62-test('stderr can be [process.stdout], sync', testRedirect, ['stdout'], 2, false, true);63-test('stderr can be [process.stdout, "pipe"], sync', testRedirect, ['stdout', 'pipe'], 2, false, true);64-test('stdio[*] can be 1, sync', testRedirect, 1, 3, false, true);65-test('stdio[*] can be [1], sync', testRedirect, [1], 3, false, true);66-test('stdio[*] can be [1, "pipe"], sync', testRedirect, [1, 'pipe'], 3, false, true);67-test('stdio[*] can be 2, sync', testRedirect, 2, 3, false, true);68-test('stdio[*] can be [2], sync', testRedirect, [2], 3, false, true);69-test('stdio[*] can be [2, "pipe"], sync', testRedirect, [2, 'pipe'], 3, false, true);70-test('stdio[*] can be process.stdout, sync', testRedirect, 'stdout', 3, false, true);71-test('stdio[*] can be [process.stdout], sync', testRedirect, ['stdout'], 3, false, true);72-test('stdio[*] can be [process.stdout, "pipe"], sync', testRedirect, ['stdout', 'pipe'], 3, false, true);73-test('stdio[*] can be process.stderr, sync', testRedirect, 'stderr', 3, false, true);74-test('stdio[*] can be [process.stderr], sync', testRedirect, ['stderr'], 3, false, true);75-test('stdio[*] can be [process.stderr, "pipe"], sync', testRedirect, ['stderr', 'pipe'], 3, false, true);22+test('stdio[*] can be 0', () => testRedirect(0, 3, true, false));23+test('stdio[*] can be [0]', () => testRedirect([0], 3, true, false));24+test('stdio[*] can be [0, "pipe"]', () => testRedirect([0, 'pipe'], 3, true, false));25+test('stdio[*] can be process.stdin', () => testRedirect('stdin', 3, true, false));26+test('stdio[*] can be [process.stdin]', () => testRedirect(['stdin'], 3, true, false));27+test('stdio[*] can be [process.stdin, "pipe"]', () => testRedirect(['stdin', 'pipe'], 3, true, false));28+test('stdout can be 2', () => testRedirect(2, 1, false, false));29+test('stdout can be [2]', () => testRedirect([2], 1, false, false));30+test('stdout can be [2, "pipe"]', () => testRedirect([2, 'pipe'], 1, false, false));31+test('stdout can be process.stderr', () => testRedirect('stderr', 1, false, false));32+test('stdout can be [process.stderr]', () => testRedirect(['stderr'], 1, false, false));33+test('stdout can be [process.stderr, "pipe"]', () => testRedirect(['stderr', 'pipe'], 1, false, false));34+test('stderr can be 1', () => testRedirect(1, 2, false, false));35+test('stderr can be [1]', () => testRedirect([1], 2, false, false));36+test('stderr can be [1, "pipe"]', () => testRedirect([1, 'pipe'], 2, false, false));37+test('stderr can be process.stdout', () => testRedirect('stdout', 2, false, false));38+test('stderr can be [process.stdout]', () => testRedirect(['stdout'], 2, false, false));39+test('stderr can be [process.stdout, "pipe"]', () => testRedirect(['stdout', 'pipe'], 2, false, false));40+test('stdio[*] can be 1', () => testRedirect(1, 3, false, false));41+test('stdio[*] can be [1]', () => testRedirect([1], 3, false, false));42+test('stdio[*] can be [1, "pipe"]', () => testRedirect([1, 'pipe'], 3, false, false));43+test('stdio[*] can be 2', () => testRedirect(2, 3, false, false));44+test('stdio[*] can be [2]', () => testRedirect([2], 3, false, false));45+test('stdio[*] can be [2, "pipe"]', () => testRedirect([2, 'pipe'], 3, false, false));46+test('stdio[*] can be process.stdout', () => testRedirect('stdout', 3, false, false));47+test('stdio[*] can be [process.stdout]', () => testRedirect(['stdout'], 3, false, false));48+test('stdio[*] can be [process.stdout, "pipe"]', () => testRedirect(['stdout', 'pipe'], 3, false, false));49+test('stdio[*] can be process.stderr', () => testRedirect('stderr', 3, false, false));50+test('stdio[*] can be [process.stderr]', () => testRedirect(['stderr'], 3, false, false));51+test('stdio[*] can be [process.stderr, "pipe"]', () => testRedirect(['stderr', 'pipe'], 3, false, false));52+test('stdout can be 2, sync', () => testRedirect(2, 1, false, true));53+test('stdout can be [2], sync', () => testRedirect([2], 1, false, true));54+test('stdout can be [2, "pipe"], sync', () => testRedirect([2, 'pipe'], 1, false, true));55+test('stdout can be process.stderr, sync', () => testRedirect('stderr', 1, false, true));56+test('stdout can be [process.stderr], sync', () => testRedirect(['stderr'], 1, false, true));57+test('stdout can be [process.stderr, "pipe"], sync', () => testRedirect(['stderr', 'pipe'], 1, false, true));58+test('stderr can be 1, sync', () => testRedirect(1, 2, false, true));59+test('stderr can be [1], sync', () => testRedirect([1], 2, false, true));60+test('stderr can be [1, "pipe"], sync', () => testRedirect([1, 'pipe'], 2, false, true));61+test('stderr can be process.stdout, sync', () => testRedirect('stdout', 2, false, true));62+test('stderr can be [process.stdout], sync', () => testRedirect(['stdout'], 2, false, true));63+test('stderr can be [process.stdout, "pipe"], sync', () => testRedirect(['stdout', 'pipe'], 2, false, true));64+test('stdio[*] can be 1, sync', () => testRedirect(1, 3, false, true));65+test('stdio[*] can be [1], sync', () => testRedirect([1], 3, false, true));66+test('stdio[*] can be [1, "pipe"], sync', () => testRedirect([1, 'pipe'], 3, false, true));67+test('stdio[*] can be 2, sync', () => testRedirect(2, 3, false, true));68+test('stdio[*] can be [2], sync', () => testRedirect([2], 3, false, true));69+test('stdio[*] can be [2, "pipe"], sync', () => testRedirect([2, 'pipe'], 3, false, true));70+test('stdio[*] can be process.stdout, sync', () => testRedirect('stdout', 3, false, true));71+test('stdio[*] can be [process.stdout], sync', () => testRedirect(['stdout'], 3, false, true));72+test('stdio[*] can be [process.stdout, "pipe"], sync', () => testRedirect(['stdout', 'pipe'], 3, false, true));73+test('stdio[*] can be process.stderr, sync', () => testRedirect('stderr', 3, false, true));74+test('stdio[*] can be [process.stderr], sync', () => testRedirect(['stderr'], 3, false, true));75+test('stdio[*] can be [process.stderr, "pipe"], sync', () => testRedirect(['stderr', 'pipe'], 3, false, true));modified:test/stdio/node-stream-custom.js+70 added-68 removed
1+import assert from 'node:assert/strict';2 import {createReadStream, createWriteStream} from 'node:fs';3 import {readFile, writeFile, rm} from 'node:fs/promises';4 import {Writable, PassThrough} from 'node:stream';5 import {text} from 'node:stream/consumers';6 import {setImmediate} from 'node:timers/promises';7 import {callbackify} from 'node:util';7-import test from 'ava';8+import test from 'node:test';9 import tempfile from 'tempfile';10+import {assertThrows, assertRejects, assertLike} from '../helpers/assert.js';11 import {execa, execaSync} from '../../index.js';12 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';13 import {getStdio} from '../helpers/stdio.js';14 import {foobarString} from '../helpers/input.js';1 unmodified line16 import {getEarlyErrorSubprocess, expectedEarlyError} from '../helpers/early-error.js';17 18 setFixtureDirectory();19 18-const testLazyFileReadable = async (t, fdNumber) => {20+const testLazyFileReadable = async fdNumber => {21 const filePath = tempfile();22 await writeFile(filePath, 'foobar');23 const stream = createReadStream(filePath);24 25 const {stdout} = await execa('stdin-fd.js', [`${fdNumber}`], getStdio(fdNumber, [stream, 'pipe']));24- t.is(stdout, 'foobar');26+ assert.equal(stdout, 'foobar');27 28 await rm(filePath);29 };30 29-test('stdin can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 0);30-test('stdio[*] can be [Readable, "pipe"] without a file descriptor', testLazyFileReadable, 3);31+test('stdin can be [Readable, "pipe"] without a file descriptor', () => testLazyFileReadable(0));32+test('stdio[*] can be [Readable, "pipe"] without a file descriptor', () => testLazyFileReadable(3));33 32-const testLazyFileReadableSync = (t, fdNumber) => {33- t.throws(() => {34+const 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 };39 38-test('stdin cannot be [Readable, "pipe"] without a file descriptor, sync', testLazyFileReadableSync, 0);39-test('stdio[*] cannot be [Readable, "pipe"] without a file descriptor, sync', testLazyFileReadableSync, 3);40+test('stdin cannot be [Readable, "pipe"] without a file descriptor, sync', () => testLazyFileReadableSync(0));41+test('stdio[*] cannot be [Readable, "pipe"] without a file descriptor, sync', () => testLazyFileReadableSync(3));42 41-const testLazyFileWritable = async (t, fdNumber) => {43+const testLazyFileWritable = async fdNumber => {44 const filePath = tempfile();45 const stream = createWriteStream(filePath);46 47 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');49 50 await rm(filePath);51 };52 51-test('stdout can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 1);52-test('stderr can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 2);53-test('stdio[*] can be [Writable, "pipe"] without a file descriptor', testLazyFileWritable, 3);53+test('stdout can be [Writable, "pipe"] without a file descriptor', () => testLazyFileWritable(1));54+test('stderr can be [Writable, "pipe"] without a file descriptor', () => testLazyFileWritable(2));55+test('stdio[*] can be [Writable, "pipe"] without a file descriptor', () => testLazyFileWritable(3));56 55-const testLazyFileWritableSync = (t, fdNumber) => {56- t.throws(() => {57+const 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 };62 61-test('stdout cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 1);62-test('stderr cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 2);63-test('stdio[*] cannot be [Writable, "pipe"] without a file descriptor, sync', testLazyFileWritableSync, 3);63+test('stdout cannot be [Writable, "pipe"] without a file descriptor, sync', () => testLazyFileWritableSync(1));64+test('stderr cannot be [Writable, "pipe"] without a file descriptor, sync', () => testLazyFileWritableSync(2));65+test('stdio[*] cannot be [Writable, "pipe"] without a file descriptor, sync', () => testLazyFileWritableSync(3));66 67 /*68 An output stream is written to, then handed back to the user.69 We must only wait for our writes to be flushed, not for the user to consume its readable side,70 otherwise the subprocess promise hangs until they do.71 */70-const testUnconsumedOutputStream = async (t, fdNumber) => {72+const 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 };77 76-test('stdout does not wait for the user to consume the output stream', testUnconsumedOutputStream, 1);77-test('stderr does not wait for the user to consume the output stream', testUnconsumedOutputStream, 2);78-test('stdio[*] does not wait for the user to consume the output stream', testUnconsumedOutputStream, 3);78+test('stdout does not wait for the user to consume the output stream', () => testUnconsumedOutputStream(1));79+test('stderr does not wait for the user to consume the output stream', () => testUnconsumedOutputStream(2));80+test('stdio[*] does not wait for the user to consume the output stream', () => testUnconsumedOutputStream(3));81 80-test('stdout does not wait for the user to consume the output stream on subprocess errors', async t => {82+test('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 });88 89 // The stream is handed back to the user with its data still readable88-test('output stream data is readable once the subprocess is done', async t => {90+test('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 });95 94-test('Waits for custom streams destroy on subprocess errors', async t => {96+test('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 });109 108-test('Handles custom streams destroy errors on subprocess success', async t => {110+test('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 });120 119-const 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);121+const testStreamEarlyExit = async (stream, streamName) => {122+ const error = await assertRejects(getEarlyErrorSubprocess({[streamName]: [stream, 'pipe']}));123+ assertLike(error, expectedEarlyError);124+ assert.equal(stream.destroyed, true);125 };126 125-test('Input streams are canceled on early subprocess exit', testStreamEarlyExit, noopReadable(), 'stdin');126-test('Output streams are canceled on early subprocess exit', testStreamEarlyExit, noopWritable(), 'stdout');127+test('Input streams are canceled on early subprocess exit', () => testStreamEarlyExit(noopReadable(), 'stdin'));128+test('Output streams are canceled on early subprocess exit', () => testStreamEarlyExit(noopWritable(), 'stdout'));129 128-const testInputDuplexStream = async (t, fdNumber) => {130+const 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 };136 135-test('Can pass Duplex streams to stdin', testInputDuplexStream, 0);136-test('Can pass Duplex streams to input stdio[*]', testInputDuplexStream, 3);137+test('Can pass Duplex streams to stdin', () => testInputDuplexStream(0));138+test('Can pass Duplex streams to input stdio[*]', () => testInputDuplexStream(3));139 138-const testOutputDuplexStream = async (t, fdNumber) => {140+const 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 };148 147-test('Can pass Duplex streams to stdout', testOutputDuplexStream, 1);148-test('Can pass Duplex streams to stderr', testOutputDuplexStream, 2);149-test('Can pass Duplex streams to output stdio[*]', testOutputDuplexStream, 3);149+test('Can pass Duplex streams to stdout', () => testOutputDuplexStream(1));150+test('Can pass Duplex streams to stderr', () => testOutputDuplexStream(2));151+test('Can pass Duplex streams to output stdio[*]', () => testOutputDuplexStream(3));152 151-const testInputStreamAbort = async (t, fdNumber) => {153+const testInputStreamAbort = async fdNumber => {154 const stream = new PassThrough();155 stream.destroy();156 157 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 };161 160-test('subprocess.stdin is ended when an input stream aborts', testInputStreamAbort, 0);161-test('subprocess.stdio[*] is ended when an input stream aborts', testInputStreamAbort, 3);162+test('subprocess.stdin is ended when an input stream aborts', () => testInputStreamAbort(0));163+test('subprocess.stdio[*] is ended when an input stream aborts', () => testInputStreamAbort(3));164 163-const testInputStreamError = async (t, fdNumber) => {165+const testInputStreamError = async fdNumber => {166 const stream = new PassThrough();167 const cause = new Error(foobarString);168 stream.destroy(cause);169 170 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 };174 173-test('subprocess.stdin is ended when an input stream errors', testInputStreamError, 0);174-test('subprocess.stdio[*] is ended when an input stream errors', testInputStreamError, 3);175+test('subprocess.stdin is ended when an input stream errors', () => testInputStreamError(0));176+test('subprocess.stdio[*] is ended when an input stream errors', () => testInputStreamError(3));177 176-const testOutputStreamError = async (t, fdNumber) => {178+const testOutputStreamError = async fdNumber => {179 const stream = new PassThrough();180 const cause = new Error(foobarString);181 stream.destroy(cause);182 183 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 };188 187-test('subprocess.stdout is aborted when an output stream errors', testOutputStreamError, 1);188-test('subprocess.stderr is aborted when an output stream errors', testOutputStreamError, 2);189-test('subprocess.stdio[*] is aborted when an output stream errors', testOutputStreamError, 3);189+test('subprocess.stdout is aborted when an output stream errors', () => testOutputStreamError(1));190+test('subprocess.stderr is aborted when an output stream errors', () => testOutputStreamError(2));191+test('subprocess.stdio[*] is aborted when an output stream errors', () => testOutputStreamError(3));modified:test/stdio/node-stream-native.js+82 added-80 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {createReadStream, createWriteStream} from 'node:fs';4 import {readFile, writeFile, rm} from 'node:fs/promises';4-import test from 'ava';5+import test from 'node:test';6 import tempfile from 'tempfile';7+import {assertThrows, assertRejects} from '../helpers/assert.js';8 import {execa, execaSync} from '../../index.js';9 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10 import {getStdio} from '../helpers/stdio.js';11 import {foobarString} from '../helpers/input.js';5 unmodified lines17 } from '../helpers/stream.js';18 19 setFixtureDirectory();20 19-const testNoFileStreamSync = async (t, fdNumber, stream) => {20- t.throws(() => {21+const testNoFileStreamSync = async (fdNumber, stream) => {22+ assertThrows(() => {23 execaSync('empty.js', getStdio(fdNumber, stream));24 }, {code: 'ERR_INVALID_ARG_VALUE'});25 };26 25-test('stdin cannot be a Node.js Readable without a file descriptor - sync', testNoFileStreamSync, 0, noopReadable());26-test('stdin cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 0, noopDuplex());27-test('stdout cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 1, noopWritable());28-test('stdout cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 1, noopDuplex());29-test('stderr cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 2, noopWritable());30-test('stderr cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 2, noopDuplex());31-test('stdio[*] cannot be a Node.js Readable without a file descriptor - sync', testNoFileStreamSync, 3, noopReadable());32-test('stdio[*] cannot be a Node.js Writable without a file descriptor - sync', testNoFileStreamSync, 3, noopWritable());33-test('stdio[*] cannot be a Node.js Duplex without a file descriptor - sync', testNoFileStreamSync, 3, noopDuplex());27+test('stdin cannot be a Node.js Readable without a file descriptor - sync', () => testNoFileStreamSync(0, noopReadable()));28+test('stdin cannot be a Node.js Duplex without a file descriptor - sync', () => testNoFileStreamSync(0, noopDuplex()));29+test('stdout cannot be a Node.js Writable without a file descriptor - sync', () => testNoFileStreamSync(1, noopWritable()));30+test('stdout cannot be a Node.js Duplex without a file descriptor - sync', () => testNoFileStreamSync(1, noopDuplex()));31+test('stderr cannot be a Node.js Writable without a file descriptor - sync', () => testNoFileStreamSync(2, noopWritable()));32+test('stderr cannot be a Node.js Duplex without a file descriptor - sync', () => testNoFileStreamSync(2, noopDuplex()));33+test('stdio[*] cannot be a Node.js Readable without a file descriptor - sync', () => testNoFileStreamSync(3, noopReadable()));34+test('stdio[*] cannot be a Node.js Writable without a file descriptor - sync', () => testNoFileStreamSync(3, noopWritable()));35+test('stdio[*] cannot be a Node.js Duplex without a file descriptor - sync', () => testNoFileStreamSync(3, noopDuplex()));36 35-test('input can be a Node.js Readable without a file descriptor', async t => {37+test('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 });41 40-test('input cannot be a Node.js Readable without a file descriptor - sync', t => {41- t.throws(() => {42+test('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 });47 46-const testNoFileStream = async (t, fdNumber, stream) => {47- await t.throwsAsync(execa('empty.js', getStdio(fdNumber, stream)), {code: 'ERR_INVALID_ARG_VALUE'});48+const testNoFileStream = async (fdNumber, stream) => {49+ await assertRejects(execa('empty.js', getStdio(fdNumber, stream)), {code: 'ERR_INVALID_ARG_VALUE'});50 };51 50-test('stdin cannot be a Node.js Readable without a file descriptor', testNoFileStream, 0, noopReadable());51-test('stdin cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 0, noopDuplex());52-test('stdout cannot be a Node.js Writable without a file descriptor', testNoFileStream, 1, noopWritable());53-test('stdout cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 1, noopDuplex());54-test('stderr cannot be a Node.js Writable without a file descriptor', testNoFileStream, 2, noopWritable());55-test('stderr cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 2, noopDuplex());56-test('stdio[*] cannot be a Node.js Readable without a file descriptor', testNoFileStream, 3, noopReadable());57-test('stdio[*] cannot be a Node.js Writable without a file descriptor', testNoFileStream, 3, noopWritable());58-test('stdio[*] cannot be a Node.js Duplex without a file descriptor', testNoFileStream, 3, noopDuplex());52+test('stdin cannot be a Node.js Readable without a file descriptor', () => testNoFileStream(0, noopReadable()));53+test('stdin cannot be a Node.js Duplex without a file descriptor', () => testNoFileStream(0, noopDuplex()));54+test('stdout cannot be a Node.js Writable without a file descriptor', () => testNoFileStream(1, noopWritable()));55+test('stdout cannot be a Node.js Duplex without a file descriptor', () => testNoFileStream(1, noopDuplex()));56+test('stderr cannot be a Node.js Writable without a file descriptor', () => testNoFileStream(2, noopWritable()));57+test('stderr cannot be a Node.js Duplex without a file descriptor', () => testNoFileStream(2, noopDuplex()));58+test('stdio[*] cannot be a Node.js Readable without a file descriptor', () => testNoFileStream(3, noopReadable()));59+test('stdio[*] cannot be a Node.js Writable without a file descriptor', () => testNoFileStream(3, noopWritable()));60+test('stdio[*] cannot be a Node.js Duplex without a file descriptor', () => testNoFileStream(3, noopDuplex()));61 62 const createFileReadStream = async () => {63 const filePath = tempfile();64 await writeFile(filePath, 'foobar');8 unmodified lines73 await once(stream, 'open');74 return {stream, filePath};75 };76 75-const assertFileStreamError = async (t, subprocess, stream, filePath) => {77+const assertFileStreamError = async (subprocess, stream, filePath) => {78 const cause = new Error('test');79 stream.destroy(cause);80 79- 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);85 86 await rm(filePath);87 };88 87-const testFileReadable = async (t, fdNumber, execaMethod) => {89+const testFileReadable = async (fdNumber, execaMethod) => {90 const {stream, filePath} = await createFileReadStream();91 92 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');95 96 await rm(filePath);97 };98 97-test('input can be a Node.js Readable with a file descriptor', testFileReadable, 'input', execa);98-test('stdin can be a Node.js Readable with a file descriptor', testFileReadable, 0, execa);99-test('stdio[*] can be a Node.js Readable with a file descriptor', testFileReadable, 3, execa);100-test('stdin can be a Node.js Readable with a file descriptor - sync', testFileReadable, 0, execaSync);101-test('stdio[*] can be a Node.js Readable with a file descriptor - sync', testFileReadable, 3, execaSync);99+test('input can be a Node.js Readable with a file descriptor', () => testFileReadable('input', execa));100+test('stdin can be a Node.js Readable with a file descriptor', () => testFileReadable(0, execa));101+test('stdio[*] can be a Node.js Readable with a file descriptor', () => testFileReadable(3, execa));102+test('stdin can be a Node.js Readable with a file descriptor - sync', () => testFileReadable(0, execaSync));103+test('stdio[*] can be a Node.js Readable with a file descriptor - sync', () => testFileReadable(3, execaSync));104 103-const testFileReadableError = async (t, fdNumber) => {105+const testFileReadableError = async fdNumber => {106 const {stream, filePath} = await createFileReadStream();107 108 const fdNumberString = fdNumber === 'input' ? '0' : `${fdNumber}`;109 const subprocess = execa('stdin-fd.js', [fdNumberString], getStdio(fdNumber, stream));110 109- await assertFileStreamError(t, subprocess, stream, filePath);111+ await assertFileStreamError(subprocess, stream, filePath);112 };113 112-test.serial('input handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 'input');113-test.serial('stdin handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 0);114-test.serial('stdio[*] handles errors from a Node.js Readable with a file descriptor', testFileReadableError, 3);114+test('input handles errors from a Node.js Readable with a file descriptor', () => testFileReadableError('input'));115+test('stdin handles errors from a Node.js Readable with a file descriptor', () => testFileReadableError(0));116+test('stdio[*] handles errors from a Node.js Readable with a file descriptor', () => testFileReadableError(3));117 116-const testFileReadableOpen = async (t, fdNumber, useSingle, execaMethod) => {118+const testFileReadableOpen = async (fdNumber, useSingle, execaMethod) => {119 const {stream, filePath} = await createFileReadStream();118- t.deepEqual(stream.eventNames(), []);120+ assert.deepEqual(stream.eventNames(), []);121 122 const stdioOption = useSingle ? stream : [stream, 'pipe'];123 await execaMethod('empty.js', getStdio(fdNumber, stdioOption));124 123- 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(), []);127 128 await rm(filePath);129 };130 129-test('input closes a Node.js Readable with a file descriptor', testFileReadableOpen, 'input', true, execa);130-test('stdin leaves open a single Node.js Readable with a file descriptor', testFileReadableOpen, 0, true, execa);131-test('stdin closes a combined Node.js Readable with a file descriptor', testFileReadableOpen, 0, false, execa);132-test('stdio[*] leaves open a single Node.js Readable with a file descriptor', testFileReadableOpen, 3, true, execa);133-test('stdin leaves open a single Node.js Readable with a file descriptor - sync', testFileReadableOpen, 0, true, execaSync);134-test('stdio[*] leaves open a single Node.js Readable with a file descriptor - sync', testFileReadableOpen, 3, true, execaSync);131+test('input closes a Node.js Readable with a file descriptor', () => testFileReadableOpen('input', true, execa));132+test('stdin leaves open a single Node.js Readable with a file descriptor', () => testFileReadableOpen(0, true, execa));133+test('stdin closes a combined Node.js Readable with a file descriptor', () => testFileReadableOpen(0, false, execa));134+test('stdio[*] leaves open a single Node.js Readable with a file descriptor', () => testFileReadableOpen(3, true, execa));135+test('stdin leaves open a single Node.js Readable with a file descriptor - sync', () => testFileReadableOpen(0, true, execaSync));136+test('stdio[*] leaves open a single Node.js Readable with a file descriptor - sync', () => testFileReadableOpen(3, true, execaSync));137 136-const testFileWritable = async (t, fdNumber, execaMethod) => {138+const testFileWritable = async (fdNumber, execaMethod) => {139 const {stream, filePath} = await createFileWriteStream();140 141 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');143 144 await rm(filePath);145 };146 145-test('stdout can be a Node.js Writable with a file descriptor', testFileWritable, 1, execa);146-test('stderr can be a Node.js Writable with a file descriptor', testFileWritable, 2, execa);147-test('stdio[*] can be a Node.js Writable with a file descriptor', testFileWritable, 3, execa);148-test('stdout can be a Node.js Writable with a file descriptor - sync', testFileWritable, 1, execaSync);149-test('stderr can be a Node.js Writable with a file descriptor - sync', testFileWritable, 2, execaSync);150-test('stdio[*] can be a Node.js Writable with a file descriptor - sync', testFileWritable, 3, execaSync);147+test('stdout can be a Node.js Writable with a file descriptor', () => testFileWritable(1, execa));148+test('stderr can be a Node.js Writable with a file descriptor', () => testFileWritable(2, execa));149+test('stdio[*] can be a Node.js Writable with a file descriptor', () => testFileWritable(3, execa));150+test('stdout can be a Node.js Writable with a file descriptor - sync', () => testFileWritable(1, execaSync));151+test('stderr can be a Node.js Writable with a file descriptor - sync', () => testFileWritable(2, execaSync));152+test('stdio[*] can be a Node.js Writable with a file descriptor - sync', () => testFileWritable(3, execaSync));153 152-const testFileWritableError = async (t, fdNumber) => {154+const testFileWritableError = async fdNumber => {155 const {stream, filePath} = await createFileWriteStream();156 157 const subprocess = execa('noop-fd.js', [`${fdNumber}`, foobarString], getStdio(fdNumber, stream));158 157- await assertFileStreamError(t, subprocess, stream, filePath);159+ await assertFileStreamError(subprocess, stream, filePath);160 };161 160-test.serial('stdout handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 1);161-test.serial('stderr handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 2);162-test.serial('stdio[*] handles errors from a Node.js Writable with a file descriptor', testFileWritableError, 3);162+test('stdout handles errors from a Node.js Writable with a file descriptor', () => testFileWritableError(1));163+test('stderr handles errors from a Node.js Writable with a file descriptor', () => testFileWritableError(2));164+test('stdio[*] handles errors from a Node.js Writable with a file descriptor', () => testFileWritableError(3));165 164-const testFileWritableOpen = async (t, fdNumber, useSingle, execaMethod) => {166+const testFileWritableOpen = async (fdNumber, useSingle, execaMethod) => {167 const {stream, filePath} = await createFileWriteStream();166- t.deepEqual(stream.eventNames(), []);168+ assert.deepEqual(stream.eventNames(), []);169 170 const stdioOption = useSingle ? stream : [stream, 'pipe'];171 await execaMethod('empty.js', getStdio(fdNumber, stdioOption));172 171- t.is(stream.writable, useSingle);172- t.deepEqual(stream.eventNames(), []);173+ assert.equal(stream.writable, useSingle);174+ assert.deepEqual(stream.eventNames(), []);175 176 await rm(filePath);177 };178 177-test('stdout leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 1, true, execa);178-test('stdout closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 1, false, execa);179-test('stderr leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 2, true, execa);180-test('stderr closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 2, false, execa);181-test('stdio[*] leaves open a single Node.js Writable with a file descriptor', testFileWritableOpen, 3, true, execa);182-test('stdio[*] closes a combined Node.js Writable with a file descriptor', testFileWritableOpen, 3, false, execa);183-test('stdout leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 1, true, execaSync);184-test('stderr leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 2, true, execaSync);185-test('stdio[*] leaves open a single Node.js Writable with a file descriptor - sync', testFileWritableOpen, 3, true, execaSync);179+test('stdout leaves open a single Node.js Writable with a file descriptor', () => testFileWritableOpen(1, true, execa));180+test('stdout closes a combined Node.js Writable with a file descriptor', () => testFileWritableOpen(1, false, execa));181+test('stderr leaves open a single Node.js Writable with a file descriptor', () => testFileWritableOpen(2, true, execa));182+test('stderr closes a combined Node.js Writable with a file descriptor', () => testFileWritableOpen(2, false, execa));183+test('stdio[*] leaves open a single Node.js Writable with a file descriptor', () => testFileWritableOpen(3, true, execa));184+test('stdio[*] closes a combined Node.js Writable with a file descriptor', () => testFileWritableOpen(3, false, execa));185+test('stdout leaves open a single Node.js Writable with a file descriptor - sync', () => testFileWritableOpen(1, true, execaSync));186+test('stderr leaves open a single Node.js Writable with a file descriptor - sync', () => testFileWritableOpen(2, true, execaSync));187+test('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
1+import assert from 'node:assert/strict';2 import {inspect} from 'node:util';2-import test from 'ava';3+import test from 'node:test';4+import {assertThrows} from '../helpers/assert.js';5 import {normalizeStdioOption} from '../../lib/stdio/stdio-option.js';6 5-const stdioMacro = (t, input, expected) => {7+const stdioMacro = (input, expected) => {8 if (expected instanceof Error) {7- t.throws(() => {9+ assertThrows(() => {10 normalizeStdioOption(input);11 }, {message: expected.message});12 return;13 }14 13- t.deepEqual(normalizeStdioOption(input), expected);15+ assert.deepEqual(normalizeStdioOption(input), expected);16 };17 16-stdioMacro.title = (_, input) => `execa() ${(inspect(input))}`;18+const stdioCases = [19+ [{stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']],20+ [{stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']],21+ [{stdio: 'ignore'}, ['ignore', 'ignore', 'ignore']],22 18-test(stdioMacro, {stdio: 'inherit'}, ['inherit', 'inherit', 'inherit']);19-test(stdioMacro, {stdio: 'pipe'}, ['pipe', 'pipe', 'pipe']);20-test(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']],37 22-test(stdioMacro, {}, ['pipe', 'pipe', 'pipe']);23-test(stdioMacro, {stdio: []}, ['pipe', 'pipe', 'pipe']);24-test(stdioMacro, {stdio: [0]}, [0, 'pipe', 'pipe']);25-test(stdioMacro, {stdio: [0, 1]}, [0, 1, 'pipe']);26-test(stdioMacro, {stdio: [0, 1, 2]}, [0, 1, 2]);27-test(stdioMacro, {stdio: [0, 1, 2, 3]}, [0, 1, 2, 3]);28-test(stdioMacro, {stdio: [undefined, 1, 2]}, ['pipe', 1, 2]);29-test(stdioMacro, {stdio: [null, 1, 2]}, ['pipe', 1, 2]);30-test(stdioMacro, {stdio: [0, undefined, 2]}, [0, 'pipe', 2]);31-test(stdioMacro, {stdio: [0, null, 2]}, [0, 'pipe', 2]);32-test(stdioMacro, {stdio: [0, 1, undefined]}, [0, 1, 'pipe']);33-test(stdioMacro, {stdio: [0, 1, null]}, [0, 1, 'pipe']);34-test(stdioMacro, {stdio: [0, 1, 2, undefined]}, [0, 1, 2, 'ignore']);35-test(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]],49 37-test(stdioMacro, {stdin: 'pipe'}, ['pipe', 'pipe', 'pipe']);38-test(stdioMacro, {stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);39-test(stdioMacro, {stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);40-test(stdioMacro, {stdin: 'pipe', stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);41-test(stdioMacro, {stdin: 'pipe', stdout: 'ignore'}, ['pipe', 'ignore', 'pipe']);42-test(stdioMacro, {stdin: 'pipe', stderr: 'inherit'}, ['pipe', 'pipe', 'inherit']);43-test(stdioMacro, {stdout: 'ignore', stderr: 'inherit'}, ['pipe', 'ignore', 'inherit']);44-test(stdioMacro, {stdin: 0, stdout: 1, stderr: 2}, [0, 1, 2]);45-test(stdioMacro, {stdin: 0, stdout: 1}, [0, 1, 'pipe']);46-test(stdioMacro, {stdin: 0, stderr: 2}, [0, 'pipe', 2]);47-test(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`')],51 49-test(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+];57 51-test(stdioMacro, {stdin: 'inherit', stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));52-test(stdioMacro, {stdin: 'inherit', stdio: ['pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));53-test(stdioMacro, {stdin: 'inherit', stdio: [undefined, 'pipe']}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));54-test(stdioMacro, {stdin: 0, stdio: 'pipe'}, new Error('It\'s not possible to provide `stdio` in combination with one of `stdin`, `stdout`, `stderr`'));58+for (const [input, expected] of stdioCases) {59+ test(`execa() ${inspect(input)}`, () => stdioMacro(input, expected));60+}modified:test/stdio/type-invalid.js+46 added-46 removed
1-import test from 'ava';1+import test from 'node:test';2+import {assertThrows} from '../helpers/assert.js';3 import {execa, execaSync} from '../../index.js';4 import {getStdio} from '../helpers/stdio.js';5 import {noopGenerator} from '../helpers/generator.js';6 import {generatorsMap} from '../helpers/map.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 9 setFixtureDirectory();10 10-const testInvalidGenerator = (t, fdNumber, stdioOption, execaMethod) => {11- t.throws(() => {11+const 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 };16 16-test('Cannot use invalid "transform" with stdin', testInvalidGenerator, 0, {transform: true}, execa);17-test('Cannot use invalid "transform" with stdout', testInvalidGenerator, 1, {transform: true}, execa);18-test('Cannot use invalid "transform" with stderr', testInvalidGenerator, 2, {transform: true}, execa);19-test('Cannot use invalid "transform" with stdio[*]', testInvalidGenerator, 3, {transform: true}, execa);20-test('Cannot use invalid "final" with stdin', testInvalidGenerator, 0, {final: true}, execa);21-test('Cannot use invalid "final" with stdout', testInvalidGenerator, 1, {final: true}, execa);22-test('Cannot use invalid "final" with stderr', testInvalidGenerator, 2, {final: true}, execa);23-test('Cannot use invalid "final" with stdio[*]', testInvalidGenerator, 3, {final: true}, execa);24-test('Cannot use invalid "transform" with stdin, sync', testInvalidGenerator, 0, {transform: true}, execaSync);25-test('Cannot use invalid "transform" with stdout, sync', testInvalidGenerator, 1, {transform: true}, execaSync);26-test('Cannot use invalid "transform" with stderr, sync', testInvalidGenerator, 2, {transform: true}, execaSync);27-test('Cannot use invalid "transform" with stdio[*], sync', testInvalidGenerator, 3, {transform: true}, execaSync);28-test('Cannot use invalid "final" with stdin, sync', testInvalidGenerator, 0, {final: true}, execaSync);29-test('Cannot use invalid "final" with stdout, sync', testInvalidGenerator, 1, {final: true}, execaSync);30-test('Cannot use invalid "final" with stderr, sync', testInvalidGenerator, 2, {final: true}, execaSync);31-test('Cannot use invalid "final" with stdio[*], sync', testInvalidGenerator, 3, {final: true}, execaSync);17+test('Cannot use invalid "transform" with stdin', () => testInvalidGenerator(0, {transform: true}, execa));18+test('Cannot use invalid "transform" with stdout', () => testInvalidGenerator(1, {transform: true}, execa));19+test('Cannot use invalid "transform" with stderr', () => testInvalidGenerator(2, {transform: true}, execa));20+test('Cannot use invalid "transform" with stdio[*]', () => testInvalidGenerator(3, {transform: true}, execa));21+test('Cannot use invalid "final" with stdin', () => testInvalidGenerator(0, {final: true}, execa));22+test('Cannot use invalid "final" with stdout', () => testInvalidGenerator(1, {final: true}, execa));23+test('Cannot use invalid "final" with stderr', () => testInvalidGenerator(2, {final: true}, execa));24+test('Cannot use invalid "final" with stdio[*]', () => testInvalidGenerator(3, {final: true}, execa));25+test('Cannot use invalid "transform" with stdin, sync', () => testInvalidGenerator(0, {transform: true}, execaSync));26+test('Cannot use invalid "transform" with stdout, sync', () => testInvalidGenerator(1, {transform: true}, execaSync));27+test('Cannot use invalid "transform" with stderr, sync', () => testInvalidGenerator(2, {transform: true}, execaSync));28+test('Cannot use invalid "transform" with stdio[*], sync', () => testInvalidGenerator(3, {transform: true}, execaSync));29+test('Cannot use invalid "final" with stdin, sync', () => testInvalidGenerator(0, {final: true}, execaSync));30+test('Cannot use invalid "final" with stdout, sync', () => testInvalidGenerator(1, {final: true}, execaSync));31+test('Cannot use invalid "final" with stderr, sync', () => testInvalidGenerator(2, {final: true}, execaSync));32+test('Cannot use invalid "final" with stdio[*], sync', () => testInvalidGenerator(3, {final: true}, execaSync));33 33-// eslint-disable-next-line max-params34-const testInvalidBinary = (t, fdNumber, optionName, type, execaMethod) => {35- t.throws(() => {34+const testInvalidBinary = (fdNumber, optionName, type, execaMethod) => {35+ assertThrows(() => {36 execaMethod('empty.js', getStdio(fdNumber, {...generatorsMap[type].uppercase(), [optionName]: 'true'}));37 }, {message: /a boolean/});38 };39 40-test('Cannot use invalid "binary" with stdin', testInvalidBinary, 0, 'binary', 'generator', execa);41-test('Cannot use invalid "binary" with stdout', testInvalidBinary, 1, 'binary', 'generator', execa);42-test('Cannot use invalid "binary" with stderr', testInvalidBinary, 2, 'binary', 'generator', execa);43-test('Cannot use invalid "binary" with stdio[*]', testInvalidBinary, 3, 'binary', 'generator', execa);44-test('Cannot use invalid "objectMode" with stdin, generators', testInvalidBinary, 0, 'objectMode', 'generator', execa);45-test('Cannot use invalid "objectMode" with stdout, generators', testInvalidBinary, 1, 'objectMode', 'generator', execa);46-test('Cannot use invalid "objectMode" with stderr, generators', testInvalidBinary, 2, 'objectMode', 'generator', execa);47-test('Cannot use invalid "objectMode" with stdio[*], generators', testInvalidBinary, 3, 'objectMode', 'generator', execa);48-test('Cannot use invalid "binary" with stdin, sync', testInvalidBinary, 0, 'binary', 'generator', execaSync);49-test('Cannot use invalid "binary" with stdout, sync', testInvalidBinary, 1, 'binary', 'generator', execaSync);50-test('Cannot use invalid "binary" with stderr, sync', testInvalidBinary, 2, 'binary', 'generator', execaSync);51-test('Cannot use invalid "binary" with stdio[*], sync', testInvalidBinary, 3, 'binary', 'generator', execaSync);52-test('Cannot use invalid "objectMode" with stdin, generators, sync', testInvalidBinary, 0, 'objectMode', 'generator', execaSync);53-test('Cannot use invalid "objectMode" with stdout, generators, sync', testInvalidBinary, 1, 'objectMode', 'generator', execaSync);54-test('Cannot use invalid "objectMode" with stderr, generators, sync', testInvalidBinary, 2, 'objectMode', 'generator', execaSync);55-test('Cannot use invalid "objectMode" with stdio[*], generators, sync', testInvalidBinary, 3, 'objectMode', 'generator', execaSync);56-test('Cannot use invalid "objectMode" with stdin, duplexes', testInvalidBinary, 0, 'objectMode', 'duplex', execa);57-test('Cannot use invalid "objectMode" with stdout, duplexes', testInvalidBinary, 1, 'objectMode', 'duplex', execa);58-test('Cannot use invalid "objectMode" with stderr, duplexes', testInvalidBinary, 2, 'objectMode', 'duplex', execa);59-test('Cannot use invalid "objectMode" with stdio[*], duplexes', testInvalidBinary, 3, 'objectMode', 'duplex', execa);60-test('Cannot use invalid "objectMode" with stdin, webTransforms', testInvalidBinary, 0, 'objectMode', 'webTransform', execa);61-test('Cannot use invalid "objectMode" with stdout, webTransforms', testInvalidBinary, 1, 'objectMode', 'webTransform', execa);62-test('Cannot use invalid "objectMode" with stderr, webTransforms', testInvalidBinary, 2, 'objectMode', 'webTransform', execa);63-test('Cannot use invalid "objectMode" with stdio[*], webTransforms', testInvalidBinary, 3, 'objectMode', 'webTransform', execa);40+test('Cannot use invalid "binary" with stdin', () => testInvalidBinary(0, 'binary', 'generator', execa));41+test('Cannot use invalid "binary" with stdout', () => testInvalidBinary(1, 'binary', 'generator', execa));42+test('Cannot use invalid "binary" with stderr', () => testInvalidBinary(2, 'binary', 'generator', execa));43+test('Cannot use invalid "binary" with stdio[*]', () => testInvalidBinary(3, 'binary', 'generator', execa));44+test('Cannot use invalid "objectMode" with stdin, generators', () => testInvalidBinary(0, 'objectMode', 'generator', execa));45+test('Cannot use invalid "objectMode" with stdout, generators', () => testInvalidBinary(1, 'objectMode', 'generator', execa));46+test('Cannot use invalid "objectMode" with stderr, generators', () => testInvalidBinary(2, 'objectMode', 'generator', execa));47+test('Cannot use invalid "objectMode" with stdio[*], generators', () => testInvalidBinary(3, 'objectMode', 'generator', execa));48+test('Cannot use invalid "binary" with stdin, sync', () => testInvalidBinary(0, 'binary', 'generator', execaSync));49+test('Cannot use invalid "binary" with stdout, sync', () => testInvalidBinary(1, 'binary', 'generator', execaSync));50+test('Cannot use invalid "binary" with stderr, sync', () => testInvalidBinary(2, 'binary', 'generator', execaSync));51+test('Cannot use invalid "binary" with stdio[*], sync', () => testInvalidBinary(3, 'binary', 'generator', execaSync));52+test('Cannot use invalid "objectMode" with stdin, generators, sync', () => testInvalidBinary(0, 'objectMode', 'generator', execaSync));53+test('Cannot use invalid "objectMode" with stdout, generators, sync', () => testInvalidBinary(1, 'objectMode', 'generator', execaSync));54+test('Cannot use invalid "objectMode" with stderr, generators, sync', () => testInvalidBinary(2, 'objectMode', 'generator', execaSync));55+test('Cannot use invalid "objectMode" with stdio[*], generators, sync', () => testInvalidBinary(3, 'objectMode', 'generator', execaSync));56+test('Cannot use invalid "objectMode" with stdin, duplexes', () => testInvalidBinary(0, 'objectMode', 'duplex', execa));57+test('Cannot use invalid "objectMode" with stdout, duplexes', () => testInvalidBinary(1, 'objectMode', 'duplex', execa));58+test('Cannot use invalid "objectMode" with stderr, duplexes', () => testInvalidBinary(2, 'objectMode', 'duplex', execa));59+test('Cannot use invalid "objectMode" with stdio[*], duplexes', () => testInvalidBinary(3, 'objectMode', 'duplex', execa));60+test('Cannot use invalid "objectMode" with stdin, webTransforms', () => testInvalidBinary(0, 'objectMode', 'webTransform', execa));61+test('Cannot use invalid "objectMode" with stdout, webTransforms', () => testInvalidBinary(1, 'objectMode', 'webTransform', execa));62+test('Cannot use invalid "objectMode" with stderr, webTransforms', () => testInvalidBinary(2, 'objectMode', 'webTransform', execa));63+test('Cannot use invalid "objectMode" with stdio[*], webTransforms', () => testInvalidBinary(3, 'objectMode', 'webTransform', execa));modified:test/stdio/type-undefined.js+48 added-48 removed
1-import test from 'ava';1+import test from 'node:test';2+import {assertThrows} from '../helpers/assert.js';3 import {execa, execaSync} from '../../index.js';4 import {getStdio} from '../helpers/stdio.js';5 import {uppercaseGenerator} from '../helpers/generator.js';6 import {uppercaseBufferDuplex} from '../helpers/duplex.js';2 unmodified lines9 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';10 11 setFixtureDirectory();12 12-// eslint-disable-next-line max-params13-const testUndefinedOption = (t, fdNumber, optionName, type, optionValue) => {14- t.throws(() => {13+const 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 };18 19-test('Cannot use "binary" with duplexes and stdin', testUndefinedOption, 0, 'binary', 'duplex', true);20-test('Cannot use "binary" with duplexes and stdout', testUndefinedOption, 1, 'binary', 'duplex', true);21-test('Cannot use "binary" with duplexes and stderr', testUndefinedOption, 2, 'binary', 'duplex', true);22-test('Cannot use "binary" with duplexes and stdio[*]', testUndefinedOption, 3, 'binary', 'duplex', true);23-test('Cannot use "final" with duplexes and stdin', testUndefinedOption, 0, 'final', 'duplex', uppercaseBufferDuplex().transform);24-test('Cannot use "final" with duplexes and stdout', testUndefinedOption, 1, 'final', 'duplex', uppercaseBufferDuplex().transform);25-test('Cannot use "final" with duplexes and stderr', testUndefinedOption, 2, 'final', 'duplex', uppercaseBufferDuplex().transform);26-test('Cannot use "final" with duplexes and stdio[*]', testUndefinedOption, 3, 'final', 'duplex', uppercaseBufferDuplex().transform);27-test('Cannot use "binary" with webTransforms and stdin', testUndefinedOption, 0, 'binary', 'webTransform', true);28-test('Cannot use "binary" with webTransforms and stdout', testUndefinedOption, 1, 'binary', 'webTransform', true);29-test('Cannot use "binary" with webTransforms and stderr', testUndefinedOption, 2, 'binary', 'webTransform', true);30-test('Cannot use "binary" with webTransforms and stdio[*]', testUndefinedOption, 3, 'binary', 'webTransform', true);31-test('Cannot use "final" with webTransforms and stdin', testUndefinedOption, 0, 'final', 'webTransform', uppercaseBufferWebTransform().transform);32-test('Cannot use "final" with webTransforms and stdout', testUndefinedOption, 1, 'final', 'webTransform', uppercaseBufferWebTransform().transform);33-test('Cannot use "final" with webTransforms and stderr', testUndefinedOption, 2, 'final', 'webTransform', uppercaseBufferWebTransform().transform);34-test('Cannot use "final" with webTransforms and stdio[*]', testUndefinedOption, 3, 'final', 'webTransform', uppercaseBufferWebTransform().transform);19+test('Cannot use "binary" with duplexes and stdin', () => testUndefinedOption(0, 'binary', 'duplex', true));20+test('Cannot use "binary" with duplexes and stdout', () => testUndefinedOption(1, 'binary', 'duplex', true));21+test('Cannot use "binary" with duplexes and stderr', () => testUndefinedOption(2, 'binary', 'duplex', true));22+test('Cannot use "binary" with duplexes and stdio[*]', () => testUndefinedOption(3, 'binary', 'duplex', true));23+test('Cannot use "final" with duplexes and stdin', () => testUndefinedOption(0, 'final', 'duplex', uppercaseBufferDuplex().transform));24+test('Cannot use "final" with duplexes and stdout', () => testUndefinedOption(1, 'final', 'duplex', uppercaseBufferDuplex().transform));25+test('Cannot use "final" with duplexes and stderr', () => testUndefinedOption(2, 'final', 'duplex', uppercaseBufferDuplex().transform));26+test('Cannot use "final" with duplexes and stdio[*]', () => testUndefinedOption(3, 'final', 'duplex', uppercaseBufferDuplex().transform));27+test('Cannot use "binary" with webTransforms and stdin', () => testUndefinedOption(0, 'binary', 'webTransform', true));28+test('Cannot use "binary" with webTransforms and stdout', () => testUndefinedOption(1, 'binary', 'webTransform', true));29+test('Cannot use "binary" with webTransforms and stderr', () => testUndefinedOption(2, 'binary', 'webTransform', true));30+test('Cannot use "binary" with webTransforms and stdio[*]', () => testUndefinedOption(3, 'binary', 'webTransform', true));31+test('Cannot use "final" with webTransforms and stdin', () => testUndefinedOption(0, 'final', 'webTransform', uppercaseBufferWebTransform().transform));32+test('Cannot use "final" with webTransforms and stdout', () => testUndefinedOption(1, 'final', 'webTransform', uppercaseBufferWebTransform().transform));33+test('Cannot use "final" with webTransforms and stderr', () => testUndefinedOption(2, 'final', 'webTransform', uppercaseBufferWebTransform().transform));34+test('Cannot use "final" with webTransforms and stdio[*]', () => testUndefinedOption(3, 'final', 'webTransform', uppercaseBufferWebTransform().transform));35 36-const testUndefinedFinal = (t, fdNumber, type, useTransform) => {37- t.throws(() => {36+const 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 };44 45-test('Cannot use "final" with duplexes and stdin, without transform', testUndefinedFinal, 0, 'duplex', false);46-test('Cannot use "final" with duplexes and stdout, without transform', testUndefinedFinal, 1, 'duplex', false);47-test('Cannot use "final" with duplexes and stderr, without transform', testUndefinedFinal, 2, 'duplex', false);48-test('Cannot use "final" with duplexes and stdio[*], without transform', testUndefinedFinal, 3, 'duplex', false);49-test('Cannot use "final" with duplexes and stdin, with transform', testUndefinedFinal, 0, 'duplex', true);50-test('Cannot use "final" with duplexes and stdout, with transform', testUndefinedFinal, 1, 'duplex', true);51-test('Cannot use "final" with duplexes and stderr, with transform', testUndefinedFinal, 2, 'duplex', true);52-test('Cannot use "final" with duplexes and stdio[*], with transform', testUndefinedFinal, 3, 'duplex', true);53-test('Cannot use "final" with webTransforms and stdin, without transform', testUndefinedFinal, 0, 'webTransform', false);54-test('Cannot use "final" with webTransforms and stdout, without transform', testUndefinedFinal, 1, 'webTransform', false);55-test('Cannot use "final" with webTransforms and stderr, without transform', testUndefinedFinal, 2, 'webTransform', false);56-test('Cannot use "final" with webTransforms and stdio[*], without transform', testUndefinedFinal, 3, 'webTransform', false);57-test('Cannot use "final" with webTransforms and stdin, with transform', testUndefinedFinal, 0, 'webTransform', true);58-test('Cannot use "final" with webTransforms and stdout, with transform', testUndefinedFinal, 1, 'webTransform', true);59-test('Cannot use "final" with webTransforms and stderr, with transform', testUndefinedFinal, 2, 'webTransform', true);60-test('Cannot use "final" with webTransforms and stdio[*], with transform', testUndefinedFinal, 3, 'webTransform', true);45+test('Cannot use "final" with duplexes and stdin, without transform', () => testUndefinedFinal(0, 'duplex', false));46+test('Cannot use "final" with duplexes and stdout, without transform', () => testUndefinedFinal(1, 'duplex', false));47+test('Cannot use "final" with duplexes and stderr, without transform', () => testUndefinedFinal(2, 'duplex', false));48+test('Cannot use "final" with duplexes and stdio[*], without transform', () => testUndefinedFinal(3, 'duplex', false));49+test('Cannot use "final" with duplexes and stdin, with transform', () => testUndefinedFinal(0, 'duplex', true));50+test('Cannot use "final" with duplexes and stdout, with transform', () => testUndefinedFinal(1, 'duplex', true));51+test('Cannot use "final" with duplexes and stderr, with transform', () => testUndefinedFinal(2, 'duplex', true));52+test('Cannot use "final" with duplexes and stdio[*], with transform', () => testUndefinedFinal(3, 'duplex', true));53+test('Cannot use "final" with webTransforms and stdin, without transform', () => testUndefinedFinal(0, 'webTransform', false));54+test('Cannot use "final" with webTransforms and stdout, without transform', () => testUndefinedFinal(1, 'webTransform', false));55+test('Cannot use "final" with webTransforms and stderr, without transform', () => testUndefinedFinal(2, 'webTransform', false));56+test('Cannot use "final" with webTransforms and stdio[*], without transform', () => testUndefinedFinal(3, 'webTransform', false));57+test('Cannot use "final" with webTransforms and stdin, with transform', () => testUndefinedFinal(0, 'webTransform', true));58+test('Cannot use "final" with webTransforms and stdout, with transform', () => testUndefinedFinal(1, 'webTransform', true));59+test('Cannot use "final" with webTransforms and stderr, with transform', () => testUndefinedFinal(2, 'webTransform', true));60+test('Cannot use "final" with webTransforms and stdio[*], with transform', () => testUndefinedFinal(3, 'webTransform', true));61 62-const testSyncMethodsDuplex = (t, fdNumber, type) => {63- t.throws(() => {62+const 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 };67 68-test('Cannot use duplexes with sync methods and stdin', testSyncMethodsDuplex, 0, 'duplex');69-test('Cannot use duplexes with sync methods and stdout', testSyncMethodsDuplex, 1, 'duplex');70-test('Cannot use duplexes with sync methods and stderr', testSyncMethodsDuplex, 2, 'duplex');71-test('Cannot use duplexes with sync methods and stdio[*]', testSyncMethodsDuplex, 3, 'duplex');72-test('Cannot use webTransforms with sync methods and stdin', testSyncMethodsDuplex, 0, 'webTransform');73-test('Cannot use webTransforms with sync methods and stdout', testSyncMethodsDuplex, 1, 'webTransform');74-test('Cannot use webTransforms with sync methods and stderr', testSyncMethodsDuplex, 2, 'webTransform');75-test('Cannot use webTransforms with sync methods and stdio[*]', testSyncMethodsDuplex, 3, 'webTransform');68+test('Cannot use duplexes with sync methods and stdin', () => testSyncMethodsDuplex(0, 'duplex'));69+test('Cannot use duplexes with sync methods and stdout', () => testSyncMethodsDuplex(1, 'duplex'));70+test('Cannot use duplexes with sync methods and stderr', () => testSyncMethodsDuplex(2, 'duplex'));71+test('Cannot use duplexes with sync methods and stdio[*]', () => testSyncMethodsDuplex(3, 'duplex'));72+test('Cannot use webTransforms with sync methods and stdin', () => testSyncMethodsDuplex(0, 'webTransform'));73+test('Cannot use webTransforms with sync methods and stdout', () => testSyncMethodsDuplex(1, 'webTransform'));74+test('Cannot use webTransforms with sync methods and stderr', () => testSyncMethodsDuplex(2, 'webTransform'));75+test('Cannot use webTransforms with sync methods and stdio[*]', () => testSyncMethodsDuplex(3, 'webTransform'));modified:test/stdio/typed-array.js+21 added-19 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {getStdio} from '../helpers/stdio.js';7 import {foobarUint8Array, foobarBuffer, foobarString} from '../helpers/input.js';8 9 setFixtureDirectory();10 9-const testUint8Array = async (t, fdNumber, stdioOption, execaMethod) => {11+const 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 };15 14-test('stdin option can be a Uint8Array', testUint8Array, 0, foobarUint8Array, execa);15-test('stdio[*] option can be a Uint8Array', testUint8Array, 3, foobarUint8Array, execa);16-test('stdin option can be a Uint8Array - sync', testUint8Array, 0, foobarUint8Array, execaSync);17-test('stdin option can be a Buffer', testUint8Array, 0, foobarBuffer, execa);18-test('stdio[*] option can be a Buffer', testUint8Array, 3, foobarBuffer, execa);19-test('stdin option can be a Buffer - sync', testUint8Array, 0, foobarBuffer, execaSync);16+test('stdin option can be a Uint8Array', () => testUint8Array(0, foobarUint8Array, execa));17+test('stdio[*] option can be a Uint8Array', () => testUint8Array(3, foobarUint8Array, execa));18+test('stdin option can be a Uint8Array - sync', () => testUint8Array(0, foobarUint8Array, execaSync));19+test('stdin option can be a Buffer', () => testUint8Array(0, foobarBuffer, execa));20+test('stdio[*] option can be a Buffer', () => testUint8Array(3, foobarBuffer, execa));21+test('stdin option can be a Buffer - sync', () => testUint8Array(0, foobarBuffer, execaSync));22 21-const testNoUint8ArrayOutput = (t, fdNumber, stdioOption, execaMethod) => {22- t.throws(() => {23+const testNoUint8ArrayOutput = (fdNumber, stdioOption, execaMethod) => {24+ assertThrows(() => {25 execaMethod('empty.js', getStdio(fdNumber, stdioOption));26 }, {message: /cannot be a Uint8Array/});27 };28 27-test('stdout option cannot be a Uint8Array', testNoUint8ArrayOutput, 1, foobarUint8Array, execa);28-test('stderr option cannot be a Uint8Array', testNoUint8ArrayOutput, 2, foobarUint8Array, execa);29-test('stdout option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, 1, foobarUint8Array, execaSync);30-test('stderr option cannot be a Uint8Array - sync', testNoUint8ArrayOutput, 2, foobarUint8Array, execaSync);31-test('stdout option cannot be a Buffer', testNoUint8ArrayOutput, 1, foobarBuffer, execa);32-test('stderr option cannot be a Buffer', testNoUint8ArrayOutput, 2, foobarBuffer, execa);33-test('stdout option cannot be a Buffer - sync', testNoUint8ArrayOutput, 1, foobarBuffer, execaSync);34-test('stderr option cannot be a Buffer - sync', testNoUint8ArrayOutput, 2, foobarBuffer, execaSync);29+test('stdout option cannot be a Uint8Array', () => testNoUint8ArrayOutput(1, foobarUint8Array, execa));30+test('stderr option cannot be a Uint8Array', () => testNoUint8ArrayOutput(2, foobarUint8Array, execa));31+test('stdout option cannot be a Uint8Array - sync', () => testNoUint8ArrayOutput(1, foobarUint8Array, execaSync));32+test('stderr option cannot be a Uint8Array - sync', () => testNoUint8ArrayOutput(2, foobarUint8Array, execaSync));33+test('stdout option cannot be a Buffer', () => testNoUint8ArrayOutput(1, foobarBuffer, execa));34+test('stderr option cannot be a Buffer', () => testNoUint8ArrayOutput(2, foobarBuffer, execa));35+test('stdout option cannot be a Buffer - sync', () => testNoUint8ArrayOutput(1, foobarBuffer, execaSync));36+test('stderr option cannot be a Buffer - sync', () => testNoUint8ArrayOutput(2, foobarBuffer, execaSync));modified:test/stdio/web-stream.js+41 added-39 removed
1+import assert from 'node:assert/strict';2 import {Readable} from 'node:stream';3 import {setImmediate} from 'node:timers/promises';3-import test from 'ava';4+import test from 'node:test';5+import {assertThrows, assertRejects} from '../helpers/assert.js';6 import {execa, execaSync} from '../../index.js';7 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';8 import {getStdio} from '../helpers/stdio.js';9 10 setFixtureDirectory();11 10-const testReadableStream = async (t, fdNumber) => {12+const 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 };17 16-test('stdin can be a ReadableStream', testReadableStream, 0);17-test('stdio[*] can be a ReadableStream', testReadableStream, 3);18+test('stdin can be a ReadableStream', () => testReadableStream(0));19+test('stdio[*] can be a ReadableStream', () => testReadableStream(3));20 19-const testWritableStream = async (t, fdNumber) => {21+const 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 };31 30-test('stdout can be a WritableStream', testWritableStream, 1);31-test('stderr can be a WritableStream', testWritableStream, 2);32-test('stdio[*] can be a WritableStream', testWritableStream, 3);32+test('stdout can be a WritableStream', () => testWritableStream(1));33+test('stderr can be a WritableStream', () => testWritableStream(2));34+test('stdio[*] can be a WritableStream', () => testWritableStream(3));35 34-const testWebStreamSync = (t, StreamClass, fdNumber, optionName) => {35- t.throws(() => {36+const 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 };41 40-test('stdin cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, 0, 'stdin');41-test('stdio[*] cannot be a ReadableStream - sync', testWebStreamSync, ReadableStream, 3, 'stdio[3]');42-test('stdout cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 1, 'stdout');43-test('stderr cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 2, 'stderr');44-test('stdio[*] cannot be a WritableStream - sync', testWebStreamSync, WritableStream, 3, 'stdio[3]');42+test('stdin cannot be a ReadableStream - sync', () => testWebStreamSync(ReadableStream, 0, 'stdin'));43+test('stdio[*] cannot be a ReadableStream - sync', () => testWebStreamSync(ReadableStream, 3, 'stdio[3]'));44+test('stdout cannot be a WritableStream - sync', () => testWebStreamSync(WritableStream, 1, 'stdout'));45+test('stderr cannot be a WritableStream - sync', () => testWebStreamSync(WritableStream, 2, 'stderr'));46+test('stdio[*] cannot be a WritableStream - sync', () => testWebStreamSync(WritableStream, 3, 'stdio[3]'));47 46-const testLongWritableStream = async (t, fdNumber) => {48+const 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 };59 58-test('stdout waits for WritableStream completion', testLongWritableStream, 1);59-test('stderr waits for WritableStream completion', testLongWritableStream, 2);60-test('stdio[*] waits for WritableStream completion', testLongWritableStream, 3);60+test('stdout waits for WritableStream completion', () => testLongWritableStream(1));61+test('stderr waits for WritableStream completion', () => testLongWritableStream(2));62+test('stdio[*] waits for WritableStream completion', () => testLongWritableStream(3));63 62-const testWritableStreamError = async (t, fdNumber) => {64+const 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 };74 73-test('stdout option handles errors in WritableStream', testWritableStreamError, 1);74-test('stderr option handles errors in WritableStream', testWritableStreamError, 2);75-test('stdio[*] option handles errors in WritableStream', testWritableStreamError, 3);75+test('stdout option handles errors in WritableStream', () => testWritableStreamError(1));76+test('stderr option handles errors in WritableStream', () => testWritableStreamError(2));77+test('stdio[*] option handles errors in WritableStream', () => testWritableStreamError(3));78 77-const testReadableStreamError = async (t, fdNumber) => {79+const 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 };89 88-test('stdin option handles errors in ReadableStream', testReadableStreamError, 0);89-test('stdio[*] option handles errors in ReadableStream', testReadableStreamError, 3);90+test('stdin option handles errors in ReadableStream', () => testReadableStreamError(0));91+test('stdio[*] option handles errors in ReadableStream', () => testReadableStreamError(3));92 91-test('ReadableStream with stdin is canceled on subprocess exit', async t => {93+test('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 });101 102 // 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.102-const testSharedReadableStream = async (t, fixtureArguments, stdio) => {104+const 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 };109 108-test('stdin can share a ReadableStream with stdio[*]', testSharedReadableStream, ['0'], ['shared', 'pipe', 'pipe', 'shared']);109-test('stdio[*] can share a ReadableStream with another stdio[*]', testSharedReadableStream, ['3'], ['pipe', 'pipe', 'pipe', 'shared', 'shared']);110+test('stdin can share a ReadableStream with stdio[*]', () => testSharedReadableStream(['0'], ['shared', 'pipe', 'pipe', 'shared']));111+test('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
1+import assert from 'node:assert/strict';2 import {promisify} from 'node:util';3 import {gunzip} from 'node:zlib';3-import test from 'ava';4+import test from 'node:test';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {foobarString, foobarUtf16Uint8Array, foobarUint8Array} from '../helpers/input.js';8 9 setFixtureDirectory();10 10-test('Can use CompressionStream()', async t => {11+test('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 });16 16-test('Can use TextDecoderStream()', async t => {17+test('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
1+import assert from 'node:assert/strict';2 import {once, getEventListeners} from 'node:events';2-import test from 'ava';3+import test from 'node:test';4+import {assertThrows, assertRejects} from '../helpers/assert.js';5 import {execa, execaSync} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {foobarString} from '../helpers/input.js';8 9 setFixtureDirectory();10 9-const testValidCancelSignal = (t, cancelSignal) => {10- t.throws(() => {11+const testValidCancelSignal = cancelSignal => {12+ assertThrows(() => {13 execa('empty.js', {cancelSignal});14 }, {message: /must be an AbortSignal/});15 };16 15-test('cancelSignal option cannot be AbortController', testValidCancelSignal, new AbortController());16-test('cancelSignal option cannot be {}', testValidCancelSignal, {});17-test('cancelSignal option cannot be null', testValidCancelSignal, null);18-test('cancelSignal option cannot be a symbol', testValidCancelSignal, Symbol('test'));17+test('cancelSignal option cannot be AbortController', () => testValidCancelSignal(new AbortController()));18+test('cancelSignal option cannot be {}', () => testValidCancelSignal({}));19+test('cancelSignal option cannot be null', () => testValidCancelSignal(null));20+test('cancelSignal option cannot be a symbol', () => testValidCancelSignal(Symbol('test')));21 20-test('result.isCanceled is false when abort isn\'t called (success)', async t => {22+test('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 });27 26-test('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);28+test('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 });33 32-test('result.isCanceled is false when abort isn\'t called in sync mode (success)', t => {34+test('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 });39 38-test('result.isCanceled is false when abort isn\'t called in sync mode (failure)', t => {39- const {isCanceled, isGracefullyCanceled} = t.throws(() => {40+test('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 });47 46-const testCancelSuccess = async (t, options) => {48+const 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 };56 55-test('error.isCanceled is true when abort is used', testCancelSuccess, {});56-test('gracefulCancel can be false with cancelSignal', testCancelSuccess, {gracefulCancel: false});57-test('ipc can be false with cancelSignal', testCancelSuccess, {ipc: false});58-test('serialization can be "json" with cancelSignal', testCancelSuccess, {ipc: true, serialization: 'json'});57+test('error.isCanceled is true when abort is used', () => testCancelSuccess({}));58+test('gracefulCancel can be false with cancelSignal', () => testCancelSuccess({gracefulCancel: false}));59+test('ipc can be false with cancelSignal', () => testCancelSuccess({ipc: false}));60+test('serialization can be "json" with cancelSignal', () => testCancelSuccess({ipc: true, serialization: 'json'}));61 60-test('error.isCanceled is false when kill method is used', async t => {62+test('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 });70 69-test('calling abort is considered a signal termination', async t => {71+test('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 });82 81-test('cancelSignal can already be aborted', async t => {83+test('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 });92 91-test('calling abort does not emit the "error" event', async t => {93+test('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 });106 105-test('calling abort cleans up listeners on cancelSignal, called', async t => {107+test('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 });117 116-test('calling abort cleans up listeners on cancelSignal, not called', async t => {118+test('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 });125 124-test('calling abort cleans up listeners on cancelSignal, already aborted', async t => {126+test('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 });135 134-test('calling abort throws an error with message "Command was canceled"', async t => {136+test('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 });142 141-test('calling abort with no argument keeps error properties', async t => {143+test('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 });154 153-test('calling abort with an error instance keeps error properties', async t => {155+test('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 });168 167-test('calling abort with null keeps error properties', async t => {169+test('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 });179 178-test('calling abort twice should show the same behaviour as calling it once', async t => {180+test('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 });189 188-test('calling abort on a successfully completed subprocess does not make result.isCanceled true', async t => {190+test('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 });198 197-test('Throws when using the former "signal" option name', t => {199+test('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 });205 204-test('Throws when using the former "signal" option name, sync', t => {206+test('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 });212 211-test('Cannot use cancelSignal, sync', t => {213+test('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
1+import assert from 'node:assert/strict';2 import process from 'node:process';3 import {setTimeout} from 'node:timers/promises';3-import test from 'ava';4+import test from 'node:test';5 import isRunning from 'is-running';6+import {assertThrows, assertRejects} from '../helpers/assert.js';7 import {execa, execaSync} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 import {nestedSubprocess} from '../helpers/nested.js';10 import {foobarString} from '../helpers/input.js';2 unmodified lines13 14 const isWindows = process.platform === 'win32';15 16 // When subprocess exits before current process15-const spawnAndExit = async (t, worker, cleanup, detached) => {17+const 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 };21 20-test('spawnAndExit', spawnAndExit, false, false, false);21-test('spawnAndExit cleanup', spawnAndExit, false, true, false);22-test('spawnAndExit detached', spawnAndExit, false, false, true);23-test('spawnAndExit cleanup detached', spawnAndExit, false, true, true);24-test('spawnAndExit, worker', spawnAndExit, true, false, false);25-test('spawnAndExit cleanup, worker', spawnAndExit, true, true, false);26-test('spawnAndExit detached, worker', spawnAndExit, true, false, true);27-test('spawnAndExit cleanup detached, worker', spawnAndExit, true, true, true);22+test('spawnAndExit', () => spawnAndExit(false, false, false));23+test('spawnAndExit cleanup', () => spawnAndExit(false, true, false));24+test('spawnAndExit detached', () => spawnAndExit(false, false, true));25+test('spawnAndExit cleanup detached', () => spawnAndExit(false, true, true));26+test('spawnAndExit, worker', () => spawnAndExit(true, false, false));27+test('spawnAndExit cleanup, worker', () => spawnAndExit(true, true, false));28+test('spawnAndExit detached, worker', () => spawnAndExit(true, false, true));29+test('spawnAndExit cleanup detached, worker', () => spawnAndExit(true, true, true));30 31 // When current process exits before subprocess30-const spawnAndKill = async (t, [signal, cleanup, detached, isKilled]) => {32+const spawnAndKill = async ([signal, cleanup, detached, isKilled]) => {33 const subprocess = execa('ipc-send-pid.js', [cleanup, detached], {stdio: 'ignore', ipc: true});34 35 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));38 39 process.kill(subprocess.pid, signal);40 39- await t.throwsAsync(subprocess);40- t.false(isRunning(subprocess.pid));41+ await assertRejects(subprocess);42+ assert.ok(!isRunning(subprocess.pid));43 44 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 lines65 // 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 handled67-test('spawnAndKill SIGTERM', spawnAndKill, ['SIGTERM', false, false, isWindows]);68-test('spawnAndKill SIGKILL', spawnAndKill, ['SIGKILL', false, false, isWindows]);69-test('spawnAndKill cleanup SIGTERM', spawnAndKill, ['SIGTERM', true, false, true]);70-test('spawnAndKill cleanup SIGKILL', spawnAndKill, ['SIGKILL', true, false, isWindows]);71-test('spawnAndKill detached SIGTERM', spawnAndKill, ['SIGTERM', false, true, false]);72-test('spawnAndKill detached SIGKILL', spawnAndKill, ['SIGKILL', false, true, false]);73-test('spawnAndKill cleanup detached SIGTERM', spawnAndKill, ['SIGTERM', true, true, false]);74-test('spawnAndKill cleanup detached SIGKILL', spawnAndKill, ['SIGKILL', true, true, false]);69+test('spawnAndKill SIGTERM', () => spawnAndKill(['SIGTERM', false, false, isWindows]));70+test('spawnAndKill SIGKILL', () => spawnAndKill(['SIGKILL', false, false, isWindows]));71+test('spawnAndKill cleanup SIGTERM', () => spawnAndKill(['SIGTERM', true, false, true]));72+test('spawnAndKill cleanup SIGKILL', () => spawnAndKill(['SIGKILL', true, false, isWindows]));73+test('spawnAndKill detached SIGTERM', () => spawnAndKill(['SIGTERM', false, true, false]));74+test('spawnAndKill detached SIGKILL', () => spawnAndKill(['SIGKILL', false, true, false]));75+test('spawnAndKill cleanup detached SIGTERM', () => spawnAndKill(['SIGTERM', true, true, false]));76+test('spawnAndKill cleanup detached SIGKILL', () => spawnAndKill(['SIGKILL', true, true, false]));77 78 if (!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});81 82 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));85 86 process.kill(subprocess.pid, 'SIGTERM');87 86- 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 }96 97 // See #12896-test('removes exit handler on exit', async t => {98+test('removes exit handler on exit', async () => {99 // @todo this relies on `signal-exit` internals100 const exitListeners = globalThis[Symbol.for('signal-exit emitter')].listeners.exit;101 102 const subprocess = execa('noop.js');103 const listener = exitListeners.at(-1);104 105 await subprocess;104- t.false(exitListeners.includes(listener));106+ assert.ok(!exitListeners.includes(listener));107 });108 107-test('detach subprocess', async t => {109+test('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));114 115 process.kill(pid, 'SIGKILL');116 });117 116-test('Cannot use "detached" option, sync', t => {117- t.throws(() => {118+test('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
1+import assert from 'node:assert/strict';2 import {setTimeout} from 'node:timers/promises';2-import test from 'ava';3+import test from 'node:test';4+import {assertThrows, assertRejects} from '../helpers/assert.js';5 import {execa} from '../../index.js';6 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';7 import {foobarString} from '../helpers/input.js';8 import {mockSendIoError} from '../helpers/ipc.js';9 10 setFixtureDirectory();11 10-test('cancelSignal cannot be undefined with gracefulCancel', t => {11- t.throws(() => {12+test('cancelSignal cannot be undefined with gracefulCancel', () => {13+ assertThrows(() => {14 execa('empty.js', {gracefulCancel: true});15 }, {message: /The `cancelSignal` option must be defined/});16 });17 16-test('ipc cannot be false with gracefulCancel', t => {17- t.throws(() => {18+test('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 });23 22-test('serialization cannot be "json" with gracefulCancel', t => {23- t.throws(() => {24+test('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 });29 28-test('Current process can send a message right away', async t => {30+test('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 });37 36-test('Current process can receive a message right away', async t => {38+test('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 });45 44-test('Does not disconnect during I/O errors when sending the abort reason', async t => {46+test('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 });61 62 class AbortError extends Error {63 name = 'AbortError';64 }65 64-test('Abort reason is sent to the subprocess', async t => {66+test('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 });81 80-test('Abort default reason is sent to the subprocess', async t => {82+test('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 });96 95-test('Fail when sending non-serializable abort reason', async t => {97+test('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 });113 112-test('timeout does not use graceful cancelSignal', async t => {114+test('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 });126 125-test('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');127+test('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 });136 135-test('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');137+test('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 });147 146-test('error on graceful cancelSignal on non-forceful termination', async t => {148+test('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 });161 160-test('`forceKillAfterDelay: false` with the "cancelSignal" option when graceful', async t => {162+test('`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 });175 174-test('subprocess.getCancelSignal() is not defined', async t => {176+test('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
1+import assert from 'node:assert/strict';2 import childProcess from 'node:child_process';3 import {syncBuiltinESMExports} from 'node:module';4 import path from 'node:path/win32';5 import process from 'node:process';6 import {setTimeout} from 'node:timers/promises';6-import test from 'ava';7+import test from 'node:test';8 import isRunning from 'is-running';9+import {assertThrows, assertRejects} from '../helpers/assert.js';10 import {execa, execaSync} from '../../index.js';11 import {getTaskkillFile} from '../../lib/terminate/kill-descendants.js';12 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';13 19 unmodified lines33 const descendantPid = await subprocess.getOneMessage();34 return {subprocess, descendantPid};35 };36 35-test('killDescendants terminates descendant processes', async t => {37+test('killDescendants terminates descendant processes', async () => {38 const {subprocess, descendantPid} = await spawnDescendant(true);37- t.true(isRunning(descendantPid));39+ assert.ok(isRunning(descendantPid));40 41 subprocess.kill();40- await t.throwsAsync(subprocess);41- t.false(isRunning(subprocess.pid));42+ await assertRejects(subprocess);43+ assert.ok(!isRunning(subprocess.pid));44 45 await Promise.race([46 setTimeout(1e4, undefined, {ref: false}),47 pollForSubprocessExit(descendantPid),48 ]);47- t.false(isRunning(descendantPid));49+ assert.ok(!isRunning(descendantPid));50 });51 50-test('killDescendants also terminates descendant processes when the subprocess times out', async t => {52+test('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));55 54- const {timedOut} = await t.throwsAsync(subprocess);55- t.true(timedOut);56+ const {timedOut} = await assertRejects(subprocess);57+ assert.equal(timedOut, true);58 59 await Promise.race([60 setTimeout(1e4, undefined, {ref: false}),61 pollForSubprocessExit(descendantPid),62 ]);61- t.false(isRunning(descendantPid));63+ assert.ok(!isRunning(descendantPid));64 });65 66 // On Windows, terminating the direct subprocess already terminates its descendants, so this67 // only asserts the default Unix behavior of leaving descendants running.68 if (!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));72 73 subprocess.kill();72- await t.throwsAsync(subprocess);73- t.false(isRunning(subprocess.pid));74+ await assertRejects(subprocess);75+ assert.ok(!isRunning(subprocess.pid));76 75- t.true(isRunning(descendantPid));77+ assert.ok(isRunning(descendantPid));78 process.kill(descendantPid, 'SIGKILL');79 });80 79- 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));84 83- 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 line93 The `forceKillAfterDelay` escalation happens after the subprocess exited, since that is when its termination has been noticed.94 A descendant which ignores `SIGTERM` is still running then, so the escalation must still reach it.95 Otherwise, since that descendant keeps the subprocess' `stdout` open, awaiting the subprocess would never settle.96 */95-test('killDescendants escalates to descendants which outlive the subprocess', async t => {97+test('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));105 106 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 });114 115 if (!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);121 119- const originalKill = process.kill;120- t.teardown(() => {121- process.kill = originalKill;122- });123-124- const signaledProcesses = [];125- process.kill = (pid, signal) => {126- signaledProcesses.push([pid, signal]);127- return true;128- };129-130- 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 });132 134- test.serial('killDescendants does not signal the process group once Execa is done with the subprocess', testAbandonedProcessGroup, () => execa('fail.js', {killDescendants: true}));135-136- 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 });139 140 // 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});143 144 const originalKill = process.kill;147- t.teardown(() => {145+ t.after(() => {146 process.kill = originalKill;147 });148 149 const signaledProcesses = [];1 unmodified line151 signaledProcesses.push([pid, signal]);152 return originalKill(pid, signal);153 };154 157- 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 }161 164-test('Cannot use "killDescendants" option, sync', t => {165- t.throws(() => {162+test('Cannot use "killDescendants" option, sync', () => {163+ assertThrows(() => {164 execaSync('empty.js', {killDescendants: true});165 }, {message: /The "killDescendants: true" option cannot be used/});166 });167 170-test.serial('taskkill is resolved from the Windows directory when available', t => {168+test('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 });174 175 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'));178 179 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'));181 182 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'));184 185 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'));187 188 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'));190 191 process.env.windir = 'Windows';194- t.is(getTaskkillFile(), undefined);192+ assert.equal(getTaskkillFile(), undefined);193 194 process.env.windir = '\\Windows';197- t.is(getTaskkillFile(), undefined);195+ assert.equal(getTaskkillFile(), undefined);196 197 process.env.windir = '\\\\server\\share\\Windows';200- t.is(getTaskkillFile(), undefined);198+ assert.equal(getTaskkillFile(), undefined);199 200 process.env.windir = '';203- t.is(getTaskkillFile(), undefined);201+ assert.equal(getTaskkillFile(), undefined);202 203 delete process.env.windir;206- t.is(getTaskkillFile(), undefined);204+ assert.equal(getTaskkillFile(), undefined);205 });206 207 /*208 The `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 lines213 const 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 lines246 };247 return subprocess;248 };249 252-const abortedController = () => {253- const controller = new AbortController();254- controller.abort();255- return controller;256-};257-258-test.serial('taskkill fallback uses direct subprocess kill when Windows directory is unavailable', async t => {250+test('taskkill fallback uses direct subprocess kill when Windows directory is unavailable', async t => {251 const getKillFunction = await fakeWindows(t, 'Windows');252 const subprocess = createFakeSubprocess();253 262- 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 });258 267-test.serial('taskkill fallback uses direct subprocess kill when taskkill cannot be spawned', async t => {259+test('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();270 279- 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);274 275 await taskkillFailure.promise;284- t.is(subprocess.killedWith, 'SIGTERM');276+ assert.equal(subprocess.killedWith, 'SIGTERM');277 });278 287-// Once Execa is done with the subprocess, its PID can be re-assigned by the OS, so its process tree must not be terminated anymore288-test.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 it280+test('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});286 295- 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 });292 301-// While Execa is still waiting on the subprocess, its process tree is still its own, even after it exited302-test.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});308-309- const kill = getKillFunction(subprocess, {killDescendants: true}, new AbortController());310- t.true(kill('SIGTERM'));311- t.deepEqual(taskkillArguments, ['/pid', '123', '/T', '/F']);312-});313-293 // A subprocess which never spawned has no PID to signal315-test.serial('taskkill is not spawned when the subprocess has no PID', async t => {294+test('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;301 323- 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 });307 308 const restoreEnvironment = (name, value) => {309 if (value === undefined) {5 unmodified linesmodified:test/terminate/kill-error.js+40 added-38 removed
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {setImmediate} from 'node:timers/promises';3-import test from 'ava';4+import test from 'node:test';5 import isRunning from 'is-running';6+import {assertRejects} from '../helpers/assert.js';7 import {execa} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 10 setFixtureDirectory();11 10-test('.kill(error) propagates error', async t => {12+test('.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 });27 26-test('.kill(error) uses killSignal', async t => {28+test('.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 });36 35-test('.kill(signal, error) uses signal', async t => {37+test('.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 });45 44-test('.kill(error) is a noop if subprocess already exited', async t => {46+test('.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 });52 51-test('.kill(error) terminates but does not change the error if the subprocess already errored but did not exit yet', async t => {53+test('.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 });67 66-test('.kill(error) twice in a row', async t => {68+test('.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 });78 77-test('.kill(error) does not emit the "error" event', async t => {79+test('.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
1+import assert from 'node:assert/strict';2 import process from 'node:process';3 import {once, defaultMaxListeners} from 'node:events';4 import {constants} from 'node:os';5 import {setTimeout} from 'node:timers/promises';5-import test from 'ava';6+import test from 'node:test';7 import isRunning from 'is-running';8+import {assertThrows, assertRejects} from '../helpers/assert.js';9 import {execa} from '../../index.js';10 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';11 import {assertMaxListeners} from '../helpers/listeners.js';12 import {foobarString} from '../helpers/input.js';15 unmodified lines28 29 const noKillableSimpleOptions = {killSignal: 'SIGWINCH', forceKillAfterDelay: 1};30 const spawnNoKillableSimple = options => execa('forever.js', {...noKillableSimpleOptions, ...options});31 30-test('kill("SIGKILL") should terminate cleanly', async t => {32+test('kill("SIGKILL") should terminate cleanly', async () => {33 const {subprocess} = await spawnNoKillable();34 35 subprocess.kill('SIGKILL');36 35- 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 });43 42-const testInvalidForceKill = async (t, forceKillAfterDelay) => {43- t.throws(() => {44+const testInvalidForceKill = async forceKillAfterDelay => {45+ assertThrows(() => {46 execa('empty.js', {forceKillAfterDelay});47 }, {instanceOf: TypeError, message: /non-negative integer/});48 };49 48-test('`forceKillAfterDelay` should not be NaN', testInvalidForceKill, NaN);49-test('`forceKillAfterDelay` should not be negative', testInvalidForceKill, -1);50+test('`forceKillAfterDelay` should not be NaN', () => testInvalidForceKill(NaN));51+test('`forceKillAfterDelay` should not be negative', () => testInvalidForceKill(-1));52 53 // `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.55 if (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();59 58- 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);69 70 subprocess.kill(killArgument);71 72 await setTimeout(6e3);71- t.true(isRunning(subprocess.pid));73+ assert.ok(isRunning(subprocess.pid));74 subprocess.kill('SIGKILL');75 74- 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 };81 80- 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}));86 87 // 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);90 91 subprocess.kill(killSignal);92 91- 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 };101 100- 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'}));112 111- 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 });126 125- 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 });135 134- 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 });147 146- 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 });163 162- 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();166 167 const subprocess = spawnNoKillableSimple();168 for (let index = 0; index < defaultMaxListeners + 1; index += 1) {169 subprocess.kill();170 }171 170- 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);176 177 checkMaxListeners();178 });179 178- 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();184 183- 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 }191 190-test('result.isForcefullyTerminated is false on success', async t => {192+test('result.isForcefullyTerminated is false on success', async () => {193 const {isForcefullyTerminated} = await execa('empty.js');192- t.false(isForcefullyTerminated);194+ assert.equal(isForcefullyTerminated, false);195 });196 195-test('error.isForcefullyTerminated is false on spawn errors', async t => {196- const {isForcefullyTerminated} = await t.throwsAsync(getEarlyErrorSubprocess());197- t.false(isForcefullyTerminated);197+test('error.isForcefullyTerminated is false on spawn errors', async () => {198+ const {isForcefullyTerminated} = await assertRejects(getEarlyErrorSubprocess());199+ assert.equal(isForcefullyTerminated, false);200 });201 200-test('error.isForcefullyTerminated is false when already terminated', async t => {202+test('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 lines212 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
1+import assert from 'node:assert/strict';2 import {once} from 'node:events';3 import {constants} from 'node:os';4 import {setImmediate} from 'node:timers/promises';4-import test from 'ava';5+import test from 'node:test';6+import {assertThrows, assertRejects} from '../helpers/assert.js';7 import {execa, execaSync} from '../../index.js';8 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';9 10 setFixtureDirectory();11 10-const 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');12+const 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 };17 16-test('Can use killSignal: "SIGINT"', testKillSignal, 'SIGINT');17-test('Can use killSignal: 2', testKillSignal, constants.signals.SIGINT);18+test('Can use killSignal: "SIGINT"', () => testKillSignal('SIGINT'));19+test('Can use killSignal: 2', () => testKillSignal(constants.signals.SIGINT));20 19-const testKillSignalSync = (t, killSignal) => {20- const {isTerminated, signal} = t.throws(() => {21+const 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 };28 27-test('Can use killSignal: "SIGINT", sync', testKillSignalSync, 'SIGINT');28-test('Can use killSignal: 2, sync', testKillSignalSync, constants.signals.SIGINT);29+test('Can use killSignal: "SIGINT", sync', () => testKillSignalSync('SIGINT'));30+test('Can use killSignal: 2, sync', () => testKillSignalSync(constants.signals.SIGINT));31 30-test('Can call .kill("SIGTERM")', async t => {32+test('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 });39 38-test('Can call .kill(15)', async t => {40+test('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 });47 46-test('Can call .kill(0)', async t => {48+test('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 });55 54-test('Can call `.kill()` multiple times', async t => {56+test('Can call `.kill()` multiple times', async () => {57 const subprocess = execa('forever.js');58 subprocess.kill();59 subprocess.kill();60 59- 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 });67 66-test('execa() returns a promise with kill()', async t => {68+test('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 });73 72-const testInvalidKillArgument = async (t, killArgument, secondKillArgument) => {74+const 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 };84 83-test('Cannot call .kill(errorObject)', testInvalidKillArgument, {name: '', message: '', stack: ''});84-test('Cannot call .kill(errorArray)', testInvalidKillArgument, [new Error('test')]);85-test('Cannot call .kill(undefined, true)', testInvalidKillArgument, undefined, true);86-test('Cannot call .kill("SIGTERM", true)', testInvalidKillArgument, 'SIGTERM', true);87-test('Cannot call .kill(true, error)', testInvalidKillArgument, true, new Error('test'));85+test('Cannot call .kill(errorObject)', () => testInvalidKillArgument({name: '', message: '', stack: ''}));86+test('Cannot call .kill(errorArray)', () => testInvalidKillArgument([new Error('test')]));87+test('Cannot call .kill(undefined, true)', () => testInvalidKillArgument(undefined, true));88+test('Cannot call .kill("SIGTERM", true)', () => testInvalidKillArgument('SIGTERM', true));89+test('Cannot call .kill(true, error)', () => testInvalidKillArgument(true, new Error('test')));90 89-test('subprocess errors are handled before spawn', async t => {91+test('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 });102 101-test('subprocess errors are handled after spawn', async t => {103+test('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 });115 114-test('subprocess double errors are handled after spawn', async t => {116+test('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 });131 130-test('subprocess errors use killSignal', async t => {132+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 7 setFixtureDirectory();5 unmodified lines13 rename: 'please rename it to',14 zero: '0 cannot be used',15 };16 15-const validateMessage = (t, message, type) => {16- t.true(message.includes(VALIDATION_MESSAGES[type]));17+const validateMessage = (message, type) => {18+ assert.ok(message.includes(VALIDATION_MESSAGES[type]));19 18- 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 }23+24+ assert.ok(message.includes('Available signal names: \'SIGABRT\', '));25+ assert.ok(message.includes('Available signal numbers: 1, '));26 };27 24-const testInvalidKillSignal = (t, killSignal, type, execaMethod) => {25- const {message} = t.throws(() => {28+const 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 };35 32-test('Cannot use killSignal: "SIGOTHER"', testInvalidKillSignal, 'SIGOTHER', 'string', execa);33-test('Cannot use killSignal: "Sigterm"', testInvalidKillSignal, 'Sigterm', 'rename', execa);34-test('Cannot use killSignal: "sigterm"', testInvalidKillSignal, 'sigterm', 'rename', execa);35-test('Cannot use killSignal: -1', testInvalidKillSignal, -1, 'integer', execa);36-test('Cannot use killSignal: 200', testInvalidKillSignal, 200, 'integer', execa);37-test('Cannot use killSignal: 1n', testInvalidKillSignal, 1n, 'other', execa);38-test('Cannot use killSignal: 1.5', testInvalidKillSignal, 1.5, 'other', execa);39-test('Cannot use killSignal: Infinity', testInvalidKillSignal, Infinity, 'other', execa);40-test('Cannot use killSignal: NaN', testInvalidKillSignal, NaN, 'other', execa);41-test('Cannot use killSignal: false', testInvalidKillSignal, false, 'other', execa);42-test('Cannot use killSignal: null', testInvalidKillSignal, null, 'other', execa);43-test('Cannot use killSignal: symbol', testInvalidKillSignal, Symbol('test'), 'other', execa);44-test('Cannot use killSignal: {}', testInvalidKillSignal, {}, 'other', execa);45-test('Cannot use killSignal: 0', testInvalidKillSignal, 0, 'zero', execa);46-test('Cannot use killSignal: "SIGOTHER", sync', testInvalidKillSignal, 'SIGOTHER', 'string', execaSync);47-test('Cannot use killSignal: "Sigterm", sync', testInvalidKillSignal, 'Sigterm', 'rename', execaSync);48-test('Cannot use killSignal: "sigterm", sync', testInvalidKillSignal, 'sigterm', 'rename', execaSync);49-test('Cannot use killSignal: -1, sync', testInvalidKillSignal, -1, 'integer', execaSync);50-test('Cannot use killSignal: 200, sync', testInvalidKillSignal, 200, 'integer', execaSync);51-test('Cannot use killSignal: 1.5, sync', testInvalidKillSignal, 1.5, 'other', execaSync);52-test('Cannot use killSignal: Infinity, sync', testInvalidKillSignal, Infinity, 'other', execaSync);53-test('Cannot use killSignal: NaN, sync', testInvalidKillSignal, NaN, 'other', execaSync);54-test('Cannot use killSignal: null, sync', testInvalidKillSignal, null, 'other', execaSync);55-test('Cannot use killSignal: symbol, sync', testInvalidKillSignal, Symbol('test'), 'other', execaSync);56-test('Cannot use killSignal: {}, sync', testInvalidKillSignal, {}, 'other', execaSync);57-test('Cannot use killSignal: 0, sync', testInvalidKillSignal, 0, 'zero', execaSync);36+test('Cannot use killSignal: "SIGOTHER"', () => testInvalidKillSignal('SIGOTHER', 'string', execa));37+test('Cannot use killSignal: "Sigterm"', () => testInvalidKillSignal('Sigterm', 'rename', execa));38+test('Cannot use killSignal: "sigterm"', () => testInvalidKillSignal('sigterm', 'rename', execa));39+test('Cannot use killSignal: -1', () => testInvalidKillSignal(-1, 'integer', execa));40+test('Cannot use killSignal: 200', () => testInvalidKillSignal(200, 'integer', execa));41+test('Cannot use killSignal: 1n', () => testInvalidKillSignal(1n, 'other', execa));42+test('Cannot use killSignal: 1.5', () => testInvalidKillSignal(1.5, 'other', execa));43+test('Cannot use killSignal: Infinity', () => testInvalidKillSignal(Infinity, 'other', execa));44+test('Cannot use killSignal: NaN', () => testInvalidKillSignal(NaN, 'other', execa));45+test('Cannot use killSignal: false', () => testInvalidKillSignal(false, 'other', execa));46+test('Cannot use killSignal: null', () => testInvalidKillSignal(null, 'other', execa));47+test('Cannot use killSignal: symbol', () => testInvalidKillSignal(Symbol('test'), 'other', execa));48+test('Cannot use killSignal: {}', () => testInvalidKillSignal({}, 'other', execa));49+test('Cannot use killSignal: 0', () => testInvalidKillSignal(0, 'zero', execa));50+test('Cannot use killSignal: "SIGOTHER", sync', () => testInvalidKillSignal('SIGOTHER', 'string', execaSync));51+test('Cannot use killSignal: "Sigterm", sync', () => testInvalidKillSignal('Sigterm', 'rename', execaSync));52+test('Cannot use killSignal: "sigterm", sync', () => testInvalidKillSignal('sigterm', 'rename', execaSync));53+test('Cannot use killSignal: -1, sync', () => testInvalidKillSignal(-1, 'integer', execaSync));54+test('Cannot use killSignal: 200, sync', () => testInvalidKillSignal(200, 'integer', execaSync));55+test('Cannot use killSignal: 1.5, sync', () => testInvalidKillSignal(1.5, 'other', execaSync));56+test('Cannot use killSignal: Infinity, sync', () => testInvalidKillSignal(Infinity, 'other', execaSync));57+test('Cannot use killSignal: NaN, sync', () => testInvalidKillSignal(NaN, 'other', execaSync));58+test('Cannot use killSignal: null, sync', () => testInvalidKillSignal(null, 'other', execaSync));59+test('Cannot use killSignal: symbol, sync', () => testInvalidKillSignal(Symbol('test'), 'other', execaSync));60+test('Cannot use killSignal: {}, sync', () => testInvalidKillSignal({}, 'other', execaSync));61+test('Cannot use killSignal: 0, sync', () => testInvalidKillSignal(0, 'zero', execaSync));62 59-const testInvalidSignalArgument = async (t, signal, type) => {63+const testInvalidSignalArgument = async (signal, type) => {64 const subprocess = execa('empty.js');61- const {message} = t.throws(() => {65+ const {message} = assertThrows(() => {66 subprocess.kill(signal);67 });68 69 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 }75 76 await subprocess;77 };78 75-test('Cannot use subprocess.kill("SIGOTHER")', testInvalidSignalArgument, 'SIGOTHER', 'string');76-test('Cannot use subprocess.kill("Sigterm")', testInvalidSignalArgument, 'Sigterm', 'rename');77-test('Cannot use subprocess.kill("sigterm")', testInvalidSignalArgument, 'sigterm', 'rename');78-test('Cannot use subprocess.kill(-1)', testInvalidSignalArgument, -1, 'integer');79-test('Cannot use subprocess.kill(200)', testInvalidSignalArgument, 200, 'integer');80-test('Cannot use subprocess.kill(1n)', testInvalidSignalArgument, 1n, 'other');81-test('Cannot use subprocess.kill(1.5)', testInvalidSignalArgument, 1.5, 'other');82-test('Cannot use subprocess.kill(Infinity)', testInvalidSignalArgument, Infinity, 'other');83-test('Cannot use subprocess.kill(NaN)', testInvalidSignalArgument, NaN, 'other');84-test('Cannot use subprocess.kill(false)', testInvalidSignalArgument, false, 'other');85-test('Cannot use subprocess.kill(null)', testInvalidSignalArgument, null, 'other');86-test('Cannot use subprocess.kill(symbol)', testInvalidSignalArgument, Symbol('test'), 'other');87-test('Cannot use subprocess.kill({})', testInvalidSignalArgument, {}, 'other');79+test('Cannot use subprocess.kill("SIGOTHER")', () => testInvalidSignalArgument('SIGOTHER', 'string'));80+test('Cannot use subprocess.kill("Sigterm")', () => testInvalidSignalArgument('Sigterm', 'rename'));81+test('Cannot use subprocess.kill("sigterm")', () => testInvalidSignalArgument('sigterm', 'rename'));82+test('Cannot use subprocess.kill(-1)', () => testInvalidSignalArgument(-1, 'integer'));83+test('Cannot use subprocess.kill(200)', () => testInvalidSignalArgument(200, 'integer'));84+test('Cannot use subprocess.kill(1n)', () => testInvalidSignalArgument(1n, 'other'));85+test('Cannot use subprocess.kill(1.5)', () => testInvalidSignalArgument(1.5, 'other'));86+test('Cannot use subprocess.kill(Infinity)', () => testInvalidSignalArgument(Infinity, 'other'));87+test('Cannot use subprocess.kill(NaN)', () => testInvalidSignalArgument(NaN, 'other'));88+test('Cannot use subprocess.kill(false)', () => testInvalidSignalArgument(false, 'other'));89+test('Cannot use subprocess.kill(null)', () => testInvalidSignalArgument(null, 'other'));90+test('Cannot use subprocess.kill(symbol)', () => testInvalidSignalArgument(Symbol('test'), 'other'));91+test('Cannot use subprocess.kill({})', () => testInvalidSignalArgument({}, 'other'));modified:test/terminate/timeout.js+42 added-40 removed
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3+import {assertThrows, assertRejects} from '../helpers/assert.js';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';6 7 setFixtureDirectory();8 7-test('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);9+test('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 });18 17-test('timeout kills the subprocess if it times out, in sync mode', async t => {18- const {isTerminated, signal, timedOut, originalMessage, shortMessage, message} = await t.throws(() => {19+test('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 });31 30-test('timeout does not kill the subprocess if it does not time out', async t => {32+test('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 });36 35-test('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);37+test('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 });43 44 const INVALID_TIMEOUT_REGEXP = /`timeout` option to be a non-negative integer/;45 44-const testTimeoutValidation = (t, timeout, execaMethod) => {45- t.throws(() => {46+const testTimeoutValidation = (timeout, execaMethod) => {47+ assertThrows(() => {48 execaMethod('empty.js', {timeout});49 }, {message: INVALID_TIMEOUT_REGEXP});50 };51 50-test('timeout must not be negative', testTimeoutValidation, -1, execa);51-test('timeout must be an integer', testTimeoutValidation, false, execa);52-test('timeout must not be negative - sync', testTimeoutValidation, -1, execaSync);53-test('timeout must be an integer - sync', testTimeoutValidation, false, execaSync);52+test('timeout must not be negative', () => testTimeoutValidation(-1, execa));53+test('timeout must be an integer', () => testTimeoutValidation(false, execa));54+test('timeout must not be negative - sync', () => testTimeoutValidation(-1, execaSync));55+test('timeout must be an integer - sync', () => testTimeoutValidation(false, execaSync));56 55-test('timedOut is false if timeout is undefined', async t => {57+test('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 });61 60-test('timedOut is false if timeout is 0', async t => {62+test('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 });66 65-test('timedOut is false if timeout is undefined and exit code is 0 in sync mode', t => {67+test('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 });71 70-test('timedOut is false if the timeout happened after a different error occurred', async t => {72+test('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
1+import assert from 'node:assert/strict';2 import {Buffer} from 'node:buffer';3 import {exec} from 'node:child_process';4 import {promisify} from 'node:util';4-import test from 'ava';5+import test from 'node:test';6 import getStream from 'get-stream';7 import {execa, execaSync} from '../../index.js';8 import {setFixtureDirectory, FIXTURES_DIRECTORY} from '../helpers/fixtures-directory.js';9 import {fullStdio} from '../helpers/stdio.js';2 unmodified lines12 const pExec = promisify(exec);13 14 setFixtureDirectory();15 15-const checkEncoding = async (t, encoding, fdNumber, execaMethod) => {16+const 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);19 20 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 }26 27 if (fdNumber === 3) {28 return;29 }30 31 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 };34 34-const compareValues = (t, value, encoding) => {35+const 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 };43 44 // This string gives different outputs with each encoding type45 const STRING_TO_ENCODE = '\u{1000}.';46 const BUFFER_TO_ENCODE = Buffer.from(STRING_TO_ENCODE);47 47-test('can pass encoding "buffer" to stdout', checkEncoding, 'buffer', 1, execa);48-test('can pass encoding "utf8" to stdout', checkEncoding, 'utf8', 1, execa);49-test('can pass encoding "utf16le" to stdout', checkEncoding, 'utf16le', 1, execa);50-test('can pass encoding "latin1" to stdout', checkEncoding, 'latin1', 1, execa);51-test('can pass encoding "ascii" to stdout', checkEncoding, 'ascii', 1, execa);52-test('can pass encoding "hex" to stdout', checkEncoding, 'hex', 1, execa);53-test('can pass encoding "base64" to stdout', checkEncoding, 'base64', 1, execa);54-test('can pass encoding "base64url" to stdout', checkEncoding, 'base64url', 1, execa);55-test('can pass encoding "buffer" to stderr', checkEncoding, 'buffer', 2, execa);56-test('can pass encoding "utf8" to stderr', checkEncoding, 'utf8', 2, execa);57-test('can pass encoding "utf16le" to stderr', checkEncoding, 'utf16le', 2, execa);58-test('can pass encoding "latin1" to stderr', checkEncoding, 'latin1', 2, execa);59-test('can pass encoding "ascii" to stderr', checkEncoding, 'ascii', 2, execa);60-test('can pass encoding "hex" to stderr', checkEncoding, 'hex', 2, execa);61-test('can pass encoding "base64" to stderr', checkEncoding, 'base64', 2, execa);62-test('can pass encoding "base64url" to stderr', checkEncoding, 'base64url', 2, execa);63-test('can pass encoding "buffer" to stdio[*]', checkEncoding, 'buffer', 3, execa);64-test('can pass encoding "utf8" to stdio[*]', checkEncoding, 'utf8', 3, execa);65-test('can pass encoding "utf16le" to stdio[*]', checkEncoding, 'utf16le', 3, execa);66-test('can pass encoding "latin1" to stdio[*]', checkEncoding, 'latin1', 3, execa);67-test('can pass encoding "ascii" to stdio[*]', checkEncoding, 'ascii', 3, execa);68-test('can pass encoding "hex" to stdio[*]', checkEncoding, 'hex', 3, execa);69-test('can pass encoding "base64" to stdio[*]', checkEncoding, 'base64', 3, execa);70-test('can pass encoding "base64url" to stdio[*]', checkEncoding, 'base64url', 3, execa);71-test('can pass encoding "buffer" to stdout - sync', checkEncoding, 'buffer', 1, execaSync);72-test('can pass encoding "utf8" to stdout - sync', checkEncoding, 'utf8', 1, execaSync);73-test('can pass encoding "utf16le" to stdout - sync', checkEncoding, 'utf16le', 1, execaSync);74-test('can pass encoding "latin1" to stdout - sync', checkEncoding, 'latin1', 1, execaSync);75-test('can pass encoding "ascii" to stdout - sync', checkEncoding, 'ascii', 1, execaSync);76-test('can pass encoding "hex" to stdout - sync', checkEncoding, 'hex', 1, execaSync);77-test('can pass encoding "base64" to stdout - sync', checkEncoding, 'base64', 1, execaSync);78-test('can pass encoding "base64url" to stdout - sync', checkEncoding, 'base64url', 1, execaSync);79-test('can pass encoding "buffer" to stderr - sync', checkEncoding, 'buffer', 2, execaSync);80-test('can pass encoding "utf8" to stderr - sync', checkEncoding, 'utf8', 2, execaSync);81-test('can pass encoding "utf16le" to stderr - sync', checkEncoding, 'utf16le', 2, execaSync);82-test('can pass encoding "latin1" to stderr - sync', checkEncoding, 'latin1', 2, execaSync);83-test('can pass encoding "ascii" to stderr - sync', checkEncoding, 'ascii', 2, execaSync);84-test('can pass encoding "hex" to stderr - sync', checkEncoding, 'hex', 2, execaSync);85-test('can pass encoding "base64" to stderr - sync', checkEncoding, 'base64', 2, execaSync);86-test('can pass encoding "base64url" to stderr - sync', checkEncoding, 'base64url', 2, execaSync);87-test('can pass encoding "buffer" to stdio[*] - sync', checkEncoding, 'buffer', 3, execaSync);88-test('can pass encoding "utf8" to stdio[*] - sync', checkEncoding, 'utf8', 3, execaSync);89-test('can pass encoding "utf16le" to stdio[*] - sync', checkEncoding, 'utf16le', 3, execaSync);90-test('can pass encoding "latin1" to stdio[*] - sync', checkEncoding, 'latin1', 3, execaSync);91-test('can pass encoding "ascii" to stdio[*] - sync', checkEncoding, 'ascii', 3, execaSync);92-test('can pass encoding "hex" to stdio[*] - sync', checkEncoding, 'hex', 3, execaSync);93-test('can pass encoding "base64" to stdio[*] - sync', checkEncoding, 'base64', 3, execaSync);94-test('can pass encoding "base64url" to stdio[*] - sync', checkEncoding, 'base64url', 3, execaSync);48+test('can pass encoding "buffer" to stdout', () => checkEncoding('buffer', 1, execa));49+test('can pass encoding "utf8" to stdout', () => checkEncoding('utf8', 1, execa));50+test('can pass encoding "utf16le" to stdout', () => checkEncoding('utf16le', 1, execa));51+test('can pass encoding "latin1" to stdout', () => checkEncoding('latin1', 1, execa));52+test('can pass encoding "ascii" to stdout', () => checkEncoding('ascii', 1, execa));53+test('can pass encoding "hex" to stdout', () => checkEncoding('hex', 1, execa));54+test('can pass encoding "base64" to stdout', () => checkEncoding('base64', 1, execa));55+test('can pass encoding "base64url" to stdout', () => checkEncoding('base64url', 1, execa));56+test('can pass encoding "buffer" to stderr', () => checkEncoding('buffer', 2, execa));57+test('can pass encoding "utf8" to stderr', () => checkEncoding('utf8', 2, execa));58+test('can pass encoding "utf16le" to stderr', () => checkEncoding('utf16le', 2, execa));59+test('can pass encoding "latin1" to stderr', () => checkEncoding('latin1', 2, execa));60+test('can pass encoding "ascii" to stderr', () => checkEncoding('ascii', 2, execa));61+test('can pass encoding "hex" to stderr', () => checkEncoding('hex', 2, execa));62+test('can pass encoding "base64" to stderr', () => checkEncoding('base64', 2, execa));63+test('can pass encoding "base64url" to stderr', () => checkEncoding('base64url', 2, execa));64+test('can pass encoding "buffer" to stdio[*]', () => checkEncoding('buffer', 3, execa));65+test('can pass encoding "utf8" to stdio[*]', () => checkEncoding('utf8', 3, execa));66+test('can pass encoding "utf16le" to stdio[*]', () => checkEncoding('utf16le', 3, execa));67+test('can pass encoding "latin1" to stdio[*]', () => checkEncoding('latin1', 3, execa));68+test('can pass encoding "ascii" to stdio[*]', () => checkEncoding('ascii', 3, execa));69+test('can pass encoding "hex" to stdio[*]', () => checkEncoding('hex', 3, execa));70+test('can pass encoding "base64" to stdio[*]', () => checkEncoding('base64', 3, execa));71+test('can pass encoding "base64url" to stdio[*]', () => checkEncoding('base64url', 3, execa));72+test('can pass encoding "buffer" to stdout - sync', () => checkEncoding('buffer', 1, execaSync));73+test('can pass encoding "utf8" to stdout - sync', () => checkEncoding('utf8', 1, execaSync));74+test('can pass encoding "utf16le" to stdout - sync', () => checkEncoding('utf16le', 1, execaSync));75+test('can pass encoding "latin1" to stdout - sync', () => checkEncoding('latin1', 1, execaSync));76+test('can pass encoding "ascii" to stdout - sync', () => checkEncoding('ascii', 1, execaSync));77+test('can pass encoding "hex" to stdout - sync', () => checkEncoding('hex', 1, execaSync));78+test('can pass encoding "base64" to stdout - sync', () => checkEncoding('base64', 1, execaSync));79+test('can pass encoding "base64url" to stdout - sync', () => checkEncoding('base64url', 1, execaSync));80+test('can pass encoding "buffer" to stderr - sync', () => checkEncoding('buffer', 2, execaSync));81+test('can pass encoding "utf8" to stderr - sync', () => checkEncoding('utf8', 2, execaSync));82+test('can pass encoding "utf16le" to stderr - sync', () => checkEncoding('utf16le', 2, execaSync));83+test('can pass encoding "latin1" to stderr - sync', () => checkEncoding('latin1', 2, execaSync));84+test('can pass encoding "ascii" to stderr - sync', () => checkEncoding('ascii', 2, execaSync));85+test('can pass encoding "hex" to stderr - sync', () => checkEncoding('hex', 2, execaSync));86+test('can pass encoding "base64" to stderr - sync', () => checkEncoding('base64', 2, execaSync));87+test('can pass encoding "base64url" to stderr - sync', () => checkEncoding('base64url', 2, execaSync));88+test('can pass encoding "buffer" to stdio[*] - sync', () => checkEncoding('buffer', 3, execaSync));89+test('can pass encoding "utf8" to stdio[*] - sync', () => checkEncoding('utf8', 3, execaSync));90+test('can pass encoding "utf16le" to stdio[*] - sync', () => checkEncoding('utf16le', 3, execaSync));91+test('can pass encoding "latin1" to stdio[*] - sync', () => checkEncoding('latin1', 3, execaSync));92+test('can pass encoding "ascii" to stdio[*] - sync', () => checkEncoding('ascii', 3, execaSync));93+test('can pass encoding "hex" to stdio[*] - sync', () => checkEncoding('hex', 3, execaSync));94+test('can pass encoding "base64" to stdio[*] - sync', () => checkEncoding('base64', 3, execaSync));95+test('can pass encoding "base64url" to stdio[*] - sync', () => checkEncoding('base64url', 3, execaSync));96 96-// eslint-disable-next-line max-params97-const testEncodingInput = async (t, input, expectedStdout, encoding, execaMethod) => {97+const 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 };101 102-test('Can use string input', testEncodingInput, foobarString, foobarString, 'utf8', execa);103-test('Can use Uint8Array input', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execa);104-test('Can use string input, encoding "buffer"', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execa);105-test('Can use Uint8Array input, encoding "buffer"', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execa);106-test('Can use string input, encoding "hex"', testEncodingInput, foobarString, foobarHex, 'hex', execa);107-test('Can use Uint8Array input, encoding "hex"', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execa);108-test('Can use string input, sync', testEncodingInput, foobarString, foobarString, 'utf8', execaSync);109-test('Can use Uint8Array input, sync', testEncodingInput, foobarUint8Array, foobarString, 'utf8', execaSync);110-test('Can use string input, encoding "buffer", sync', testEncodingInput, foobarString, foobarUint8Array, 'buffer', execaSync);111-test('Can use Uint8Array input, encoding "buffer", sync', testEncodingInput, foobarUint8Array, foobarUint8Array, 'buffer', execaSync);112-test('Can use string input, encoding "hex", sync', testEncodingInput, foobarString, foobarHex, 'hex', execaSync);113-test('Can use Uint8Array input, encoding "hex", sync', testEncodingInput, foobarUint8Array, foobarHex, 'hex', execaSync);102+test('Can use string input', () => testEncodingInput(foobarString, foobarString, 'utf8', execa));103+test('Can use Uint8Array input', () => testEncodingInput(foobarUint8Array, foobarString, 'utf8', execa));104+test('Can use string input, encoding "buffer"', () => testEncodingInput(foobarString, foobarUint8Array, 'buffer', execa));105+test('Can use Uint8Array input, encoding "buffer"', () => testEncodingInput(foobarUint8Array, foobarUint8Array, 'buffer', execa));106+test('Can use string input, encoding "hex"', () => testEncodingInput(foobarString, foobarHex, 'hex', execa));107+test('Can use Uint8Array input, encoding "hex"', () => testEncodingInput(foobarUint8Array, foobarHex, 'hex', execa));108+test('Can use string input, sync', () => testEncodingInput(foobarString, foobarString, 'utf8', execaSync));109+test('Can use Uint8Array input, sync', () => testEncodingInput(foobarUint8Array, foobarString, 'utf8', execaSync));110+test('Can use string input, encoding "buffer", sync', () => testEncodingInput(foobarString, foobarUint8Array, 'buffer', execaSync));111+test('Can use Uint8Array input, encoding "buffer", sync', () => testEncodingInput(foobarUint8Array, foobarUint8Array, 'buffer', execaSync));112+test('Can use string input, encoding "hex", sync', () => testEncodingInput(foobarString, foobarHex, 'hex', execaSync));113+test('Can use Uint8Array input, encoding "hex", sync', () => testEncodingInput(foobarUint8Array, foobarHex, 'hex', execaSync));114 115-const testSubprocessEncoding = (t, encoding) => {115+const 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 };121 122-test('Does not modify subprocess.std* encoding, "utf8"', testSubprocessEncoding, 'utf8');123-test('Does not modify subprocess.std* encoding, "utf16le"', testSubprocessEncoding, 'utf16le');124-test('Does not modify subprocess.std* encoding, "buffer"', testSubprocessEncoding, 'buffer');125-test('Does not modify subprocess.std* encoding, "hex"', testSubprocessEncoding, 'hex');126-test('Does not modify subprocess.std* encoding, "base64"', testSubprocessEncoding, 'base64');127-test('Does not modify subprocess.std* encoding, "base64url"', testSubprocessEncoding, 'base64url');128-test('Does not modify subprocess.std* encoding, "latin1"', testSubprocessEncoding, 'latin1');129-test('Does not modify subprocess.std* encoding, "ascii"', testSubprocessEncoding, 'ascii');122+test('Does not modify subprocess.std* encoding, "utf8"', () => testSubprocessEncoding('utf8'));123+test('Does not modify subprocess.std* encoding, "utf16le"', () => testSubprocessEncoding('utf16le'));124+test('Does not modify subprocess.std* encoding, "buffer"', () => testSubprocessEncoding('buffer'));125+test('Does not modify subprocess.std* encoding, "hex"', () => testSubprocessEncoding('hex'));126+test('Does not modify subprocess.std* encoding, "base64"', () => testSubprocessEncoding('base64'));127+test('Does not modify subprocess.std* encoding, "base64url"', () => testSubprocessEncoding('base64url'));128+test('Does not modify subprocess.std* encoding, "latin1"', () => testSubprocessEncoding('latin1'));129+test('Does not modify subprocess.std* encoding, "ascii"', () => testSubprocessEncoding('ascii'));modified:test/transform/encoding-ignored.js+68 added-68 removed
1+import assert from 'node:assert/strict';2 import process from 'node:process';2-import test from 'ava';3+import test from 'node:test';4 import {execa, execaSync} from '../../index.js';5 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';6 import {outputObjectGenerator, addNoopGenerator} from '../helpers/generator.js';7 import {foobarObject} from '../helpers/input.js';8 9 setFixtureDirectory();10 10-const testObjectMode = async (t, addNoopTransform, execaMethod) => {11+const 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 };18 18-test('Other encodings work with transforms that return objects', testObjectMode, false, execa);19-test('Other encodings work with transforms that return objects, noop transform', testObjectMode, true, execa);20-test('Other encodings work with transforms that return objects, sync', testObjectMode, false, execaSync);21-test('Other encodings work with transforms that return objects, noop transform, sync', testObjectMode, true, execaSync);19+test('Other encodings work with transforms that return objects', () => testObjectMode(false, execa));20+test('Other encodings work with transforms that return objects, noop transform', () => testObjectMode(true, execa));21+test('Other encodings work with transforms that return objects, sync', () => testObjectMode(false, execaSync));22+test('Other encodings work with transforms that return objects, noop transform, sync', () => testObjectMode(true, execaSync));23 23-// eslint-disable-next-line max-params24-const testIgnoredEncoding = async (t, stdoutOption, isUndefined, options, execaMethod) => {24+const 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 };28 29 const base64Options = {encoding: 'base64'};30 const linesOptions = {lines: true};31-test('Is ignored with other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, base64Options, execa);32-test('Is ignored with other encodings and ["ignore"]', testIgnoredEncoding, ['ignore'], true, base64Options, execa);33-test('Is ignored with other encodings and "inherit"', testIgnoredEncoding, 'inherit', true, base64Options, execa);34-test('Is ignored with other encodings and ["inherit"]', testIgnoredEncoding, ['inherit'], true, base64Options, execa);35-test('Is ignored with other encodings and 1', testIgnoredEncoding, 1, true, base64Options, execa);36-test('Is ignored with other encodings and [1]', testIgnoredEncoding, [1], true, base64Options, execa);37-test('Is ignored with other encodings and process.stdout', testIgnoredEncoding, process.stdout, true, base64Options, execa);38-test('Is ignored with other encodings and [process.stdout]', testIgnoredEncoding, [process.stdout], true, base64Options, execa);39-test('Is not ignored with other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, base64Options, execa);40-test('Is not ignored with other encodings and ["pipe"]', testIgnoredEncoding, ['pipe'], false, base64Options, execa);41-test('Is not ignored with other encodings and "overlapped"', testIgnoredEncoding, 'overlapped', false, base64Options, execa);42-test('Is not ignored with other encodings and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, base64Options, execa);43-test('Is not ignored with other encodings and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, base64Options, execa);44-test('Is not ignored with other encodings and undefined', testIgnoredEncoding, undefined, false, base64Options, execa);45-test('Is not ignored with other encodings and null', testIgnoredEncoding, null, false, base64Options, execa);46-test('Is ignored with "lines: true" and "ignore"', testIgnoredEncoding, 'ignore', true, linesOptions, execa);47-test('Is ignored with "lines: true" and ["ignore"]', testIgnoredEncoding, ['ignore'], true, linesOptions, execa);48-test('Is ignored with "lines: true" and "inherit"', testIgnoredEncoding, 'inherit', true, linesOptions, execa);49-test('Is ignored with "lines: true" and ["inherit"]', testIgnoredEncoding, ['inherit'], true, linesOptions, execa);50-test('Is ignored with "lines: true" and 1', testIgnoredEncoding, 1, true, linesOptions, execa);51-test('Is ignored with "lines: true" and [1]', testIgnoredEncoding, [1], true, linesOptions, execa);52-test('Is ignored with "lines: true" and process.stdout', testIgnoredEncoding, process.stdout, true, linesOptions, execa);53-test('Is ignored with "lines: true" and [process.stdout]', testIgnoredEncoding, [process.stdout], true, linesOptions, execa);54-test('Is not ignored with "lines: true" and "pipe"', testIgnoredEncoding, 'pipe', false, linesOptions, execa);55-test('Is not ignored with "lines: true" and ["pipe"]', testIgnoredEncoding, ['pipe'], false, linesOptions, execa);56-test('Is not ignored with "lines: true" and "overlapped"', testIgnoredEncoding, 'overlapped', false, linesOptions, execa);57-test('Is not ignored with "lines: true" and ["overlapped"]', testIgnoredEncoding, ['overlapped'], false, linesOptions, execa);58-test('Is not ignored with "lines: true" and ["inherit", "pipe"]', testIgnoredEncoding, ['inherit', 'pipe'], false, linesOptions, execa);59-test('Is not ignored with "lines: true" and undefined', testIgnoredEncoding, undefined, false, linesOptions, execa);60-test('Is not ignored with "lines: true" and null', testIgnoredEncoding, null, false, linesOptions, execa);61-test('Is ignored with "lines: true", other encodings and "ignore"', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execa);62-test('Is not ignored with "lines: true", other encodings and "pipe"', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execa);63-test('Is ignored with other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, base64Options, execaSync);64-test('Is ignored with other encodings and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, base64Options, execaSync);65-test('Is ignored with other encodings and "inherit", sync', testIgnoredEncoding, 'inherit', true, base64Options, execaSync);66-test('Is ignored with other encodings and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, base64Options, execaSync);67-test('Is ignored with other encodings and 1, sync', testIgnoredEncoding, 1, true, base64Options, execaSync);68-test('Is ignored with other encodings and [1], sync', testIgnoredEncoding, [1], true, base64Options, execaSync);69-test('Is ignored with other encodings and process.stdout, sync', testIgnoredEncoding, process.stdout, true, base64Options, execaSync);70-test('Is ignored with other encodings and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, base64Options, execaSync);71-test('Is not ignored with other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, base64Options, execaSync);72-test('Is not ignored with other encodings and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, base64Options, execaSync);73-test('Is not ignored with other encodings and undefined, sync', testIgnoredEncoding, undefined, false, base64Options, execaSync);74-test('Is not ignored with other encodings and null, sync', testIgnoredEncoding, null, false, base64Options, execaSync);75-test('Is ignored with "lines: true" and "ignore", sync', testIgnoredEncoding, 'ignore', true, linesOptions, execaSync);76-test('Is ignored with "lines: true" and ["ignore"], sync', testIgnoredEncoding, ['ignore'], true, linesOptions, execaSync);77-test('Is ignored with "lines: true" and "inherit", sync', testIgnoredEncoding, 'inherit', true, linesOptions, execaSync);78-test('Is ignored with "lines: true" and ["inherit"], sync', testIgnoredEncoding, ['inherit'], true, linesOptions, execaSync);79-test('Is ignored with "lines: true" and 1, sync', testIgnoredEncoding, 1, true, linesOptions, execaSync);80-test('Is ignored with "lines: true" and [1], sync', testIgnoredEncoding, [1], true, linesOptions, execaSync);81-test('Is ignored with "lines: true" and process.stdout, sync', testIgnoredEncoding, process.stdout, true, linesOptions, execaSync);82-test('Is ignored with "lines: true" and [process.stdout], sync', testIgnoredEncoding, [process.stdout], true, linesOptions, execaSync);83-test('Is not ignored with "lines: true" and "pipe", sync', testIgnoredEncoding, 'pipe', false, linesOptions, execaSync);84-test('Is not ignored with "lines: true" and ["pipe"], sync', testIgnoredEncoding, ['pipe'], false, linesOptions, execaSync);85-test('Is not ignored with "lines: true" and undefined, sync', testIgnoredEncoding, undefined, false, linesOptions, execaSync);86-test('Is not ignored with "lines: true" and null, sync', testIgnoredEncoding, null, false, linesOptions, execaSync);87-test('Is ignored with "lines: true", other encodings and "ignore", sync', testIgnoredEncoding, 'ignore', true, {...base64Options, ...linesOptions}, execaSync);88-test('Is not ignored with "lines: true", other encodings and "pipe", sync', testIgnoredEncoding, 'pipe', false, {...base64Options, ...linesOptions}, execaSync);31+test('Is ignored with other encodings and "ignore"', () => testIgnoredEncoding('ignore', true, base64Options, execa));32+test('Is ignored with other encodings and ["ignore"]', () => testIgnoredEncoding(['ignore'], true, base64Options, execa));33+test('Is ignored with other encodings and "inherit"', () => testIgnoredEncoding('inherit', true, base64Options, execa));34+test('Is ignored with other encodings and ["inherit"]', () => testIgnoredEncoding(['inherit'], true, base64Options, execa));35+test('Is ignored with other encodings and 1', () => testIgnoredEncoding(1, true, base64Options, execa));36+test('Is ignored with other encodings and [1]', () => testIgnoredEncoding([1], true, base64Options, execa));37+test('Is ignored with other encodings and process.stdout', () => testIgnoredEncoding(process.stdout, true, base64Options, execa));38+test('Is ignored with other encodings and [process.stdout]', () => testIgnoredEncoding([process.stdout], true, base64Options, execa));39+test('Is not ignored with other encodings and "pipe"', () => testIgnoredEncoding('pipe', false, base64Options, execa));40+test('Is not ignored with other encodings and ["pipe"]', () => testIgnoredEncoding(['pipe'], false, base64Options, execa));41+test('Is not ignored with other encodings and "overlapped"', () => testIgnoredEncoding('overlapped', false, base64Options, execa));42+test('Is not ignored with other encodings and ["overlapped"]', () => testIgnoredEncoding(['overlapped'], false, base64Options, execa));43+test('Is not ignored with other encodings and ["inherit", "pipe"]', () => testIgnoredEncoding(['inherit', 'pipe'], false, base64Options, execa));44+test('Is not ignored with other encodings and undefined', () => testIgnoredEncoding(undefined, false, base64Options, execa));45+test('Is not ignored with other encodings and null', () => testIgnoredEncoding(null, false, base64Options, execa));46+test('Is ignored with "lines: true" and "ignore"', () => testIgnoredEncoding('ignore', true, linesOptions, execa));47+test('Is ignored with "lines: true" and ["ignore"]', () => testIgnoredEncoding(['ignore'], true, linesOptions, execa));48+test('Is ignored with "lines: true" and "inherit"', () => testIgnoredEncoding('inherit', true, linesOptions, execa));49+test('Is ignored with "lines: true" and ["inherit"]', () => testIgnoredEncoding(['inherit'], true, linesOptions, execa));50+test('Is ignored with "lines: true" and 1', () => testIgnoredEncoding(1, true, linesOptions, execa));51+test('Is ignored with "lines: true" and [1]', () => testIgnoredEncoding([1], true, linesOptions, execa));52+test('Is ignored with "lines: true" and process.stdout', () => testIgnoredEncoding(process.stdout, true, linesOptions, execa));53+test('Is ignored with "lines: true" and [process.stdout]', () => testIgnoredEncoding([process.stdout], true, linesOptions, execa));54+test('Is not ignored with "lines: true" and "pipe"', () => testIgnoredEncoding('pipe', false, linesOptions, execa));55+test('Is not ignored with "lines: true" and ["pipe"]', () => testIgnoredEncoding(['pipe'], false, linesOptions, execa));56+test('Is not ignored with "lines: true" and "overlapped"', () => testIgnoredEncoding('overlapped', false, linesOptions, execa));57+test('Is not ignored with "lines: true" and ["overlapped"]', () => testIgnoredEncoding(['overlapped'], false, linesOptions, execa));58+test('Is not ignored with "lines: true" and ["inherit", "pipe"]', () => testIgnoredEncoding(['inherit', 'pipe'], false, linesOptions, execa));59+test('Is not ignored with "lines: true" and undefined', () => testIgnoredEncoding(undefined, false, linesOptions, execa));60+test('Is not ignored with "lines: true" and null', () => testIgnoredEncoding(null, false, linesOptions, execa));61+test('Is ignored with "lines: true", other encodings and "ignore"', () => testIgnoredEncoding('ignore', true, {...base64Options, ...linesOptions}, execa));62+test('Is not ignored with "lines: true", other encodings and "pipe"', () => testIgnoredEncoding('pipe', false, {...base64Options, ...linesOptions}, execa));63+test('Is ignored with other encodings and "ignore", sync', () => testIgnoredEncoding('ignore', true, base64Options, execaSync));64+test('Is ignored with other encodings and ["ignore"], sync', () => testIgnoredEncoding(['ignore'], true, base64Options, execaSync));65+test('Is ignored with other encodings and "inherit", sync', () => testIgnoredEncoding('inherit', true, base64Options, execaSync));66+test('Is ignored with other encodings and ["inherit"], sync', () => testIgnoredEncoding(['inherit'], true, base64Options, execaSync));67+test('Is ignored with other encodings and 1, sync', () => testIgnoredEncoding(1, true, base64Options, execaSync));68+test('Is ignored with other encodings and [1], sync', () => testIgnoredEncoding([1], true, base64Options, execaSync));69+test('Is ignored with other encodings and process.stdout, sync', () => testIgnoredEncoding(process.stdout, true, base64Options, execaSync));70+test('Is ignored with other encodings and [process.stdout], sync', () => testIgnoredEncoding([process.stdout], true, base64Options, execaSync));71+test('Is not ignored with other encodings and "pipe", sync', () => testIgnoredEncoding('pipe', false, base64Options, execaSync));72+test('Is not ignored with other encodings and ["pipe"], sync', () => testIgnoredEncoding(['pipe'], false, base64Options, execaSync));73+test('Is not ignored with other encodings and undefined, sync', () => testIgnoredEncoding(undefined, false, base64Options, execaSync));74+test('Is not ignored with other encodings and null, sync', () => testIgnoredEncoding(null, false, base64Options, execaSync));75+test('Is ignored with "lines: true" and "ignore", sync', () => testIgnoredEncoding('ignore', true, linesOptions, execaSync));76+test('Is ignored with "lines: true" and ["ignore"], sync', () => testIgnoredEncoding(['ignore'], true, linesOptions, execaSync));77+test('Is ignored with "lines: true" and "inherit", sync', () => testIgnoredEncoding('inherit', true, linesOptions, execaSync));78+test('Is ignored with "lines: true" and ["inherit"], sync', () => testIgnoredEncoding(['inherit'], true, linesOptions, execaSync));79+test('Is ignored with "lines: true" and 1, sync', () => testIgnoredEncoding(1, true, linesOptions, execaSync));80+test('Is ignored with "lines: true" and [1], sync', () => testIgnoredEncoding([1], true, linesOptions, execaSync));81+test('Is ignored with "lines: true" and process.stdout, sync', () => testIgnoredEncoding(process.stdout, true, linesOptions, execaSync));82+test('Is ignored with "lines: true" and [process.stdout], sync', () => testIgnoredEncoding([process.stdout], true, linesOptions, execaSync));83+test('Is not ignored with "lines: true" and "pipe", sync', () => testIgnoredEncoding('pipe', false, linesOptions, execaSync));84+test('Is not ignored with "lines: true" and ["pipe"], sync', () => testIgnoredEncoding(['pipe'], false, linesOptions, execaSync));85+test('Is not ignored with "lines: true" and undefined, sync', () => testIgnoredEncoding(undefined, false, linesOptions, execaSync));86+test('Is not ignored with "lines: true" and null, sync', () => testIgnoredEncoding(null, false, linesOptions, execaSync));87+test('Is ignored with "lines: true", other encodings and "ignore", sync', () => testIgnoredEncoding('ignore', true, {...base64Options, ...linesOptions}, execaSync));88+test('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
1-import test from 'ava';1+import assert from 'node:assert/strict';2+import test from 'node:test';3 import {execa, execaSync} from '../../index.js';4 import {setFixtureDirectory} from '../helpers/fixtures-directory.js';5 import {noopGenerator, getOutputsGenerator, addNoopGenerator} from '../helpers/generator.js';6 import {7 unmodified lines14 setFixtureDirectory();15 16 const foobarArray = ['fo', 'ob', 'ar', '..'];17 17-const testMultibyteCharacters = async (t, objectMode, addNoopTransform, execaMethod) => {18+const 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 };30 30-test('Handle multibyte characters', testMultibyteCharacters, false, false, execa);31-test('Handle multibyte characters, noop transform', testMultibyteCharacters, false, true, execa);32-test('Handle multibyte characters, with objectMode', testMultibyteCharacters, true, false, execa);33-test('Handle multibyte characters, with objectMode, noop transform', testMultibyteCharacters, true, true, execa);34-test('Handle multibyte characters, sync', testMultibyteCharacters, false, false, execaSync);35-test('Handle multibyte characters, noop transform, sync', testMultibyteCharacters, false, true, execaSync);36-test('Handle multibyte characters, with objectMode, sync', testMultibyteCharacters, true, false, execaSync);37-test('Handle multibyte characters, with objectMode, noop transform, sync', testMultibyteCharacters, true, true, execaSync);31+test('Handle multibyte characters', () => testMultibyteCharacters(false, false, execa));32+test('Handle multibyte characters, noop transform', () => testMultibyteCharacters(false, true, execa));33+test('Handle multibyte characters, with objectMode', () => testMultibyteCharacters(true, false, execa));34+test('Handle multibyte characters, with objectMode, noop transform', () => testMultibyteCharacters(true, true, execa));35+test('Handle multibyte characters, sync', () => testMultibyteCharacters(false, false, execaSync));36+test('Handle multibyte characters, noop transform, sync', () => testMultibyteCharacters(false, true, execaSync));37+test('Handle multibyte characters, with objectMode, sync', () => testMultibyteCharacters(true, false, execaSync));38+test('Handle multibyte characters, with objectMode, noop transform, sync', () => testMultibyteCharacters(true, true, execaSync));39 39-const testMultibyte = async (t, objectMode, execaMethod) => {40+const 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 };49 49-test('Generator handles multibyte characters with Uint8Array', testMultibyte, false, execa);50-test('Generator handles multibyte characters with Uint8Array, objectMode', testMultibyte, true, execa);51-test('Generator handles multibyte characters with Uint8Array, sync', testMultibyte, false, execaSync);52-test('Generator handles multibyte characters with Uint8Array, objectMode, sync', testMultibyte, true, execaSync);50+test('Generator handles multibyte characters with Uint8Array', () => testMultibyte(false, execa));51+test('Generator handles multibyte characters with Uint8Array, objectMode', () => testMultibyte(true, execa));52+test('Generator handles multibyte characters with Uint8Array, sync', () => testMultibyte(false, execaSync));53+test('Generator handles multibyte characters with Uint8Array, objectMode, sync', () => testMultibyte(true, execaSync));54 54-const testMultibytePartial = async (t, objectMode, execaMethod) => {55+const 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 };64 64-test('Generator handles partial multibyte characters with Uint8Array', testMultibytePartial, false, execa);65-test('Generator handles partial multibyte characters with Uint8Array, objectMode', testMultibytePartial, true, execa);66-test('Generator handles partial multibyte characters with Uint8Array, sync', testMultibytePartial, false, execaSync);67-test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', testMultibytePartial, true, execaSync);65+test('Generator handles partial multibyte characters with Uint8Array', () => testMultibytePartial(false, execa));66+test('Generator handles partial multibyte characters with Uint8Array, objectMode', () => testMultibytePartial(true, execa));67+test('Generator handles partial multibyte characters with Uint8Array, sync', () => testMultibytePartial(false, execaSync));68+test('Generator handles partial multibyte characters with Uint8Array, objectMode, sync', () => testMultibytePartial(true, execaSync));69 69-const testMultibytePartialOutput = async (t, execaMethod) => {70+const 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 };79 79-test('Generator handles output multibyte characters with Uint8Array', testMultibytePartialOutput, execa);80-test('Generator handles output multibyte characters with Uint8Array, sync', testMultibytePartialOutput, execaSync);80+test('Generator handles output multibyte characters with Uint8Array', () => testMultibytePartialOutput(execa));81+test('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 lines4 "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 lines17 },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 lines53 "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 line71 "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 lines84 "**/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 }